What happens if you change your database credentials?

Right now your class is tied to a specific set of database credentials, and you'll need to change it if:

you want to use a different engine,
or a different host,
or a different user,
or a different password,
or any combination of the above.

This is why PDO requires you to pass the dsn and the credentials through its constructor, and you should do the same. Then of course your class wouldn't be much different than PDO itself, if you don't have any additional functionality, just forget about it and use PDO.

If you want to keep your class, just store your credentials in a configuration file. A simplistic solution would be an INI file, let's call it database.ini:

engine   = "mysql"
host     = "localhost"
name     = "test"
user     = "root"
password = ""

Your database class could then be:

class DB {
    private $pdo;
    private $engine;
    private $host;
    private $db_name;
    private $db_user;
    private $db_passwd;

    public function _construct($path) {
        if(!is_file($path)) {
            throw new InvalidArgumentException("Hey, that's not a file!");
        }

        $credentials = @parse_ini_file($path);

        if(empty($credentials)) {
            throw new InvalidArgumentException("Hey, that's a file, but it's not a valid INI file!");
        }

        $this->engine    = $credentials["engine"];
        $this->host      = $credentials["host"];
        $this->db_name   = $credentials["name"];
        $this->db_user   = $credentials["user"];
        $this->db_passwd = $credentials["password"];

        try {
            $this->pdo = new PDO($this->engine.':host='.$this->host.';dbname='.$this->db_name,$this->db_user,$this->db_passwd);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $this->pdo;
        }   catch(PDOException $e) {
            throw new Exception("Boo, wrong credentials!");
        }
    }

}

Looks like a lot of work? Well, it is, and it's not finished, but changing any of your credentials is now as simple as changing its value in database.ini. All you need to do to instantiate your class is:

$db = new DB("database.ini");

Let's go quickly through the main parts of the class:

Don't protect what should be private

Don't declare your class properties and methods as protected if you don't need to. Protected means:

  Members declared protected can be accessed only within the class itself and by inherited and parent classes

If you are not going to extend the class, there's absolutely no reason to go with protected instead of private:

  Members declared as private may only be accessed by the class that defines the member.

This might seem extremely pedantic, the world won't stop spinning because your properties are protected, but since you're a fresher, better avoid this common bad habit.
Connect? Why, let's construct instead!

The database class is useless if we don't run connect(), calling the method is a prerequisite for the class to do anything else. When that happens, it's a good sign that our method should either be called in the class constructor, or be the constructor itself. If it's absolutely necessary for the method to be called, then it makes sense to be the one function that gets called by default when we create an instance of our class, doesn't it?
Check your arguments

I'm doing two checks on our $path argument, first if it's a valid file and then if parse_ini_file returned an array (that would signify that the INI file was succesfully parsed). Throw appropriate exceptions if there are problems.
The unfinished part

$this->engine    = $credentials["engine"];
$this->host      = $credentials["host"];
$this->db_name   = $credentials["name"];
$this->db_user   = $credentials["user"];
$this->db_passwd = $credentials["password"];

What I'm not doing here is check whether the indices exists in the $credentials array. That's your homework ;)
The exception

Your original code was:

} catch(PDOException $e) {
    die($e->getMessage());
}

That doesn't make sense, you catch the exception and then die with the same message? Not catching the exception will have exactly the same effect, the script will stop, so why catch it? You should catch exceptions only when you can do something productive with them, if not, just let the script fail. Usually "something productive" means gracefully recover from the error, but that's not always possible. In my code I'm doing something that might seem minor but it's very important:

}   catch(PDOException $e) {
    throw new Exception("Boo, wrong credentials!");
}

Yes, the only thing I'm doing is changing the message of the exception, the script will still fail. However PDO's constructor exception reveals your database credentials (except your password), so catching that and rethrowing it with a more generic message minimizes the risk of your database username (for example) falling in the wrong hands. Can't gracefully recover from the failure, but at least we plugged a potential security hole.

How about some setters and getters?

If you are still reading this, I'm sorry to inform you that your code doesn't work. This:

public function __construct() {
    $pdoObj = new DB();
    $this->link = $pdoObj->connect();
    return $this->link;
}

does set your database object in the $link property but it's your database object, not your PDO object. Your database object does not have a prepare() method, so this:

$query = $this->link->prepare("INSERT INTO users(username, email, password, ip_address, activation_code)
                                VALUES(:username, :email, :passwd, :ip_addr, :code)");

will simply fail. What you need to do is pass your PDO object to your User class:

class DB {

    ...

    public function getPDO() {
        return $this->pdo;
    }
}

So this simple function will always return the database's internal PDO object. Your User constructor would now be:

public function __construct() {
    $database = new DB("database.ini");

    $this->link = $database->getPDO();
}

Notice how I removed return $this->link;? Well, don't do that, a constructor returns the object it instantiates by default, there's absolutely no sense in returning anything else, it wouldn't be a constructor if it didn't give us what it constructed, would it?

Wait! There's a dependency!

This line:

$database = new DB("database.ini");

means that we don't have the option of renaming our INI file. Ever! That's not good, that's an unwanted dependency and we really don't like those. After all we went through a lot to get our database class to not be dependent on its credentials, we can't introduce another dependency now. What we are going to do is use a method called Constructor Dependency Injection, that's the simplest way to achieve Dependency Injection. It's extremely simple, all we need to do is:

public function __construct(DB $database) {
    $this->link = $database->getPDO();
}

That's right, pass the database as a parameter in the constructor, that's all there is to it. Now, to instantiate our user class all we need to do is:

$database = new DB("database.ini");
$user = new User($database);

...and our classes are dependency free! To get an idea why this is good, assume you have two databases, and you need to use them both. All you need to do is:

$database1 = new DB("database1.ini");
$user1 = new User($database1);

$database2 = new DB("database2.ini");
$user2 = new User($database2);

Does your database only have users?

If your database has any other table, and you want to model them as classes, it might be worth looking at inheritance. All your table classes have a common dependency, the database, and you don't really have to write the same constructor every time:

class Table {
    protected $database;

    public function __construct(DB $database) {
        $this->database = $database->getPDO();
    }
}

class User extends Table {

    // only user specific functions here

}

class Article extends Table {

    // only article specific functions here

}

class Comment extends Table {

    // only comment specific functions here

}

The User, Article, and Comment classes have inherited the same constructor from Table, no need to write the method more than once. As you probably already noticed, I've declared $database protected, it makes sense now as we need it to be available to the child classes. By the way that's your old $link property, since it holds a database object, makes sense to call it $database.

The register function

Sorry for being blunt, but this is a horrible mess:

Indendation is messed up.

Learn to format your code properly. Better yet, equip yourself with a decent tool to do it for you.
Your function should either return something or echo something, not both.

Preferably return something. Echoing HTML from your functions is a very poor practice, read up on separation of concerns. Simply put your function is where you put logic, and you shouldn't mix presentation with logic.
You catch an exception and die with the same message again.

Don't do that.

Since we've now have a handy getter in our database class, the way to get the reference to the PDO object in your function is:

class User {

    public function register($username, $email, $passwd, $re_passwd) {
        $link = $this->database->getPDO();

        ...

        $query = $link->prepare( ... );

        ...
    }

}

And what about static?

Well, don't worry about it. Most of the time is used as a convenience, and it's not really the better way to do things. Instantiate your objects properly, and then pass them around via one of the dependency injection techniques, you're passing around the same instance, you are not instantiating it again and again.

Further reading

Classes and Objects in the manual. Yes, you need to read everything.
Data Filtering in the manual. Again, you need to read everything.
Mutator methods.
SOLID - Don't cheat, read all the linked articles.
Inversion of Control Containers and the Dependency Injection pattern
KISS and YAGNI

Addendum

Corbin raises two important issues in a comment:

  (1) The exception shouldn't be masked. What if consuming code wants the details? A different part of code should be responsible for hiding potentially sensitive exceptions. (2) If Table (and other classes) need a PDO instance, they should accept a PDO instance, not a DB instance. There's no reason to accept the object just to call a single getter. (I also believe that this Database class shouldn't even exist though. It's pointless.)

My thoughts:

Your database class is pointless if it doesn't have any additional functionality you didn't tell us about.

As it is, it's just a wrapper for PDO that doesn't do anything more than PDO itself does, and in my answer I've assumed (hoped?) that you do have a reason for it and would further develop it to enhance PDO (perhaps adding a query cache, or a log?). But if you don't have any further plans for it, then it would be preferable to just scrap it and just use PDO and just feed your PDO object in Table::__construct().
You shouldn't be catching exceptions if you can't do anything productive, preferably gracefully recovering from the error.

Now, I do suggest that you should catch the PDOException just in case your database credentials are leaked, but that's more of a scare tactic than a solid suggestion. I've seen one too many new developers do similar mistakes, and perhaps my suggestion there was a bit drastic.

What you need to keep in mind is that this particular PDOException should not reach the end user. If there's other code in between your database instantiation and the end user (a top level script, perhaps), it would make much more sense to deal with the exception there, and if you can't recover from it do something like throwing a 404 or 503 error (whichever applies).

Take my suggestion to hide the details of the connection PDOException with a grain of salt, I'm just tired of dealing with the same crap again and again. There was a time when such an exception created a world of trouble for me, but in a typical production environment it shouldn't be easy for anyone to do anything particularly harmful just because they caught a glimpse of your database username.


Calculating the surrounding objects in a two-dimensional coordinate system leaving out the corners

This code is extremely hard to read and much longer than it needs to be.
Use documented naming conventions for C#.
Make small methods that do one thing well.

public bool IsWall(int x, int y)
{
  return this.MyWorld.GetObjectOnPosition(x, y) is Wall;
}
public bool IsValidForEditing()
{
  int x = this.X;
  int y = this.Y;
  return
    !IsWall(x-1, y) || !IsWall(x, y-1) ||
    !IsWall(x+1, y) || !IsWall(x, y+1);
}

Anyone who knows even basic C# -- or any C-like language -- can read this code and immediately understand what it means. Your original code, not so much.

Any time you write a loop, ask yourself "would this be more clear without the loop?"  Odds are good, yes. In this case, definitely.


Script to drop HTML part of multipart/mixed e-mails

I think the code is quite fine as it is. Some small notes:

if composition == (TEXTPLAIN + TEXTHTML) or composition == TEXTPLAIN:

Just to make sure: this code tests that TEXTPLAIN is set and that MISCPARTS is not set. I would make that explicit, otherwise this code is hard to understand (in particular, it’s easy to miss that MISCPARTS mustn’t be set):

if (composition & TEXTPLAIN) != 0 and (composition & MISCPARTS) == 0:

If you’re not happy with bit operations, you can a set instead.

composition = set()

# …

if TEXTPLAIN in composition and MISCPARTS not in composition:

… and define TEXTPLAIN etc. as simple consecutive constants rather than bitmasks.

This is more pythonic certainly, but I actually find the use of bit masks entirely appropriate here.


Getting an array of certain objects within an object

Your nested "ifs" make the code very hard to read.  I would think about changing your approach to something like

if (undefined === vm.masterFormObject) {
    console.log('Some error message.');
    return;
}
if (undefined === vm.masterFormObject.payload) {
    console.log('Some other message');
    return;
}
// and so on

// or if inside a loop
if (undefined === account.Forms) {
    console.log('Some error message.');
    // continue to next iteration
    continue;
}


If you want absolute performance

You could avoid printing anything at all. Since that can be slow in some cases. If you absolutly need to know at least what happened you could try flushing at the end of the process.
I know with python is delicated, but you could try visiting multiple pages at the same time? Threads or the equivalent in python


Avoid storing data unnecessarily
Your class stores the start time, stop time and frequency in member variables, however you only need to store the start time:
class Timer {
    LARGE_INTEGER start_count;

public:
    // Query performance counter at the start of a block of code
    void start() {
        QueryPerformanceCounter(&start_count);
    }

    // Query the performance counter at the end of a block of code, then calculate time elapsed in seconds
    double stop() {
        LARGE_INTEGER stop_count;
        QueryPerformanceCounter(&stop_count);

        LARGE_INTEGER tick_freq_count;
        QueryPerformanceFrequency(&tick_freq);
        return (double)(stop_count.QuadPart - start_count.QuadPart) / tick_freq.QuadPart;
    }
};

Consider using std::chrono functions
If you can use C++11 or later, then you should be able to get the same timing information in a platform-independent way by using std::chrono::high_resolution_clock. See this example for how it can be used.
Accuracy
The actual accuracy depends on many things. The inherent accuracy depends on the accuracy of the performance counter of the CPU, which can vary between models. However, there are many reasons why the measured time will vary, among them are:

The state of the cache (as suggested by Casey, you should do a warm-up run before doing the actual performance measurements)
The CPU frequency changes (the OS will normally adjust the frequency many times per second to ensure your processor runs as energy efficient as possible)
Other threads might get a timeslice while your code is running

You could try to address all these issues yourself (many of them are solved by doing a warm-up run, then running your performance measurements many times and taking the average, removing outliers in some way). Alternatively, consider using existing libraries that already solve this problem, for example Google Benchmark.


Your foldr solution doesn't work because it's using the empty list you're passing in the final step. You can use foldr1 instead, it uses the final element of the list in place of being passed an accumulator value.

Looking to the folds to implement unwords isn't a bad idea, but there are other high-level functions that you can use to write a more terse or readable version. Let's start from a verbal description of what unwords is doing.

  Insert a space character between every String in a list, then join the resulting Strings together.

The latter half of that description is easy, we know that String is really [Char], and we can easily flatten doubly-nested lists with concat. The former portion we could implement on our own, or search Hoogle for to see if anything already exists in the Prelude or other modules that could help us out. In this case, we're looking for a function with the type a -> [a] -> [a], that is, we want to pass it a value and a list and have it return a list with that value inserted between each pair of elements. As luck would have it, there's a function in Data.List that does exactly what we're looking for called intersperse that comes up as the first result if we perform that search.

Using these two functions, we can write a very short version of unwords that reads almost like prose.

import Data.List (intersperse)
import Prelude hiding (unwords)

unwords :: [String] -> String
unwords = concat . intersperse " "

Besides the aesthetic appeal of this solution, to me this illustrates the power of thinking about what you want to do in Haskell, instead of thinking about how it's going to be done.


Indeed, the values dictionary looks unnecessary. Using a built-in function ord you could compute the letter score with ord(letter) - ord('a') + 1. One may argue that it is even faster than a dictionary lookup, but in this case the timing difference is rather marginal.

With Python you should avoid rolling explicit loops. For example, collecting the word values is more idiomatically expressed as a comprehension:

    word_values = [word_value(word) for word in word_list]

Similarly, instead of

    for letter in input_word:
        value += values[letter]

consider functools.reduce:

    value = functools.reduce(lambda x, y: x + ord(y) - ord('a') + 1, input_word, 0)


Every node in binary tree = sum of subtree

This part of your code could probably be simplified

if (node.getLeft() != null && node.getRight() != null)
{
    if ((Integer) node.getData() != sum)
    {
        return false;
    }
}
else
    return true;

First off, don't do an else statement without curly braces when the corresponding if statement has curly braces, it doesn't follow expected coding practices.

Then you should return early

if (node.getLeft() == null || node.getRight() == null) {
    return true;
} else if ((Integer) node.getData() != sum) {
    return false;
}

As your code is written in the original post it will never hit this statement

return isValid(node.getLeft()) && isValid(node.getRight());

and will always return true, if (node.getLeft() == null || node.getRight() == null)


Split a given number so that their sum adds to another given number

Python 2

Python 2 is end-of-life, and Python 3 has a lot of advantages now:

f-strings
unicode support
...

More info here, here and on many other places.

If you need python 2.7, try to make your code compatible with both.

Split it into functions

You do that to a limited extent with break_down, but you can do it in a lot more places:

parsing the input
breaking the input into parts
calculating the sum of the parts
output

from __future__ import print_function

Parsing the input

you do input("") a lot. If you skip the "", you can test your input parsing with something like

input_str = '''4
15112 28
120012 33
123 123
15489001 10549'''
input = iter(input_str.split('\n')).__next__

In the parsing of the input, you iterate over the string, insert a space between characters and then split on the space, while all you need to do is list(text).

So I would go for:

def parse_input():
    cases = int(input())
    for _ in range(cases):
        question, answer = input().split()
        yield question, answer

list(parse_input())

[('15112', '28'), ('120012', '33'), ('123', '123'), ('15489001', '10549')]

Splitting the input

This is what your break_down does. But you format its answer as a str with spaces between the numbers. Why not just yield the ints immediately with int(''.join(words[i:j])) instead of ' '.join(words[i:j])

instead of words for the collection of digits, I would use digits as name. Same with ns and n, I don't find their purpose clear by their name, but I can't find a good, clear name instantly either.

For python 2 and 3 portability, you will need to do list(range(...)), because you iterate over ns twice

And your solution with zip((0,) + idxs, idxs + (None,)) is also well found, but not clear what exactly it does. The same idea can be made more clear using the pairwise itertools recipe.

def pairwise(iterable):
    '''
    s -> (s0,s1), (s1,s2), (s2, s3), ...
    https://docs.python.org/3/library/itertools.html#itertools-recipes
    '''
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

def break_down(text):
    digits = list(text)
    ns = list(range(1, len(digits))) # n = 1..(n-1)
    for n in ns: # split into 2, 3, 4, ..., n parts.
        for idxs in itertools.combinations(ns, n):
            idxs = (0, *idxs, None)
            yield tuple(int(''.join(digits[i:j])) for i, j in pairwise(idxs))

Calculating the sum

instead of

    x=[int(i) for i in x]

    for i in x:
        #calculating sum
        sum+=i

you can use the builtin sum (if you don't overwrite the name with a variable like here) total = sum(map(int, x) does the same as these original 3 lines.

But since we already got ints from the previous part instead of strings, just sum will do:

def check_sum(question, target):
    for parts in breakdown(question):
        if sum(parts) == target:
            yield parts

formatting the answer can also be more efficient and clear than manually putting '+' between all parts.

def format_answer(answer):
    return '+'.join(map(str, answer))

Putting it together

def solve_query(query):
    question, target = query
    target = int(target)
    answer = next(find_sums(question, target))
    return format_answer(answer)

and then, behind a main guard:

if __name__ == '__main__':
    queries = parse_input()
    for query in queries:
        print(solve_query(answer))


I would consider refactoring the .Select call to do this:

files = files.Union(Directory.GetFiles(year).Select(d => GetTimeForFile(d))).ToList();

Where GetTimeForFile is a method with the following content:

DateTime GetTimeForFile(String fileName)
{
    var noExtName = Path.GetFileNameWithoutExtension(fileName);
    return DateTime.ParseExact(noExtName.Substring(noExtName.Length - 8),
     "yyyyMMdd", null);
}

Either way, no matter how you indent it now, the method extraction of GetTimeForFile makes it significantly more readable.


Memorise array and print number of occurrences

One of the things that's terrible about these types of competitions is that the problems are very contrived. They're written like a math problem, which makes it tempting to write your solutions the same way. I'd do the following things to improve your code.

Formatting

The formatting of your code is very messy. Maybe it's just due to getting used to entering code in the Stack Exchange text field, but even if the tabs were correct, you're not using a lot of white space between statements. I recommend looking at other people's code to see how they use whitespace and adopting a style that you like. The book Code Complete has some useful rules of thumb to use for how to style C code. It's a good place to start from.

Naming

This is the number one thing that most developers could improve (myself included!). Just because the problem description names things like N, Q, and B[i] doesn't mean your code has to use those names. You should strive to use readable names like numEntries, numQueries, and queries.

Your function names aren't great either. check() doesn't tell me what it's doing. What is it checking? It turns out nothing. It's tabulating the number of times z occurs in arr and putting the result into c. It might be better to name it something like tabulateEntries() or something along those lines. Likewise, count() is counting something, right? What is it counting? The number of occurrences of z. So maybe it should be named countOccurences()?

Be Careful With The Stack

You're allocating everything on the stack. This can get you in trouble with longer programs. For example, your declaration of B is using either 400 or 800KB of stack space. The default stack size in many implementations is 1MB, so this would use almost 80% of the stack just in your main() function. It might be wiser to allocate that space on the heap or better yet, only allocate as much as you actually need (which will be q elements instead of 100,000). Same thing with arr.

Avoid Magic Numbers

You have several magic numbers in your code. These are numbers that are hard-coded to specific values. Someone reading your code would have no idea where they come from. You should use named constants or enumerations where appropriate. For example,

const int kMaxQueries = 1000;
const int kUnsetEntry = -1;
const int kInvalidEntry = 9999;

Use structs Where Appropriate

You're using a 2 dimensional array to represent the values and their counts. You should instead use a struct that holds those 2 values and have a 1-dimensional array of those structs. Something like this:

typedef struct ValueCounts {
    int value;
    int count;
} ValueCounts;

Then you can write self-documenting code like this:

int check(int z, ValueCounts counts, int q, int arr[])
{
    int i = 0;
    while (counts[i].value != kUnsetEntry)
    {
        if (z == counts [ i ].value)
        {
            return counts [ i ].count;
        }
        else
        {
            counts [ i ].value = z;
            counts [ i ].count = count(z, arr, q);
            return counts [ i ].count;
        }
        i++;
    }
}

Errors

Notice that your check() function can return an undefined value. If c[i][0] == -1, then the while loop ends, and the function will return whatever's on the stack, which is likely uninitialized memory. Is this why you made c[0][0] have an initial value of 9999? While that works around the problem, it's a bad way to do it.

Performance

Looking at your code, it seems to be doing things the long way. arr is an unsorted array. Tabulating how many occurrences there are of a single value in arr potentially involves looping over the entirety of c processed so far. This can happen for every value in arr. It would probably be faster to sort arr before counting the occurrences of each value. If it were already sorted, you'd be able to just run through arr in order, and as soon as the value changed, you'd fill in the next value in c with the total number of occurrences of the value before the change. That would leave c in order and would allow you to do a binary search of c for getting the values needed to print out the result. That should be considerably faster than the linear search you're currently doing.

In fact, I went to the site and tried the above suggestions and passed the tests in the time allotted. For the sorting, I used the standard library qsort() function. I wrote my own binary search, and it seemed to do the trick.


Parse input string into vector of i16 in Rust

I don't know Rust too well, so take this review with a grain of salt. That being said, your get_input can be heavily simplified if you return. That way we don't need to remember whether the parsed input was valid: if it's valid we just return:

fn get_input() -> Option<Vec<i16>> {
    loop {
        // Get user input.
        print!("Enter series-> ");
        std::io::stdout().flush().unwrap();
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap();

        // Parse it.
        match input.trim() {
            "q" => return None,
            _ => {
                let parsed = parse_input(input);
                if let Ok(out) = parsed {
                    return Some(out);
                }
            }
        }
    }
}

Note that this prevents some errors that were possible before. For example you could have missed to set out and accidentally returned None instead of Some, e.g.

    // ...
    _ => {
        let parsed = parse_input(input);
        if let Ok(_) = parsed {
            valid = true;
            // whoops forgot out
        }
    }

This erroneous state cannot happen now.

Also note that we now have a simple loop. We don't have any mut bindings, only a single if let is left. Also note that we don't need to unwrap parsed: if parsed is an Ok(out), we can use that out.

That being said, you should add an error message after the match, e.g.

match input.trim() {
    // same as above
}
println!("Your input could not get parsed. Please write space-separated numbers or 'q' to quit");


JavaScript Boilerplate - Review comments required

Interesting work Arif. I really loved to see different as well as interesting JS patterns you have used. It is looking to me like, it is going in a good and right direction.

Few things that you might consider to do is

I) Create some example of different modules and ensure they are in different files (it is not very clear with the current example but I assume you have already thought about it).

II) Might be a very personal choice, I don’t like _ in variable and method names. The way I know what is public and what is private is by looking at what is being returned at the bottom, as I use a pattern like below in most occasions

    (function(MODULE, $)  {
       MODULE.charting = function(options) {
          options = $.extend({
              defaultParam1: “a”,
              defaultParam2: “b”
          }, options);

          var xAxis, yAxis;

          function render() {

          }

          function destroy() {

          }

          (function init() {
             //Anything that is suppose to be called when a object of the
             //module is created. Acts like a psuedo constructor.
          })();

          return {
             render: render,
             destroy: destroy
          };
       };
     }(MODULE || {}, jQuery));

What do you think? In above example you can clearly see what is public and they can be exposed with a different name if one wants. So in refactoring it will not break other components as the way it is exposed outside can be different. If you see what I mean.

III) If you are using jQuery, you can use extend like above to define defaults and then override if passed by the user.

IV) Generally I don’t tend to put URLs in JavaScript and prefer to put them on jsp, asp, json response, etc. as then front-end doesn’t need to worry about context/domain/port.

Will send you more comments if I think of any. For the time being have a think about it and let me know your views. Also keep on sharing the progress, would love to see this growing into a very fruitful thing.


Extracting sleep quality scores from periodic readings

First of all the quantities global sounds unnecessary.  The value is
cleared at the start and the value is returned from the function too,
no need to clobber a global.

The way quantity is updated can be written much more concisely by
immediately appending a literal list instead of updating a variable:

quantities.append([hour, day, minute, sleep / total])

Now just another quick suggestion is to use destructuring in the inner
for loop too:

    for (stage, time_string) in scores:

Finally, the ordering of hour, day, minute in the result means that the
normal sort method on a list isn't sufficient to sort the list in a
sensible manner - I'd suggest to put it in decreasing order, i.e. day,
hour, minute.

Edit: Was updated before I ended up posting, but my assumptions still hold I think. (Unfortunately there's not much of an explanation of why this function does what it does.)

However it's immediately a concern that the way the iterations are set
up is less efficient than the other way round: the product list is
4320 elements long, while the scores list is likely much shorter -
that sounds like they should be nested the other way round.

Given that there's no explanation of what the code is supposed to do I'm
going to guess a bit on the semantics.  Now we're iterating over three
days in one minute steps, checking whether any of the elements in
scores match and do something if so.  For total, we accumulate all
the matches for that moment in time and if we got one, we append to the
quantities list.

That means, I think, that you're looking for all timestamps in the list,
which occur at the same moment, then add up the "type" of the timestamp
and append one result for each moment where there were any matches.

That can be written much better in terms of sorting (the timestamps) and
accumulating consecutive ranges instead:

def sleep_quantity2(scores):
    buckets = {}

    for stage, time_string in scores:
        time = datetime.datetime.strptime(time_string, '%d %H:%M:%S')

        stages = buckets.get(time, [0, 0])
        buckets[time] = stages

        stages[0] += 1
        if stage == "R" or stage == "S":
            stages[1] += 1

    quantities = []
    for time, stages in buckets.iteritems():
        quantities.append([time.day, time.hour, time.minute, stages[1] / stages[0]])

    quantities.sort()

    return quantities

The process is thus: accumulate entries into buckets, one bucket for
each moment and at the same time updating the numbers for that bucket,
then at the end, iterating over all buckets and producing the result
list and, since the order is arbitrary, sort them again so it matches
the output of the previous approach.

Now if you want, you can still use yield instead of accumulating the
list in place and use xrange instead of range in Python 2.7.

Oh and run a profiler.

For reference, I ended up comparing it with the following code:

def sleep_quantity1(scores):
    quantities = []
    for day, hour, minute in product(range(1, 4), range(24), range(60)):
        sleep = 0
        total = 0
        for (stage, time_string) in scores:
            time = datetime.datetime.strptime(time_string, '%d %H:%M:%S')
            if time.hour == hour and time.day == day and time.minute == minute:
                total += 1
                if stage == 'S' or stage == 'R':
                    sleep += 1
        if total != 0:
            quantities.append([day, hour, minute, sleep / total])
    return quantities


iOS4 alternatives for dismissViewControllerAnimated:completion:

Two light suggestions:

disappear has one s and two ps.
the word "block" to describe a block is accurate but not very descriptive. OK, so I need to pass a block, but I can see that from the parameter list. What the block is for should be explained in the method name: this is why Apple often uses phrases like "completion handler" or "comparator" to describe block parameters.


Replacing birth year column values with calculated age value

First, as dnoeth commented, why are you doing this job in mass rather than calculating on the fly? You might have a good reason, but you never clarified.  Of course the best way to lighten the load would be not to do this task at all.

Second, as 200_success commented, you are damaging your database design by writing age data into a birth_year column.

If you MUST run this procedure and you MUST overwrite the birth_year, then I have some advice for your single-query approach:

You should consistently use all caps when writing mysql keywords and functions for readability.
You should try to minimize the number function calls and overall length of your query.
Because, I assume, you have covered all potential outcomes with your table data in your CASE conditions, there should be no logical requirement for the null outcome.  Furthermore, because there are only 2 outcomes, I would opt for an IF statement rather than the more verbose CASE statement.
Depending on the possibility of a null value in birth_year, you may need to include another IF or COALESCE call to mitigate that data challenge.

SQL (D.R.Y.):

UPDATE table_name
SET birth_year = YEAR(GETDATE()) - birth_year - IF(birth_month IS NULL OR birth_month <= MONTH(GETDATE()), 0, 1)
FROM table_name


Print element in a linked list in reverse

This approach is fine if you know the linked list will always be less than 100 elements. To fix this issue while still using the same method, you could iterate through the linked list first to count the number of elements needed in your array.

If I were doing this problem, I'd look at using a stack... just push all the elements onto the stack, then pop them all off again to print them. This way we avoid iterating through the linked list twice (once to count, once to store in an array), while still solving to problem.


Recursive function that generates the permutations of a string

Your code seems to be correct, and is written in a good style. However, both the interface of your code as well as the algorithm used can be improved.

You currently have a global variable permutations which also contains the output. This variable will have to be cleared every time before doPerm is invoked. Instead, wrap doPerm in another function that provides initialization and input validation:

function perms(data) {
    if (!(data instanceof Array)) {
        throw new TypeError("input data must be an Array");
    }

    data = data.slice();  // make a copy
    var permutations = [],
        stack = [];

    function doPerm() {
        if (data.length == 0) {
            permutations.push(stack.slice());
        }
        for (var i = 0; i < data.length; i++) {
            var x = data.splice(i, 1);
            stack.push(x);
            doPerm();
            stack.pop();
            data.splice(i, 0, x);
        }
    }

    doPerm();
    return permutations;
}

var input = "abcd".split('');
var result = perms(input);
for (var i = 0; i < result.length; i++) {
    result[i] = result[i].join('');
}
console.log(result);

Note that this function will operate on arrays of any type and does not special-case strings.

Your algorithm currently relies on splicing elements into and out of the input array. This is somewhat expensive on larger data sets, and it would be better to generate the permutations by swapping. Heap's Algorithm does just this.


What would you think of

match_iter = izip(*valid_lists)
rid2 = defaultdict(list)
for qfx, rid, fx, fs, fk in match_iter:
    rid2[rid].append(qfx, fx, fs, fk)

Seems like that might cut the time in the final loop by almost 50%. The extraction from match_iter doesn't change, so it will take the same amount of time. The append will take about the same amount of time as one of the appends you're already doing. Since two appends will be eliminated, I think the time they're taking will go away.


Finding an employee from a given mother company

Ultimately, style considerations are subject to opinion and your actual style usually doesn't matter as much as being consistent. That said, your code might be found more readable if formatted like so:

$scope.getEmployee = function(subsidiary, salaryScale) { //1
    var workingDepartments = []; //2
    var findInGroupOfCompanies = function(comGroup, salaryScale) { //3
        var salaryIndex = subsidiary[salaryScale]; //4
        if (salaryIndex != "SUPERIOR" && salaryIndex == comGroup.salaryIndex) { //5
            if (comGroup.hasSubsidiaries()) { //6
                findInGroupOfCompanies(comGroup, salaryScale++); //7
            } else { //8
                workingDepartments.push(comGroup); //8
                //and do some stuff
            }
        }
    };

It's not necessary to indent findInGroupOfCompanies all the way to align with the equals sign. One additional level of indentation is sufficient to indicate a new block, and anybody reading the code can see that it's a new function declaration.


Something I noticed in your algorithm is that despite using memoization, you are still reassigning the Fibonnacci number into the array every time you calculate it.

You could avoid reassigning by having a function like computeIfAbsent that determines if the Fibonacci for a given n has already been calculated, and if not, use the Fibonacci function to calculate it and put it into the array, but only this time.

Also, we could avoid having to calculate the first two Fibonaccis by having them memoized from the start, and make the code fail for any index n smaller than 0.

memo = [0,1]

computeIfAbsent = (n, f) ->
    fib = memo[n]
    if typeof fib is 'undefined'
        fib = f(n)
        memo[n] = fib
    fib

fibonacci = (x) ->
    if x < 0
        throw Error("Invalid index: " + x)
    computeIfAbsent(x, (n) -> fibonacci(n-1) +  fibonacci(n-2))

console.log("#{i}: #{fibonacci(i)}") for i in [0..79]

Still, you must be aware that this code will not detect arithmetic overflows. It might look like it is calculating it right, but in fact, the calculations could be wrong due to overflow. I think your version and mine start to produce invalid results around 79.

You can check using a Fibonacci Calculator


Recreating Google homepage for learning purposes

Add both buttons in a single <div>, and center that div instead of the buttons individually.


Books Algorithm Dealing with Square Digit Sums

Can someone see if there is a more efficient way of writing this using fewer lines of code?

I suppose your focus is not literally on the part about "fewer lines of code".
You could use more semicolons to squeeze more lines onto a single line,
but that would violate PEP 20, the Zen of Python,
even more than it already does.

Your current solution is essentially a brute force algorithm,
counting up from the beginning until you find a suitable start page from which the last page will be reached on Day 6.
The algorithm is well implemented,
and I don't know a better way.
I can suggest some other improvements though.

Coding style

You should follow PEP8, the Python coding style guide.
In particular:

Do break lines in loops
Avoid using semicolon to separate multiple statements
Don't put spaces around method parameters, for example write read_book(start) instead of read_book( start )

Generalize

It would be nice to make the implementation more general.

For example, the target pages 411 and the required number of days would be nice to put in constants, to make them easier to play with and less magic.

Also,
instead of executing code in the global namespace,
the best practice is wrap your main code in a main() method,
and call that from within if __name__ == '__main__':, like this:

def main():
    # main implementation

if __name__ == '__main__':
    main()

Robustness

The find_start method counts up from 1 until the target page is reached,
or else...forever.
It would better to set an upper limit, like this:

def find_start(pages):
    for start in range(1, pages):
        read = start
        for read in read_book(start):
            pass
        if read == pages:
            return start
    raise ValueError("Impossible to reach page {} exactly".format(pages))

Suggested implementation

Putting the above suggestions together:

PAGES = 411
DAYS_TO_READ = 6

def read_book(start):
    for _ in range(DAYS_TO_READ):
        yield start
        start += sum(int(digit) for digit in str(start)) ** 2

def find_start(pages):
    for start in range(1, pages):
        read = start
        for read in read_book(start):
            pass
        if read == pages:
            return start
    raise ValueError("Impossible to reach page {} exactly".format(pages))

def main():
    previous_answer, start = 0, find_start(PAGES)
    for i, read in enumerate(read_book(start), 1):
        print("Pages read on day {} was {}\t(Now on page {})\n".format(
            i, read - previous_answer, read))
        previous_answer += read - previous_answer

if __name__ == '__main__':
    main()


I suggest two changes to values(SubType):

Return a Set instead of a List.
Prepare all the possible results at class-loading time, so that values(SubType) could be accomplished by a simple lookup.  The code is slightly more complicated, but the runtime performance should be better.

private static final Map<SubType, Set<ContentType>> BY_SUBTYPE;
static {
    BY_SUBTYPE = new HashMap<SubType, Set<ContentType>>();
    for (SubType subType : SubType.values()) {
        BY_SUBTYPE.put(subType, new TreeSet<ContentType>());
    }
    for (ContentType type : ContentType.values()) {
        BY_SUBTYPE.get(type.getSubType()).add(type);
    }
    for (SubType subType : BY_SUBTYPE.keySet()) {
        // Make Set<ContentType> values immutable
        BY_SUBTYPE.put(subType, Collections.unmodifiableSet(BY_SUBTYPE.get(subType)));
    }
}

public static Set<ContentType> values(SubType subType) {
    // Returns an unmodifiable view of a SortedSet
    return BY_SUBTYPE.get(subType);
}


I would try and simplify that each structure knows how to print itself:

int main()
{
    Year    year;
    // Load data into year.

    std::cout << year;

    // You can print a vector of years with:
    std::vector<Year>   yrs;

    std::copy(std::begin(yrs), std::end(yrs),
              std::ostream_iterator<Year>(std::cout, "\n"));

    // or a Simple loop:
    for(auto const& year: yrs) {
        std::cout << year << "\n";
    }

};

To make this work you need to define an operator<< for Year

struct Year{
    int year;
    vector<Month>month;
    Year(): month(12) { }

    friend std::ostream& operator<<(std::ostream& str, Year const& year)
    {
        str << "{year " << year.year;
        for(auto const& month : year.month) {
            str << month;
        }
        str << "}";
        return str;
    }
};

So the print for Year is defined in terms of printing for a Month object. So you know have to define how to print a Month. Which in turn will print some Day objects. So you will also have to define how to print a Day object.

The problem you are seeing:

os << '(' << v[i].month[j].day <<" "<< v[i].month[j].day[k].hour;
//           ^^^^^^^^^^^^^^^^^
//    This is a vector.
//    The stream class does not know how to stream a vector.
//    Did you mean `v[i].month[j].month`


Simple SQL query to get phrase pairs from a translations table

I recommend using more vertical space when you write a query to make it easier to read. That said, this should work:

SELECT
    P1.phrase_id,
    P1.language,
    P1.text,
    P2.phrase_id,
    P2.language,
    P2.text
FROM    phrases P1
INNER JOIN translations T
    ON P1.phrase_id = T.source_id
INNER JOIN phrases P2
    ON P2.phrase_id = T.destination_id
WHERE   P1.language = 'eng'
AND     P2.language = 'fra'
LIMIT 100;


Is there a better way to write the JS?

Yes there is.
First off, lets face it, your function fixMenus looks quite complex and a double for loop in one function is usually a big "no no" sign. Any company with a coding standard would want this to be different.
You have a double for loop with some conditions and some HTML building. That's a lot for one function and it looks hard to test accurately.
Your function does the following things

Loops through each menu
Destructures some data
Loops through a sublist to apply a class
Applies the new menu to the variable

So instead of having one function handle all this, let's break it up.
Make small simple functions that are easy to test
The concept of Test Driven Development (TDD) forces you to write code that is:

Easy to understand
Easy to test

This by itself already forces you to write better code and smaller functions.
You're probably not doing TDD, but writing code as if you were is already a great step!
Focus on the simple tasks

fixMenus should call generateMenus and ultimately generateMenu
Use Array#map and Array#join instead of forEach
create a function to update the actives
create a function to generate your html string

function updateActives(subItems){
   for (let i of subItems) {
      if (i.firstElementChild.href === window.location.href) {
        i.firstElementChild.classList.add(`is-active`);
      }
   }
}

function createMenu(labels, subMenus){
  return `

${labels}

       ${subMenus}

  `
}

function generateMenu(item){
  const {children:[elem1, elem2]} = item;
  updateActives(elem2.children);
  return createMenu(elem1.innerHTML, elem2.innerHTML);
}

function generateMenus(items){
  return items.map(item => generateMenu(item)).join("");
}

function fixMenus(menu, items){
  menu.remove();
  return generateMenus(items);
}


Ahhhh. Okay.

That the issue here is that if the process takes a right branch at node Foo, it needs to store a reference to Foo in the event that it fails to find a child node which is less-than or equal. That reference effectively lives in the stack-calls which occur in inside the calls to the work function.

There can be an arbitrary number of these calls, so we need an internal, private stack:

def find_val_iterative(parent_node, x):
    right_branch = []
    def _inner(parent_node, x):
        if parent_node is None:
            if right_branch:
                return right_branch.pop().val
            return None
        elif parent_node.val == x:
            return x
        elif parent_node.val > x:
            return _inner(parent_node.left, x)
        else:
            right_branch.append(parent_node)
            return _inner(parent_node.right, x)
    return _inner(parent_node, x)


Shell POSIX OpenSSL file decryption script

Get rid of unnecessary nested and combined ifs

While here it goes to no extreme, it's advisable to check for errors first, and to do that one by one - if possible, which is exactly this case.

Do some extra checks

Only in case of 0 arguments, the script should output usage message.
This script does not support multiple arguments, so if given more than 1, inform the user.
The script only checks for existence of the file, but what if it's not readable by the user.

Use tput for handling text colors instead of escape sequences

Those escape sequences are non-portable and the fact it works in dash does not mean it would do the job in Cygwin for instance; tput is clearly more portable.

bold=$(tput bold)
red=$(tput setaf 1)
yellow=$(tput setaf 3)
nocolor=$(tput sgr0)

bold_red=${bold}${red}
bold_yellow=${bold}${yellow}

Write a function for handling errors

print_error_and_exit()
{
    echo "${bold_red}$1 Exit code = $2.${nocolor}"
    exit "$2"
}

Shorten test commands, since there are only if ... then

[ "$#" -eq 0 ] \
&& print_error_and_exit "One argument needs to be given. Both relative, and absolute file paths are supported." 1

Declare and initialize variables just before they're used

The following declarations:

input_filename="$1"
filepath=$(dirname "$1")
filename_extracted_from_path=$(basename "$1")
filename_without_enc_extension="${filename_extracted_from_path%.enc}"

Should be split in order not to declare / initialize variables the script may not use in event of a failure.

Use exit return codes

The script should give the system feedback for example for automated processing. And be sure to use different exit codes in every failure event.

Root account check is unnecessary

The following test:

[ "$(id -u)" -ne 0 ]

Does not serve the intended purpose and should be omitted.

Comment code, that is not self-explanatory

The following code:

if [ "$filename_extracted_from_path" = "$filename_without_enc_extension" ]
then
    output_filename="$filepath/$filename_extracted_from_path".dec
else
    output_filename="$filepath/$filename_without_enc_extension"
fi

May be a little unclear, so a short comment is advisable.

The script should give feedback to the user too

The core code:

pv --wait "$input_filename" | openssl enc -aes-256-cbc -d -salt -out "$output_filename"

Should say something like:

Decryption failed / successful.

Clean after failed decryption

In the event of failed decryption, there is an empty output file present.

(Optional) The decryption status message could use some colors

In the end, if the decryption fails, it shows something similar to:

bad decrypt
140673166227096:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:529:

Though it might suffice to say the above mentioned message, some users might prefer it in color.

Based on the above code, I would re-write it as follows:

#!/bin/sh

bold=$(tput bold)
red=$(tput setaf 1)
yellow=$(tput setaf 3)
nocolor=$(tput sgr0)

bold_red=${bold}${red}
bold_yellow=${bold}${yellow}

print_error_and_exit()
{
    echo "${bold_red}$1 Exit code = $2.${nocolor}"
    exit "$2"
}

[ "$#" -eq 0 ] \
&& print_error_and_exit "One argument needs to be given. Both relative, and absolute file paths are supported." 1

[ "$#" -gt 1 ] \
&& print_error_and_exit "Multiple arguments are not supported." 2

[ ! -f "$1" ] \
&& print_error_and_exit "The given argument is not an existing file." 3

input_filename="$1"

[ ! -r "$input_filename" ] \
&& print_error_and_exit "Input file is not readable by you." 4

input_filepath=$(dirname "$input_filename")

[ ! -w "$input_filepath" ] \
&& print_error_and_exit "Destination directory is not writable by you." 5

filename_extracted_from_path=$(basename "$input_filename")
filename_without_enc_extension="${filename_extracted_from_path%.enc}"

if [ "$filename_extracted_from_path" = "$filename_without_enc_extension" ]
then
    # the file has a different than .enc extension or no extension at all
    # what we do now, is that we append .dec extention to the file name
    output_filename="$input_filepath/$filename_extracted_from_path".dec
else
    # the file has the .enc extension
    # what we do now, is that we use the file name without .enc extension
    output_filename="$input_filepath/$filename_without_enc_extension"
fi

[ -f "$output_filename" ] \
&& print_error_and_exit "Destination file exists." 6

if ! pv -W "$input_filename" | openssl enc -aes-256-cbc -md sha256 -salt -out "$output_filename" -d 2> /dev/null
then
    [ -f "$output_filename" ] && rm "$output_filename"

    print_error_and_exit "Decryption failed." 7
else
    echo "${bold_yellow}Decryption successful.${nocolor}"

    exit 0
fi


I have a query like this that seems complicated and I want to do it by using Java Stream Api

First off, the SQL query you are generating probably doesn't do what you want it to do. Because you using a subquery (a SELECT inside a SELECT) you are first limiting the unsorted data, and the sorting it, resulting in returning "random" rows instead of the first rows in sorted order. There is no reason to use a subquery, so instead of
SELECT * FROM (SELECT * FROM user_order WHERE ... LIMIT ?, ?) a ORDER BY ...

use
SELECT * FROM user_order WHERE ... ORDER BY ... LIMIT ?, ?

Then you really should format your code cleanly. The indentation is really bad and you should insert some empty lines between logical code blocks to separate them optically. Also put spaces in lines, specifically around operators, between keywords (if, while etc.) and (, after ; and before {. For example, the line:
for(int i=0;i<values.size();i++){

should look like this:
for (int i = 0; i < values.size(); i++) {

BTW, your editor/IDE should be able to do that for you. Look for a menu item "Format code".

Don't declare variables until you need them. Both resultSet and orders don't need to be declared until the loop at the end:
ResultSet resultSet = statement.executeQuery();
List<Order> orders = new ArrayList<>();
while (resultSet.next()){


Collection to hold maximum number of running Tasks

What you have described here is a Producer- Consumer relationship. .Net has a BlockingCollection that performs exactly what you are trying to create here

public BlockingCollection(
    IProducerConsumerCollection<T> collection,
    int boundedCapacity
)

  You could use a ConcurrentBag as the underlying store or any ConcurrentCollection of your choice and the boundedCapacitycan be the maximum number of Tasks that can be added to the collection. An example usage is

BlockingCollection<int> messages = new BlockingCollection<int>(new ConcurrentBag<int>(), 10);


Moving a value into another cell IF the destination does not have an adjacent border OR contain certain text

Your main concern is the GoTo and rightly so. But the main problems caused by the statement become a lot more obvious with complex code, not in your short Sub

The main issue with GoTo is that it creates convoluted logic: If condition go to this label, when you get to this label there might be another condition that will redirect to another place which redirects to yet another place, yet another place back to this label where another condition leads to a new location, and so on until you become completely lost and are barely able to keep up with the last two or three locations, and this creates a huge potential for bugs

The solution to avoiding these jumps is not necessarily simpler, because you will probably need more steps to connect the flow and overcome the disjointed shortcuts created by the GoTo’s. But these extra steps will help later on when maintaining the code because you’ll always be aware of the context: where the logic is coming from and where it leads, causes and effects, and it makes it a lot easier to spot the issues

Back to your Sub, you are aware the formatting is not ideal but you did try to highlight the main “action” by the use of vertical white space – it makes it quite easy to locate. But there are more issues as well:

  Option Explicit

Missing the first line of defense - any spelling mistake will create a new variable, and the variables you intended to use are not behaving as expected. The compiler will never alert you, and finding these simple issues can be very time consuming in large procedures

  Sub MoveUp()

The title is too generic; it doesn’t provide clues to the general intent of the Sub which is very specific to the letter O and the cell above it, under certain conditions which are also quite specific. In a larger application you might end up with a dozen “MoveUp” procedures that will probably need to be distinguished by non-intuitive numbers MoveUp1, MoveUp2, MoveUp3, etc. You could name it something like MoveUpAllOs()
All subs and functions default to Public, but you should make this intention clear by declaring the Sub as Public (accessible outside of this module)

When I first glanced at the code I inferred that you wanted to move all “O”s accordingly, but the code moves only the first O found in the range. Is this random or you actually wanted to move all of them? Maybe you have a specific reason to search for the first O found “ByRows”, which is the default SearchOrder for the “Find” method. If you want to check all of them you need to use a loop.

  Dim O As Range

The name does indicate the main subject but it doesn’t convey its purpose. And what happens if the latter changes – will you update all variable names from “O” to “X”? Again, this will be more difficult in larger procedures

  Set O = Range("A1:Z26")

Unqualified Range reference - what Worksheet are you referring to? Which Workbook? This is the main cause for issue in VBA. The macro recorder creates a bad habit because it implicitly refers to the ActiveWorkbook.ActiveSheet.

Be explicit about the full path of the range: ThisWorkbook is where the VBA code resides and executes. Worksheets(“Sheet1”) is identifying the worksheet by the name displayed in the tab, or Worksheets(1) is identifying it by its index as it appears in the tab order, Sheet1 is identifying it using the CodeName property of the Worksheet object which is visible and editable only from the VBA editor window and makes it safer to use – sheet names and indexes are easily changed by the end-user

"A1:Z26" is too specific – do you have thousands of rows and columns, and you only want A to Z, row 1 to 26, or is this intended for the entire used range? If it’s all data, you could make it dynamic without the need to update it for every new row or column: Sheet1.UsedRange would be a bit more flexible, yet restrictive enough for the Find to avoid searching 1 million+ rows

  If O.Offset(-1, 0) = "."

This is expecting the previous search to return a cell, but doesn’t account for the possibility of not finding an O. If the Find returns nothing the “O” range will be Nothing, and O.Offset(-1, 0) will generate "Run-time error '91' (Object variable or With block variable not set)"
It’s also assuming that there will always be a cell above the found O. If it’s found in row 1 this will generate "Run-time error '1004' (Application-defined or object-defined error)"

.

The GoTo can be avoided with this If statement, using “And” to combine the conditions:

If O.Offset(-1, 0).Value2 <> "." And _
   O.Offset(-1, 0).Borders(xlEdgeBottom).LineStyle = xlNone Then
        O.Offset(-1, 0) = "O"
        O.ClearContents
End If

Your If translates to a double negative, and it jumps over the main steps:

Don't move O if the above is a dot, or it doesn't have a border

This If translates to:

Move O if the above is not a dot and it doesn't have a border

.

.

This is how I would re-write the Sub

Move all instances

Option Explicit

Public Sub MoveUpAllOs()
    Const COND_VAL = "."
    Const COND_BRD_LOC = xlEdgeBottom
    Const COND_BRD_TYPE = xlNone
    Dim usedArea As Range, foundItem As Range

    Set usedArea = Sheet1.UsedRange
    Set foundItem = usedArea.Find(What:="O", LookAt:=xlWhole, MatchCase:=True)
    If foundItem Is Nothing Then Exit Sub

    Dim firstFound As String
    firstFound = foundItem.Address
    Dim upperIsFree As Boolean          'declaration to closest usage, outside loop
    Dim started As Boolean
    Application.ScreenUpdating = False
    Do
        If foundItem.Row > 1 Then
            With foundItem.Offset(-1)
                upperIsFree = .Borders(COND_BRD_LOC).LineStyle = COND_BRD_TYPE
                If .Value2 <> COND_VAL And upperIsFree Then
                    .Value2 = foundItem.Value2
                    foundItem.Value2 = vbNullString
                    If Not started Then 'updates first found address, after the move
                        firstFound = .Address
                        started = True
                    End If
                End If
            End With
        End If
        Set foundItem = usedArea.FindNext(foundItem)
    Loop While foundItem.Address <> firstFound
    Application.ScreenUpdating = True
End Sub

Move the first found

Public Sub MoveUpFirstO()
    Const COND_VAL = "."
    Const COND_BRD_LOC = xlEdgeBottom
    Const COND_BRD_TYPE = xlNone

    Dim usedArea As Range
    Dim foundItem As Range

    Set usedArea = Sheet1.UsedRange
    Set foundItem = usedArea.Find(What:="O", LookAt:=xlWhole, MatchCase:=True)

    If foundItem Is Nothing Then Exit Sub

    If foundItem.Row > 1 Then
        With foundItem.Offset(-1)

            Dim upperIsFree As Boolean
            upperIsFree = .Borders(COND_BRD_LOC).LineStyle = COND_BRD_TYPE
            If .Value2 <> COND_VAL And upperIsFree Then
                .Value2 = foundItem.Value2
                foundItem.Value2 = vbNullString
            End If

        End With
    End If
End Sub


Find all of the values in a list that are repeated the most

It would be easier, and have better performance, to iterate over Counter.most_common() rather than using .pop(0) lots.

From here you just want to use next until the value is not the same. Which is effectively what you're doing with .pop.

from collections import Counter

input_lst = [1, 2, 3, 3, 4, 4, 0, 1]

counts = Counter(input_lst)
items = iter(counts.most_common())
value, amount = next(items)
values = [value]
while True:
    value, a = next(items)
    if amount != a:
        break
    values.append(value)

print(values)

This is effectively grouping consecutive values together, and so you can instead use itertools.groupby rather than roll your own.

from collections import Counter
from itertools import groupby

input_lst = [1, 2, 3, 3, 4, 4, 0, 1]

_, values = next(groupby(Counter(input_lst).most_common(), lambda i: i[1]))
values = [value for value, _ in values]
print(values)


match name = Unchecked.defaultof<NameTable> with
| false -> …
| _ -> …

If you're checking whether a condition is true, you should use if, not pattern matching. It's simpler and clearer.

0 |> ignore

Instead of this, you can write the unit value: ().


Simplify SQL query that utilizes GROUP BY and HAVING BY and uses aggregation

SELECT Rating.rID, Rating.mID
FROM Rating
GROUP BY Rating.rID, Rating.mID
HAVING count(*) > 1;

This returns all ratings where the same person reviewed the same movie more than once, but that's not what we want.  We want all the ratings where the same person reviewed the same movie twice, giving it a higher rating the second time.

SELECT DISTINCT S2.rID, S2.mID
FROM Rating S1 INNER JOIN Rating S2 ON S1.rID = S2.rID AND S1.mID = S2.mID
WHERE S1.ratingDate > S2.ratingDate AND S1.stars > S2.stars;

Now let's look at your step 2:

SELECT Movie.mID, Movie.title, Movie.year, Movie.director, Rating.rID,
       Rating.stars, Rating.ratingDate, Reviewer.name
FROM Movie, Rating, Reviewer
WHERE Movie.mID = Rating.mID and Rating.rID = Reviewer.rID;

Why do we need so many columns?  The assignment is to return the movie title and reviewer name, so let's just do that:

SELECT Movie.title, Reviewer.name
FROM Movie
  INNER JOIN Rating S ON Movie.mID = S.mID
  INNER JOIN Reviewer ON S.rID = Reviewer.rID;

So we can finish with a new step 3:

SELECT Movie.title, Reviewer.name
FROM Movie
  INNER JOIN (
    SELECT DISTINCT S2.rID, S2.mID
    FROM Rating S1 INNER JOIN Rating S2 ON S1.rID = S2.rID AND S1.mID = S2.mID
    WHERE S1.ratingDate > S2.ratingDate AND S1.stars > S2.stars
             ) S ON Movie.mID = S.mID
  INNER JOIN Reviewer ON S.rID = Reviewer.rID;

This uses a single subselect to replace Rating from step 2 with a new version that only includes those Reviewer/Movie pairs where the second rating was higher than the first.


Let's start off with your questions:

  Do I need to somehow close the connection? It looks like send() automatically closes the connection because I cannot execute send() twice.

No. The browser abstracts all connection details from you, like connection persistence, caching, protocols, etc. You just have to think that an instance of XMLHttpRequest represents one request-response pair.

  Is the error handling ok? When my internet connection was a bit unstable, I got the message "Error: 0". Zero sounds like a strange status code.

A zero status code is a non-HTTP status code for a generic network failure. You can get that status code from invalid certificate errors, cross-domain errors, extensions blocking the connection, etc. On JS, you often cannot get any specific information from the error, and the only thing you can do is show a generic error message on your app. However, the browser console will tell you what happened exactly.

var xhr = new XMLHttpRequest();

Is so 2010. There's a simpler fetch that does more with a simpler syntax. Consider using that instead. It's inspired greatly by jQuery. If you're familiar with jQuery, you pretty much know what to do.

    var DONE = 4; // readyState 4 means the request is done.
    var OK = 200; // status 200 is a successful return.
    if (xhr.readyState === DONE) {
        if (xhr.status === OK) {

Unless you're reusing DONE and OK elsewhere, it's pointless to put them in variables. If one sees xhr code done manually, it's pretty much standard to check readyState 4 and status 200 when expecting a success.

obj = JSON.parse(xhr.responseText);

JSON.parse can throw an error when the string is malformed JSON. And malformed JSON can be caused by bad server code, or a misconfigured server that returns HTML error pages on errors. Wrap this in a try-catch, and fail the operation if it does throw.


If you were using python 2.x, there would be no need to do doors = [i for i in range(1, num_doors+1)], because range just returns a list. So just do:

doors = range(1, num_doors+1)

(similar for host_doors).

Since you are using python 3.x, range will return a range object, but you can just call list on it:

doors = list(range(1, num_doors+1))

Minor point: there is no need for the intermediate variable probability, just return successes / trials.

Python has an official style-guide, PEP8, which recommends not having unnecessary blank lines (such as between your if and else block).

Also, you should add one space in front between # and the actual comment.

It is also customary to use _ as a loop variable that is unused.

You can make your code slightly more efficient by only drawing the user's switched choice when actually switching:

def monty_hall (num_doors, trials, switch):
    successes = 0
    for _ in range(trials):
        # determine behind which door the prize is
        doors = list(range(1, num_doors+1))
        prize_door = np.random.choice(doors)

        # door the guest chooses. (Fixed to 1)
        guest_choice = 1
        doors.remove(guest_choice)

        # determine which door the host opens before guest is allowed to switch
        # this will be faster for larger lists than copying the `doors` list
        host_choice = prize_door
        while host_choice == prize_door:
            host_choice = np.random.choice(doors)
        doors.remove(host_choice)

        # determine which door the guest chooses if switching
        if switch:
            guest_choice = np.random.choice(doors)

        # check win condition
        if guest_choice == prize_door:
            successes += 1

    return successes / trials

It might actually be faster (for larger number of doors it will be), not to copy the doors for the host choice, but just take a random door from doors and take another one if it is the prize_door:

host_choice = prize_door
while host_choice == prize_door:
    host_choice = np.random.choice(doors)
doors.remove(host_choice)

For small lists this will be better:

host_doors = doors[:]
host_doors.remove(prize_door)
host_choice = np.random.choice(host_doors)
doors.remove(host_choice)

Overall the most costly part of this code is probably the removes, which can be quite costly for large lists if removing near the beginning (like for guest_choice). It would be better to store the doors as a set (for which deleting is O(1)). But that makes choosing one door harder (you have to do np.random.choice(tuple(doors)) everytime you draw). You should time both approaches and see what works best for your data.


Do I need to use inheritance and classes for my OOP webscraper?

I see no benefit to any of these approaches. You're just making yourself write more code. All you need is one class that analyzes a website entered from a user. If you have a predefined list of websites that you need to scrape, then iterate over each website instead of using a class for each one.
Since you say there are two ways of accomplishing this task, you can have the user pass in what mode they want to use to get the information. Something like
website = Scraper("https://www.google.com", "DIRECT")
website = Scraper("https://www.website_here.com/articles/article.pdf", "PDF")

Then you build your class around it. You want your code to be easily accessible and usable by a user. As a first time user, I would have no idea if I should use Website1 or Website2. What are the differences? Why should I use one over the other? You should always look at your code through the lens of a user.


Iterating over unequal unordered pairs in one collection

Also not really pretty, but perhaps a start

#include <algorithm>
#include <iostream>
#include <list>
using namespace std;

int main()
{
    list<int> lst = {1,2,3,4,5,6};

    auto a = lst.cbegin();
    int first = *a;
    auto output_pairs = [&first](const int second){ cout << " ("<<first<<','<<second<<')'; };
    while(++a != lst.cend())
    {
        for_each(a, lst.cend(), output_pairs);
        cout << '\n';
        first = *a;
    }
    cout << flush;
}

It's C++0x because I was too lazy to write a functor for that lambda and I don't know the Boost.Lambda syntax off the top of my head.


Converting imperative style user input menu to functional programming style

One of the Scala features you need to get used to using is match - it is your friend. One of your very best friends.

Also, the way you have defined menu is recursive, with no bounding. In this particular case, it's probably not an issue, but it is, in general a Really Bad Idea.

Finally, you have repeated the printing of the menu and reading of the option. In general, one should follow Don't Repeat Yourself.

So how about something like the code below. Note, one of the rare cases tailor made for do...while.

def menu(option: Int): Boolean = {
  option match {
    case 1 =>
      println("selected 1")
      true
    case 2 =>
      println("selected 2")
      true
    case 3 =>
      println("selected quit")
      false
    case _ => // the else case
      println("Sorry, that command is not recognized")
      true
  }
}

def readOption: Int = {
  println("""|Please select one of the following:
             |  1 - one
             |  2 - two
             |  3 - quit""".stripMargin)
  StdIn.readInt()
}

def main(args: Array[String]) {
  var opt = 0
  do {
    opt = readOption
  } while (menu(opt))
}

Alternately, if you wanted to something more functional, you could change menu to something like this:

val actionMap = Map[Int, () => Boolean](1 -> handleOne, 2 -> handleTwo, 3 ->handleThree)

def handleOne(): Boolean = {
  println("selected 1")
  true
}

def handleTwo(): Boolean = {
  println("selected 2")
  true
}

def handleThree(): Boolean = {
  println("selected quit")
  false
}

def menu(option: Int): Boolean = {
  actionMap.get(option) match {
    case Some(f) => f()
    case None =>
      println("Sorry, that command is not recognized")
      false
  }
}

Where actionMap maps each Int to a function that takes no parameters and returns a Boolean. In menu, we use option as the key into the map and then call the result (if there is one).


You spend a lot of lines of code trying to get the expressions lessthan(), getsize(), and bracket() to behave like plain old functions. Consider just using plain old functions, instead. For example:

static uint8_t get_char(int x, size_t offset)
{
    const int bit_shift = 8 * (sizeof(int) - offset - 1);
    uint8_t result = (x >> bit_shift) & 0xFF;
    if (offset == 0) result ^= 128;
    return result;
}

static uint8_t bracket(const std::pair<int,int>& x, size_t offset)
{
    if (offset < sizeof(int))
      return get_char(x.first, offset);
    return get_char(x.second, offset - sizeof(int));
}

...
string_sort(a.begin(), a.end(), bracket, getsize(), lessthan());

You could also productively replace the expression getsize() with

auto getsize = [](auto){ return 2*sizeof(int); };

...
string_sort(a.begin(), a.end(), bracket, getsize, lessthan());

Finally, lessthan is equivalent to std::less<std::pair<int,int>>, so you can just write

string_sort(a.begin(), a.end(), bracket, getsize, std::less<>());

That's the kind of shortening you were looking for, right? :)


When writing macros, it is best to avoid using functions like datum->syntax to conjure up identifiers. Instead, your macro should take the identifiers to bind from the macro use site.

For your example, I would write it like this:

#lang racket

(provide square total)

;; note how `n` is passed in as an argument
(define-syntax-rule (induction n base rule)
  (lambda (n)
    (cond [(n . = . 1) base]
          [(n . > . 1) rule]
          [else        (error "invalid number:" n)])))

(define square (induction n 1 (* 2 (square (- n 1)))))
(define sum    (induction n 1 (+ (square n) (sum (- n 1)))))

(define (total)
  (sum 64))

Macros written in this style are more composable and cooperate with macro hygiene. Racket's macro system lets you break this hygiene in a controlled way, but that is usually a bad idea.

Also, for a simple program like this I would usually not bother writing a macro. In this case, you could even have abstracted this using only first-class functions instead of macros.

You may also wish to read Macros and Languages in Racket and Fear of Macros if you haven't already.


I'm doing a little guess work here because you've not shown us the method'd signature. I apologize if I've made some bad assumptions.

Typically, when I see a Target Range, it means we're working inside of a worksheet's OnChange event. Assuming that, I would recommend introducing a new Range variable into the mix so you're not accidentally modifying the incoming range. Adding an extra variable would make it clear and explicit when/if you're programmatically changing the same range the user modified.

This snippet makes me believe it's the right thing to do even if my assumption is wrong.

                'Set target offset to new cell
                Set target = target.Offset(, ColumnCount)

                'Generate key and pass target offset value to table update module
                modTableUpdate.TableUpdate target, destsheet, sourcesheet, ColumnHeader, ColumnFormula, Celladdress, Key, cell, result

                'Set target offset back to original cell
                ColumnCount = -1

                Set target = target.Offset(, ColumnCount)
                'Set column count to 0 to maintain alignment when loop repeats

By introducing an offsetTarget variable, you should be able to avoid tracking the column count and all this setting and resetting because you've never modified target to begin with.

The other thing I would be careful of is detailed at the end of this answer and again assumes this code resides in the Worksheet_Change event. Target could possibly be a multi-cell Range. Double check your code to make sure it can deal with that edge case.

One last thing. This method takes in an awful lot of parameters.

modTableUpdate.TableUpdate target, destsheet, sourcesheet, ColumnHeader, ColumnFormula, Celladdress, Key, cell, result

Consider creating a simple class to encapsulate that data and simplify the call.

modTableUpdate.TableUpdate instanceOfYourAwesomeNewClass


Bad storage and time

Your code solves the problem but is a memory hog.

Algorithm complexity

You are looping over the digits twice, once to extract each digit, and then once to sum each half. The logic can be improved if you calculate the sums as you extract each digit. This also means you do not have to store each digit in the array for the sum calculations.

If you include the two Array.slice calls that is a total of 3 iteration of each digit in n and two stored copies of each digit.

JavaScript performance

In terms of JavaScript performance array functions that take callbacks, like Array.reduce, have a high per iteration overhead when compared to standard loops. When the inner code is small that overhead is a significant part of the overall iteration time.

Array.slice should only be used when you need a copy of items in a new array. (Note items that are references only copy the reference. IE shallow copy).

Arrays in JavaScript are expensive in terms of performance because they do not get space from the heap but rather invoke the memory management system for allocation and disposal.

Code style

Never create un-delimited blocks. if (n === 10) return false; should be if (n === 10) { return false; } or if (n === 10) { return false }
The reduce callback is written in the long form, .reduce(function(a, b) { return a + b }) it would be less noisy to write it as .reduce((a, b) => a + b)
Too many comment, and one that conflicts with the code (a lie).

Apart from that the code is well formatted, has good naming, and good use of variable declaration type.

Your question

  would recursion be faster?

Seldom is recursion faster. Recursion is used to simplify state stack management, the function call is the state push, and return the state pop.

Until tailcalls are implemented in JavaScript, functions that are O(1) storage, become O(n) storage if converted to recursive solutions. There is no time complexity change. The solution is a O(1) storage problem and thus will not benefit from recursion.

  I wonder if there is an even more efficient way write it

Yes there is, see bottom rewrite.

Rewrites

Using your algorithm and API use.

Comment are only added as I am not sure if you recognize the code or why.

The test for 10 is not worth the cost [1]

const isLucky = n => {
    const sum = (a, b) => a + b; // minor memory/parse gain with one rather than two functions
    const digitCorral = [];
    while (n > 0) {
        digitCorral.push(n % 10);
        n = n / 10 | 0;  // Bitwise OR 0 is the faster form of Math.trunc
    }
    const first = digitCorral
        .slice(0, digitCorral.length / 2)
        .reduce(sum);
    const second = digitCorral
        .slice(digitCorral.length / 2)
        .reduce(sum);
    return first === second;
}

A better way.

Improved with O(1) storage, O(n) complexity where n is the number of digits in argument n

const isLucky = n => {
    var midDigit, n1, sum1 = 0, sum2 = 0;
    midDigit = (Math.log10(n) + 1 | 0) >> 1;
    const midMod = 10 ** midDigit;
    n1 = n / midMod | 0;
    n %= midMod;
    while (midDigit --) {
        sum1 += n % 10;
        sum2 += n1 % 10;
        n = n / 10 | 0;
        n1 = n1 / 10 | 0;
    }
    return sum1 === sum2;
}

1. The following calculations are orders of magnitude approximations only. The early exit test for 10 (about 1/100 operations) is only worth the CPU time if there is a high probability of 10. That's a cost of 1% of operations, for gain of 1e-7%. The gain should always outweigh the cost by at least one order.
 That will only happen when 10 is about 100Million times more likely than any other number


Increase view counter with each page view

No, this code is not vulnerable to SQL injection.  The use of intval() and if (… && $id > 0) guarantee that $id is a positive integer, so the UPDATE and SELECT queries cannot be malicious.

It is very weird that you use the LIKE operator, though.  Is the id column not an INTEGER?  I would expect that that works by converting every id into a string, then performing pattern matching.  That would be slow because

Converting every id in the hdflv_upload table would be extra work.
The database cannot locate the row with the right id using an index; it has to examine every id.
Pattern matching is more complicated than a simple integer equality check.

Note that in this version, you have fixed a race condition that existed in the previous version.  In the previous version, it is possible to under-count if two pages simultaneously try to update the count, and the sequence ends up being SELECT, SELECT, UPDATE, UPDATE.  This code is better because UPDATE hdflv_upload SET times_viewed = times_viewed + 1 WHERE … should be immune to race conditions.


Deployment Automatization for docker builds, kubernetes deploys and secret injection

Some suggestions in rough order of decreasing importance:

eval is evil, and I'm pretty sure you can completely avoid it in your script. Other than a massive gain in sanity, all that sed stuff to escape strings is not going to be necessary if you instead just use plain shell.
Naming is really important, and comments are a good way to detect things which should be renamed.
set -o errexit -o nounset -o pipefail would be very handy in this script. Just make sure you're aware of the caveats (that page is needlessly snarky but has some useful bits, and that site is fantastic).
A simple array is the best way to build a command. I would thoroughly recommend not building complex commands using a shell script. Instead, run each command as soon as you have all the pieces. Bundling up commands to run isn't going to make things faster; in most cases it'll make things significantly slower by making >50% of the code about building the command rather than just running it.
Nested functions aren't. There are no closures in Bash, so defining a function within another function just makes it harder to read.
In Bash the convention is that uppercase names are reserved for exported variables.
Single use variables can often be inlined without loss of clarity.
printf is meant to be used with format strings for readability. So

printf "SHA1 for ${cyan}$name${end_format} is ${yellow}$tag${end_format}.\n"

would normally be written as

printf "SHA1 for %s is %s.\n" "${cyan}${name}${end_format}" "${yellow}${tag}${end_format}"

local is considered a command for exit code purposes, which means that local foo=[variable or command substitution] only gets the exit code of local, not of the variable or command substitution. So if you start using nounset and the like you should declare variables local before assigning them separately:

deploy() {
    local deploy_name tag
    deploy_name="$1"
    tag="$2"
    …
}

shellcheck can give you more tips.


Callback class to callback member (virtual) functions

Overall, the design looks reasonable.  However, I can't shake the feeling that Lambda expressions are a good (maybe even better) fit here.

For example, instead of

member_callback(object, &integer::--);

you could use a Lambda expression:

[&] () { return object--; }

This is almost as short, and has some additional advantages:

You aren't effectively "reinventing the wheel".  Although I wouldn't say your member_callback class is precisely the same as a lambda, it's pretty close.
I'm not qualified to say whether your code conforms to the C++ 11 specification.  But assuming it does, you are relying on relatively obscure portions of the specification.  This has some practical problems:

Others might have a hard time understanding and verifying your code.
Compilers often don't conform as strictly to the spec as we would like.  So you might find that your code is not portable, even if it does conform the the spec.

You noted that one of the drawbacks of your approach is that you cannot mix functions to different types of objects.  With lambdas, you can combine functions that work on different types of objects.  You aren't just limited to objects of a single (base) type (in your case, integer).  Likewise, you can define functions that operate on more than one object, or even none at all (e.g., produce a constant value).  Or, you could combine functions.
Lambdas open the door to higher-order approaches.  For example, if you Curry the member_callback function, you can partially instantiate a callback:

With the order you have (object, function), you can construct a factory for working on a single object.  For example (eliding types for brevity):

factory = member_callback_curried(object);

// Sometime later, perhaps in a different scope
dec = factory([] (integer& obj) { return obj--; });
inc = factory([] (integer& obj) { return obj++; });

Reversing the order to (function, object), you can construct a factory for working with the specified function:

factory = callback_member_curried([&] (integer& obj) { return obj-- });

// Sometime later, perhaps in a different scope
dec_o1 = factory(obj1); // function that decrements obj1
dec_o2 = factory(obj2); // function that decrements obj2


I'd make right an exclusive instead of inclusive upper bound, that is write i < right instead of i <= right and last - v instead of last - v - 1.

This has the advantage of making the base call qsort(v, 0, length) instead of qsort(v, 0, length - 1).


Consider starting the child process in a sandbox.  /usr/bin/perl is likely safe from a malicious user since /usr/bin is typically locked down by the root user(s).  But /home/demetri/bin/awklikeperl.pl could be replaced if the owner is not careful with permissions.  Putting the process in a sandbox will not only protect the rest of your system from attack, but help you think about what files will be made available.

Obviously, the content of the script should be reviewed for vulnerabilities as well.  Take a look at perlsec for help on that front.

3 is a bit of a magic number in the C program.  As you've already discovered, it's easy to forget to change that number if you add or subtract parameters from the command array.  If you define that in one place (say #DEFINE STARTING_ARGS 3) you'll only need to change the value in one place.

Speaking of which, I considered suggesting adding a -- parameter to prevent any shenanigans with adding extra switches.  But once you pass the script name to perl, it passes all other arguments onto the script.  So I think it's not possible to use -e to execute an arbitrary command.


I don't know if something does that already, but you could mimic StructLayout if you need to read multiple types of 'objects' or need reusability.

Basically just set starting point/offset and length for each property and read them.

public class Item
{
     // 3 chars starting from 0
    [Layout(0, 3)]
    public int Number { get; set; }

     // 15 chars starting from 3
    [Layout(3, 15)]
    public string Text { get; set; }

    // 5 chars starting from 18
    [Layout(18, 5)]
    public float Number2 { get; set; }
}

reader.Read<Item>()


AFAIK, you can use List comprehension to make it more efficient

raw_data = dl("http://somewhere")
soup = BeautifulSoup(raw_data)
data = str(soup.find_all('div', attrs={'class' : "results"}))
return  [ urllib.parse.unquote_plus(link['href']) for link in BeautifulSoup(data, parse_only = SoupStrainer('a'))]


Computing the circumference of two circles

Although your code works, it's not so good.

Declare variables as late as possible

Here you declare some variables at the top, and use them much later, for example smallCircum:

double smallCircum;
double largeCircum;
InputHandler input = new InputHandler();
Question5 myq = new Question5();

double a = input.getDouble("Radius for the smaller circle:");

smallCircum = (myq.start(a));//calculate the small circle circumference

It would be better to declare as late as possible, right before you need it:

InputHandler input = new InputHandler();
Question5 myq = new Question5();

double a = input.getDouble("Radius for the smaller circle:");
double smallCircum = (myq.start(a));//calculate the small circle circumference

Pointless field

In Question5, the variable circumference doesn't need to be a field.
It's only used here:

private double circum(double radius){
    circumference = 2 * Math.PI * radius;
    return circumference;
}

But there is no need to store that value in a field, and no need for even a local variable, you can simply return it directly:

private double circum(double radius) {
    return 2 * Math.PI * radius;
}

static method

It's unclear why this method in InputHandler is static:

public static double getDouble(String prompt){

I suggest to drop the static keyword, make it non-static.

Poor naming

Looking at this:

smallCircum = (myq.start(a));//calculate the small circle circumference

A method named start returns the calculated circumference.
That's really not intuitive.
Why not rename start to calculateCircum?
If its containing Question5 class needs to be kept general purpose and not imply circumference, then perhaps you can rename the method to just calculate instead.
Probably almost anything is better than start.

Another thing, a is a poor name to store radius.

Make private what you can

In Question5, df should be private.

Make final what you can

In Question5, df can be final.

Suggested implementation

With the above suggestions applied, the solution becomes:

package com.janosgyerik.practice.oj.leetcode.hard.SubstringWithConcatenationOfAllWords;

class Q5Main {
    public static void main(String args[]) {
        InputHandler input = new InputHandler();
        Question5 myq = new Question5();

        double smallRadius = input.getDouble("Radius for the smaller circle:");
        double smallCircum = myq.calculate(smallRadius);

        double largeRadius = input.getDouble("Radius for the larger circle: ");
        double largeCircum = myq.calculate(largeRadius);

        myq.showDetails(smallCircum, largeCircum);
    }
}

class Question5 {
    private final DecimalFormat df = new DecimalFormat("0.000");

    public double calculate(double value) {
        return circum(value);
    }

    private double circum(double radius) {
        return 2 * Math.PI * radius;
    }

    public void showDetails(double smallCircum, double largeCircum) {
        System.out.println("Circumference of smaller circle: " + df.format(smallCircum));
        System.out.println("\n");
        System.out.println("Circumference of larger circle: " + df.format(largeCircum));
        System.out.println("\n");
        System.out.println("Difference: " + df.format((largeCircum - smallCircum)));
    }
}

class InputHandler {
    private static final String DOUBLE_DEFAULT_PROMPT = "Enter integer: ";

    public double getDouble() {
        return getDouble(DOUBLE_DEFAULT_PROMPT);
    }

    public double getDouble(String prompt) {
        String inStr = JOptionPane.showInputDialog(null, prompt);
        return Double.parseDouble(inStr);
    }
}


Although this feels very "examplish", here are my thoughts:

Personally, I would rethink how you handle paths currently. As it stands, the directory structure must be very specific: you are provided with some "root" folder, and in that folder you have subfolders, each named after the namespace of the library within it, then a bin folder, then a Debug folder, so an example would be:

C:\Projects\Project1\bin\Debug\Project1.dll
C:\Projects\Project2\bin\Debug\Project2.dll
C:\Projects\ClassTest\bin\Debug\ClassTest.dll
et. al.

If you just wanted to drop a bunch of files in one folder, it's currently not possible.

Why don't you, instead, add the path as a line in the XML file?

<Protocols>
  <Protocol>
    <NameSpace>ClassTest</NameSpace>
    <ClassName>Class1</ClassName>
    <FrequencyType>Minute</FrequencyType>
    <FrequencyValue>20</FrequencyValue>
    <FolderPath>../../ClassTest/bin/Debug/</FolderPath>
  </Protocol>
</Protocols>

The nicety of this is that you can now put your DLL's anywhere. You can use relative, absolute and virtual paths, and you can make them much more dynamic.

C:\Projects\Project1\bin\Debug\Project1.dll
C:\Projects\Project2\bin\Release\Project2.dll
C:\Dean Martin\ClassTest.dll
et. al.

This also means, that if you wish to use the release version of Project1, but the debug version of Project2, you can! Just include the appropriate path name!

This is generally the best-practice for this situation, as the "location" of a DLL file is a configuration aspect, rather than a programme aspect. Only in certain situations (with things like dynamic plugins) would you use a hardcoded (absolute, virtual, or relative: any of the three) path to get to the DLL's. And that would typically be something like Plugins\.

On a separate topic: I would recommend you use the @ prefix for your path strings, to be able to omit escapes:

System.Reflection.Assembly assembly = Assembly.LoadFrom(path + "../../" + NameSpace + @"\bin\Debug\" + NameSpace + ".dll");

This tends to make it more readable. Of course, if you move the file paths to the XML, it won't be a problem. :)


This is somewhat unstructured, but here are a few recommendations:

Be careful when shadowing built-ins

In dec_to_bin(), the int parameter shadows the Python core int type keyword. This works fine, but it's usually clearer to avoid redefining builtins when you can. Maybe call it num.

bytes is also a builtin. It's ok to redefine them, just be aware.

Variables not always defined

if platform.system() == 'Windows':
    mode = '644'
elif platform.system() == 'Linux':
    mode = '744'

trail = 'begin ' + mode + ' ' + filename + '\n'

What happens if platform.system() is neither Windows or Linux? (For example: on Mac it returns 'Darwin'.) mode will be undefined, raising UnboundLocalError.

Unnecessary conversion to list

char_list = list(string)
...
for char in char_list: ...

Strings are iterable just like lists, so for char in string: works fine.

In fact, consider removing string_values and char_list entirely. You can condense them into:

bytes = ''.join(dec_to_bin(ord(char)) for char in string)

Unused variable

A common convention is to use _ to represent unused vars:

for index, _ in enumerate(decimal_list):
    decimal_list[index] += 32

This shows that you are deliberately ignoring the second value from enumerate.


C# Program that checks on the status of the Capslock with each character insert

if true return true else return false antipattern

Unecessary if statements when dealing with booleans is a very common beginner pitfall.

    static bool CapsCheck()
    {
            // Check if Capslock is Active
        if (Console.CapsLock == true)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Is equivalent to:

   static bool CapsCheck()
   {
       return Console.CapsLock;
   }

As a further simplification, you may use Console.CapsLock directly and avoid this function.

Another boolean simplification is

            if (CapsCheck() == true)
            {
                CapsNotify(true);
            }
            else
            {
                CapsNotify(false);
            }

To:

 CapsNotify( CapsCheck() );

Or:

CapsNotify( Console.CapsLock );

Ternary simplification

In CapsNotify it is unecessary to use a full if else, a ternary is enough and simpler:

 Console.Writeline("CapsLock is" + (caps ? "Active" : "Inactive"));