There are a couple of ways of solving this:

Nest the other functions inside of oneIterationConway

function oneIterationConway(matrix) {
  const height = matrix.length;
  const width = matrix[0].length;
  function isInBounds(row, col, matrix) {
    return row >= 0 && col >= 0 && row < height && col < width;
  }

this way the first definition of height is in scope (available) inside isInBounds. Hiding your 'private' functions is a good idea anyway.
Don't use isInBounds at all, take advantage of the fact that items out of bounds are undefined.

function countNeighbors(row, col, matrix) {
  let neighbors = -matrix[row, col];

  for (let i = -1; i <= 1; i++) {
    for (let j = -1; j <= 1; j++) {
      let value = matrix[row+i, col+j];
      if (value) neighbors++;
    }
  }
  return neighbors;
}

If I am in control of the design, something I often do is add a boundary around my matrix. Something like:

const testMatrix = [
  [0, 0, 0, 0, 0, 0, 0],
  [0, 1, 0, 0, 0, 0, 0],
  [0, 0, 1, 1, 0, 0, 0],
  [0, 0, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
];

My loops would then be from 1 to size-2

The only other obvious thing I would be would be to factor out part of the main loop:

for (let row = 0; row < height; row++) {
  resultMatrix[row] = [];
  for (let col = 0; col < width; col++) {
    resultMatrix[row][col] = isAlive(row, col);
  }
}

function isAlive(row, col) {
  const neighborCount = countNeighbors(row, col);
  if (matrix[row][col]) {
    // current cell is alive
    return neighborCount > 1 && neighborCount < 4 ? 1 : 0;
  } else {
    // current cell is dead
    return neighborCount === 3 ? 1 : 0;
  }
}

btw, There is a nice feature in most environments. You can use: console.table(results)


This code is very easy to understand, which is great! I like that you used full words for the variable names rather than abbreviating everything to single character names.
Don't Abort
In alloc_matrix(), if there is a failure to allocate memory, it calls abort(). This is going to make it very difficult to test! If it attempts to allocate and fails, it aborts the test. Usually a test will return success or failure. This is an important distinction because you may write tests that should fail to test the failure paths of your code.
Proper Types
I would change the types of the argument to this:
char*** alloc_matrix(const size_t rows, const size_t columns);

I made them all const because the function doesn't change their values. I also made them size_t which is the appropriate type to use when you want to represent a size.
More Tests
You should add some more tests. As mentioned above, you need to test cases that should fail, such as allocating a block that's the maximum 64-bit value (for example malloc(ULLONG_MAX);).
You should also test things like alignment. Many platforms have strict byte alignment requirements. For example, pointers can usually not have an odd start address, and often must be 4-byte, 8-byte, or 16-byte aligned. You may need to check the specifics of the platform you're testing on.


There's very little I would salvage from the model code.

Converting the arguments list into comma-separated string is a little hackish and not very efficient (nevertheless it works, and I'd be totally OK with it for a quick throw away script). Therefore I would not use getListFromString.
askUser is not needed since we're not interacting with the user.
There's already an alternative to maybeRead, in Text.Read called readMaybe.

This is how I would implement it:

import System.Environment (getArgs)
import Text.Read (readMaybe)

main :: IO ()
main = do
  values <- fmap (map readMaybe) getArgs
  putStrLn $ maybe "Arguments invalid" (show . sum) $ sequence values


From a once over and reading some Jasmine docs:

I am not a big fan of _db and _testContext, I see no reason for the underscores.
It is not guaranteed that _db will be set in new MyCtorFunction(_db).myMethod(_testContext.assertions);, so you should check for that prior to calling.
You did not tell us what database (API) you are using, so we cannot tell whether you close the connection properly.
I wish you had provided us the code in assertions, it would have helped with the review
JsHint could find nothing wrong
I would advise you to make sure an assertion fails and put a log statement in your db closing code, this way you can be assured that the db connection will be closed. Though from reading the docs you should be fine.
This:

waitsFor(function () {
  return _testContext.assertions.callCount === 1;
}, "waiting for the assertions to be called.", 5000);

Seems a bit paranoid, afterEach is guaranteed to run after your assertions if I read your code well. If I am right then you can clean up your code tremendously since you will not need _testContext any more.
I hope MyCtorFunction and myMethod are not the true names in your code, those are horrible names ;)

All in all I dont really like your code, I blame Jasmine for that. I dont like their approach to naming functions nor their approach to asynchronous processing.

Update:

I realized on the subway that in my mind, the waiting for the db and the waiting for the test to finish ought to be part of the test, not part of the setup/teardown. This approach will definitely simplify since you wont need runs anymore in afterEach, plus you will not need testContext any more.

I cannot test this, but you should get the picture.

"use strict";

describe("MyCtorFunction", function () {

  describe("myMethod", function () {
    var db;

    beforeEach(function () {

      new DbHelper().openConnection(function (err, dbConnection) {
        if (err) {
          throw err;
        }
        db = dbConnection;
      });
    });

    afterEach(function () {
      if (db) {
        db.close();
        db = null;
      }
    });

    it("should do something", function () {
      //Wait for the green light
      waitsFor(function () {
        return db;
      }, "establishing a connection to the database.", 5000);
      //Start acting!
      runs(function () {
        //arrange
        spyOn(_testContext, "assertions").andCallThrough();
        //act (assertions invoked as callback)
        new MyCtorFunction(_db).myMethod( assertions );

        //assert
        function assertions(err, config) {
          expect(config).toNotBe(null);
          //etc.
        }
      });
      //Wait for the action to be done
      waitsFor(function () {
        return assertions.callCount === 1;
      }, "waiting for the assertions to be called.", 5000);
      //Done
    });
  });
});

Finally, from a library perspective, check out https://github.com/derickbailey/jasmine.async


Simple string joiner in modern C++ - follow-up

using declarations

Don't do this at top level:

using namespace std;

and certainly not in a header file, where it can can bring unexpected names into user code.

using std::cout;
using std::endl;
using std::for_each;
using std::vector;

These are less dangerous, but should still be avoided in headers.  Reduce their scope and visibility as much as you can, or use fully-qualified names.

Pointers and ownership

std::ostringstream* oss;
std::string* separator;

Who owns these objects?  Can they be null?  oss is used without checking for null, and it does not appear to be owned by this, so it should probably be a reference.  separator should probably be an owned value, so you can initialize from an rvalue.

Type of separator

Why is separator a std::string?  If the output stream can handle wide strings, we should be able to separate our values with wide strings.

Usual operator types

g++ -Weffc++ recommends that you return the result of postincrement by value, rather then by reference.  That's arguably moot in this case, as incrementing is a no-op, but I like to avoid warnings!

Code duplication

It's a small duplication, but I think it's clearer to separate out the emitting of separator and value:

my_ostream_iterator<T,charT,traits>& operator= (const T& value) {
    if (first_value_appended)
        oss << separator;
    else
        first_value_appended = true;

    oss << value;
    return *this;
}

Generality

Your iterator is templated on the character type, but you don't seem to make use of that type (see "type of separator" above).  I prefer to make the output stream a std::basic_ostringstream<CharT, Traits> so that your code will produce the correct kind of string as output.

Efficiency

In your std::for_each in main(), you pass a vector by value.  It should probably be a reference to const vector.

Modified code

#include <iterator>
#include <sstream>
#include <string>

template<typename T, typename CharT=char, typename Traits=std::char_traits<CharT>>
class my_ostream_iterator
    : public std::iterator<std::output_iterator_tag, void, void, void, void>
{
    using string_t = std::basic_string<CharT, Traits>;
    using stream_t = std::basic_ostringstream<CharT, Traits>;

    stream_t& oss;
    const string_t separator;
    bool first_value_appended;

public:

    my_ostream_iterator(stream_t& oss, const string_t& separator)
        : oss{oss},
          separator{separator},
          first_value_appended{false}
    {
    }

    my_ostream_iterator<T,CharT,Traits>& operator= (const T& value) {
        if (first_value_appended)
            oss << separator;
        else
            first_value_appended = true;

        oss << value;
        return *this;
    }

    my_ostream_iterator<T,CharT,Traits>& operator*()     { return *this; }
    my_ostream_iterator<T,CharT,Traits>& operator++()    { return *this; }
    my_ostream_iterator<T,CharT,Traits> operator++(int)  { return *this; }
};

template<typename InputIt, typename StringT = std::string>
StringT join(InputIt begin,
             InputIt end,
             const StringT& separator = ", ",
             const StringT& concluder = {})
{
    using value_type = typename std::iterator_traits<InputIt>::value_type;
    using char_type = typename StringT::value_type;

    std::basic_ostringstream<char_type> ss;
    std::copy(begin, end,
              my_ostream_iterator<value_type, char_type>(ss, separator));

    ss << concluder;
    return ss.str();
}

// test program
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    // Bring in names needed for argument-dependent lookup
    using std::begin;
    using std::end;

    const std::vector<std::vector<int>> matrix = {
        { 1, 2, 3 },
        { 4, 5 },
        { },
        { 10, 26, 29 }
    };

    std::for_each(begin(matrix), end(matrix),
                  [](const auto& a) {
                      std::cout << join(begin(a), end(a)) << std::endl;
                  });
    std::cout << " ---" << std::endl;

    std::for_each(begin(matrix), end(matrix),
                  [](const auto& a) {
                      std::wcout << join(begin(a), end(a), std::wstring(L", ")) << std::endl;
                  });
    std::wcout << " ---" << std::endl;
}


Implementing Sample Abstract Factory Pattern using Smart Pointers in C++

First, the big bug.  Your Widget class has no virtual destructor! This means that every time you return a unique_ptr<Widget>, you're losing the information about what kind of widget needs destroying.

Clang will actually diagnose this mistake for you. No matter what compiler you use, make sure you turn on warnings via -Wall -Wextra (or -W4 on MSVC).

int _tmain(int argc, _TCHAR* argv[])

This is a non-standard main routine. Maybe I'm a POSIX chauvinist, but at least for posting publicly, I'd think it would be more appropriate to use

int main(int, char **)

or even better,

int main()

(since you don't use either of those parameters for anything).

Also notice that I'm using char** instead of char*[], because in C and C++, a function parameter cannot be an array. It is pointless to deceive yourself and mean to deceive others.

SmartClient(std::unique_ptr<SmartWidgetFactory> oFactory)

This constructor should be marked explicit. In fact, every constructor you ever write (except for copy constructors and move constructors) should be explicit. If you leave off the explicit, then you're enabling people to write code like

std::unique_ptr<SmartWidgetFactory> pf = ...;
SmartClient sc = std::move(pf);

or even

SmartClient sc = nullptr;

and it'll compile, and they won't realize what they did wrong until runtime. It's better to catch this kind of thing at compile time. Mark all your constructors explicit.

std::unique_ptr<Widget> CreateButton()

If you intended this function to override the virtual function in the base class, you should have marked it override. (It may still override the virtual function in the base class, even without override, if you spelled everything correctly; but don't bet your workday on it. Mark all overriding functions override and catch your bugs at compile time.)

Also, consider whether it makes conceptual sense that "creating a button" is a non-const method of the factory. Maybe it does; I tend to think it doesn't. So I would write this as

std::unique_ptr<Widget> CreateButton() const override

std::unique_ptr<SmartClient> oClient = std::make_unique<SmartClient>( std::move(oFactory) );

Why does this need to be heap-allocated?

auto oClient = SmartClient(std::move(oFactory));

Even if you want to keep using make_unique for some reason, consider replacing the cumbersome type name std::unique_ptr<SmartClient> with auto:

auto oClient = std::make_unique<SmartClient>(std::move(oFactory));

Notice I've also normalized the whitespace while I'm at it.

void LOG(std::string strText)

Pass large expensive-to-copy objects, such as std::string, by const reference.

void LOG(const std::string& text)

If you are on C++17, consider replacing const std::string& parameters with std::string_view parameters:

void LOG(std::string_view text)

Be aware that you should use string_view only in places where it would make equal sense to use a reference type (so, parameters, and that's it).

Also be aware that when people see LOG("foo") in your code, they will assume that LOG is a macro, because it's ALL UPPER CASE. If you mean for people to assume it's a function, call it print_to_log or something like that.


Generate a Json from Strings using Jackson library

A few things:

Use descriptive variable names. A common Java convention is a camelCase version of the class name such as JsonMapper jsonMapper = new JsonMapper();
Unwrap your classes into separate files. This makes the code much easier to read and reuse.
test in your package name is very unusual, and probably not intended.
Test classes typically have the same name as the class they test suffixed with Test, such as JsonMapperTest.
Tests are not written in main methods.
Having getters and setters for everything is a code smell - not necessarily bad, but often misused. Your application doesn't do anything yet, so it's difficult to tell whether any of them will be necessary, but in general I would not add getters and setters until I know I need them.


Produce the nth lexicographic permutation of a string consisting of letters H and V

Let P(n,m) be the number of permutations of n Hs and m Vs.  For m>0 and n>0, P(n,m) = (n + m)!/(n! * m!).

Let's say you want the kth permutation of n Hs and m Vs:

If k <= P(n-1,m), then the answer is an H followed by the kth permutation of n-1 Hs and m Vs.

Otherwise the answer is a V followed by the (k-P(n-1,m))th permutation of n Hs and m-1 Vs.


You should consider any DRYing efforts in terms of its effects on code clarity. I don't think that trying to reduce foo(foo(bar)) is worth the reduced clarity. Now, if we're trying to reduce foo(foo(foo(foo(foo(bar))))), that's something else. One way you can do that is using reduce:

5.times.reduce(1 << 64) { |x,| Math.sqrt(x) }
=> 4.0

5.times.reduce('/a/b/c/d/e/f.txt') { |x,| File.dirname(x) }
=> "/a"


Retrieving the nth term of an infinite stream

Two modifications that I would make right away would be:

to use iterables instead of a generator function as parameter to allow for more genericity: this way I could use nth_term using either triangle_stream() or itertools.cycle('ABCD') as parameters;
to index elements in base 0 instead of base 1, so nth_term(triangle_stream(), 0) would return 1 instead of looping indefinitely and nth_term(triangle_stream(), 1) would return 3 instead of 1.

Now, making the function accept any iterable, I would use something along the lines of the second version this will be closer to my final proposition that will raise StopIteration if there is not enough elements instead of silently returning None ("Errors should never pass silently."). But applying both suggestions would lead to:

def nth_term(iterable, n):
    """Returns the nth term of any iterable."""
    for i, x in enumerate(iterable):
        if i == n:
            return x

or

def nth_term(iterable, n):
    """Returns the nth term of any iterable."""
    x = iter(iterable)
    for i in range(n):
        next(x)
    return next(x)

Now, instead of manually calling next on the iterator in the second version, I would ask zip to do it for me. Chances are that the execution will spend less time in the Python interpreter and more in the C part of zip and so be faster:

def nth_term(iterable, n):
    """Returns the nth term of any iterable."""
    iterator = iter(iterable)
    for _ in zip(range(n), iterator):
        pass
    return next(iterator)

Lastly, I would use existing tools to perform the iteration for me: itertools.islice is exactly what we need. In fact, your very function is already listed in the itertools recipes:

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

I would however remove the default value, especially in the case of an infinite iterable:

def nth(iterable, n):
    "Returns the nth item or raise StopIteration"
    return next(islice(iterable, n, None))

A completely unrelated note, but I would move the yield x at the beginning of the loop in triangle_stream so that you don't have to write it twice:

def triangle_stream():
    """ Infinite stream of triangle numbers. """
    x = step = 1
    while True:
        yield x
        step += 1
        x += step

And since step starts at 1, and never stop incrementing one by one, I would use itertools.count(1):

def triangle_stream():
    """ Infinite stream of triangle numbers. """
    x = 0
    for step in itertools.count(1):
        x += step
        yield x

Now triangle_stream only accumulates values from itertools.count(1), well time to make use of itertools.accumulate:

def triangle_stream():
    """ Infinite stream of triangle numbers. """
    return itertools.accumulate(itertools.count(1))

or, to make it more obvious that you get a generator by calling triangle_stream:

def triangle_stream():
    """ Infinite stream of triangle numbers. """
    yield from itertools.accumulate(itertools.count(1))


Using setTimeout to get scrolling chat window to work, but doesn't feel like the ideal solution

If you find yourself using setTimeout and want to be more angular, check out the $timeout service in the AngularJS API.

In addition, for your purposes, you might be better off using $evalAsync.

$evalAsync waits for at least one digest cycle before executing the expression, which might be enough for the DOM to have the new elements added (though not yet rendered). This can prevent the "flicker" that you otherwise get from waiting for elements to render before manipulating them. The only reason to not use $evalAsync would be if you're dependent on the DOM rendering for accuracy.


Excel Import Data from Different Workbook Dynamic Headers

Copying and pasting isn't necessary and interferes with the user's paste cache. Clear the target column of data and then set a range in the target the same size as the source. Then use an assignment statement:

TargetRange.Value = SourceRange.Value


Find the maximum number in an array of numbers

Undefined Behaviour

If you execute this code with n DB 0, it returns without setting ch to any value, leaving the result as undefined.

Signed Length

mov dl,0h
mov dh,n

cmp dl,dh
jge end

If n happens to be between 128 and 255, the jge will treat the comparison as if it was a signed comparison, and since 0 is not greater than or equal to any value between -128 and -1, inclusive, immediately jump to the end, again leaving ch as an undefined value.

You should use jae instead, so you can have up to 255 values in array.

Signed comparison

Does your array of values represent unsigned bytes, or signed bytes?  If your array contains 0FFh, is that the largest possible value, or one smaller than zero?

If the data is supposed to be signed, you're good.  If it was supposed to be unsigned bytes, you again should change the jle to jbe.

Unnecessary Register Usage

You execute mov cx,0h, but nowhere do you use cl, so are unnecessarily destroying cl.

You execute mov ah,[bx+si] and use mov ax,0h to clean-up at the end.  Again, nowhere have you used al, so you've unnecessarily destroyed al.

If you used cl instead of ah, you wouldn't need to destroy ax at all.

Use of si appears unnecessary.  Instead of based-index addressing mode:

mov cl,[bx+si]
inc si

you could use register indirect addressing mode:

mov cl,[bx]
inc bx

Better Registers

cx is the standard for loop counts.  ax is the standard for function return values.  si is the standard for source indexing.  So ...

Have your function store and return the maximum in al.  Use ah to fetch values from the array, and zero it at the end.  As a bonus, ax could also be considered the return value.  (If the array is intended to hold signed data, then use cbw to sign extend al into ax instead of zeroing ah.)

If you used cx for your array length, and decrement to zero, you could use one LOOP instruction instead of a pair of instructions to perform the compare-and-branch.  As another bonus, it will already be zero by the end, so you won't need to clear it.

Store the array address in si, and use cx for double duty by using based-index addressing (mov ah, [cx+si]) to index into your array.  Of course, you'll be searching backwards, which still fine for finding the maximum.  You'd just have to be careful to include the 0th value, and exclude the nth value (dec cx before the fetch, not afterwards).

Final tally:

return value in ax
cx zeroed (automatically)
si cleared (manually)
All other registers unchanged.


One possibility is to create a method that accepts all possible parameters, and have that method gracefully handle null values, or use the Null Object pattern for those parameters. getSortedObjectsLike(query, orderby); seems like a good candidate, if you could pass nulls for query and orderby or new EmptyQuery() and new NoOrderBy().

pro : no need for method selection, simply evaluate whether a parameter is available or not, and pass null or Null Object if unavailable.
pro : simplified API
con : adding parameters in the future will involve increasing the complexity of the one method that handles all parameters (can probably be mitigated with some refactoring)
con : implementation of the method that handles all parameters may degrade into the kind of method selection we try to avoid here.

Alternatively you could use introspection, and select a method based on the available parameters.

pro : adding future parameters (if done judiciously) will not affect the method selection implementation
con : every added parameter will double the number of methods needed on the API (for every existing one, we'll need one that also has the new parameter)
con : harder to debug
con : hides dependencies
con : query and orderBy are currently the same type, introspection can't tell them apart


Here is the performance test for these two and couple more approaches (one suggested by @elclanrs in the comments).

The performance differences will vary significantly across different browsers, and even different version on same browser, as browser these days try to optimize javascript very aggressively.

Unless you are dealing with very large arrays or this operation is performed repeatedly in quick succession, I would suggest you to use simplest and clearest approach. But, that being said the loop solution is also not that complex or big anyway (and it performs better than others especially on firefox)


Generic methods for serializing and deserialzing xml files using streams

writerSettings.IndentChars = "    "; // 4 spaces

by using

writerSettings.IndentChars = string.Empty.PadRight(4, ' ');

you wouldn't need that noisy comment.

One wouldn't expect that a passed in Stream get closed inside that method. The closing of a Stream should only belong to the creator of that stream.

In extension methods you should always check the argument which is reffered by this if it is null.
This is because that method can also be called like so

StreamExtensions.SerializeObject<someType>(null, someObject);

By checking (stream == null) and throwing an ArgumentNullException no unnecessary objects like XmlWriterSettings will be created.

Otherwise than the mentioned points your code looks clean and is easy to read.


I note three potential problems with your approach, both dealing with special characters in filenames, as well as  one comment on the example usage.

for with find

Consider a directory structure where some paths have spaces in them, say:

Source
├── Constants.h
└── Main Loop.c

(One could argue the wisdom of using spaces in paths, but your script should be able to deal with them anyway.) What would find . -type f output?

./Source/Constants.h
./Source/Main Loop.c

What would for path in $(find . -type f); do echo $path; done output?

./Source/Constants.h
./Source/Main
Loop.c

That's right; for splits on whitespace, breaking your paths. This is a notorious issue. Fortunately, that page provides a solution:

find . -type f -print0 | while IFS= read -r -d '' path; do echo $path; done

echo -e

Look at this line:

echo -e "\n**$path** ($bytes in $lines)\n"

You're substituting path in, and then telling echo to interpret the resulting text. That suggests that if path has an escape sequence in it, echo will interpret it. Indeed, it does:

% path='x\ay'
% touch "$path"
% echo -e "$path"
xy

(The \a was interpreted as "sound the bell.") Instead of using echo -e, consider passing the special characters directly to echo. You can make Bash interpret ones before passing it to echo by using $'':

% echo $'\n'"**$path** ($bytes in $lines)"$'\n'

Markdown

Markdown cares about special names, too. What if I had a file named a** b **c? Your script would give me a header:

**a** b **c**

  a b c

But that's probably not what you intended. You probably want to enclose it in backticks:

**`a** b **c`**

  a** b **c

But even that's not enough. What if my file names have backticks, like, say, a` b `c?

**`a` b `c`**

  a b c

That's no good! You have to then double-backtick it:

**``a` b `c``**

  a` b `c

Essentially, you have to count the maximum number of consecutive backticks and enclose it in that-number-plus-one of backticks.

Example usage

You suggest

mdproj.sh -name *.h -or -name *.cpp > whatever.md

but that will only work when there are exactly zero or one files whose name end with .h and exactly zero or one files whose name end with .cpp. Consider how it expands when there are no files:

mdproj.sh -name *.h -or -name *.cpp > whatever.md

That's right; Bash leaves them in place, passing them on to find, where it looks for files of the form *.h and *.cpp. Since there are no such files (otherwise, Bash would have substituted them in) find will not find the files, and so nothing will happen. What if there is example.h and example.cpp?

mdproj.sh -name example.h -or -name example.cpp > whatever.md

That works fine. What if there are multiple?

mdproj.sh -name foo.h bar.h -or -name foo.cpp bar.cpp > whatever.md

Uh oh. -name takes only one value, but you're passing it two. My find dies with this error:

find: bar.h: unknown option

I always use -regex for that sort of thing:

mdproj.sh -regex '.*\.h' -or -regex '.*\.cpp' > whatever.md

(If I was being cleverer, I might use -E and merge them into one regular expression.)


Yes, use keypress events instead of keydown events.  See example: http://jsfiddle.net/7fmjh/6/ - or a non-jquery example: http://jsfiddle.net/7fmjh/11/


I'll leave an in-depth analysis to the true Python experts, but here are just some quick notes:

Variable and function names: As far as I'm aware, variable and function names should have words/elements separated by underscores (e.g., check_dirs, is_file)

main() function: Instead of having your functionality on the first/default level of indentation, it's good form to wrap it in a def main() and call it via:

if __name__ == '__main__':
    main()

Return values: You can simply return a bool directly rather than having an if/else construction.  e.g.,

return isfile != len(os.listdir(target))

vs.

if isfile == len(os.listdir(target)):
    return False
else:
    return True

Use of global: In my experience, any time I have to use global some_var, it's indicative of bad design.  You should either be using local variables, function arguments, or the constant should be well-defined and not hidden by any local fields.


It's nicely done! One thing I'd pick on though is that your code is full of magic numbers:

var camP = [random(500,1000), random(500,1000)];
// ...
for (var y = -200; y < 200; y+=res)
// ...
for (var x = -200; x < 200; x+=res)
// ...
row.push(noise((x+camP[0])/200, (y+camP[1])/200));
// ...
if (v < 0.49)
// ...
fill(random(30,40), random(100,128), random(20,30));
// ...
fill(random(0,10), random(40,50), random(245,255));

Put these numbers into variables, defined at the top.
By doing so you will effectively give them names,
which could explain what they are.

This is especially recommended for values that you use repeatedly, for example 200.

And when a value depends on another (derived from another),
that relationship can be expressed in the definition.
For example, the difference in the parameter pairs in random(0,10), random(40,50), random(245,255) is suspiciously 10, probably for a reason, which would become clear in the variable definition.
I've no idea how fill works, so these names are probably completely inappropriate, but to illustrate what I mean:

var FILL_RGB_RANGE = 10;
var FILL_R = 0;
var FILL_G = 40;
var FILL_B = 245;

fill(
  random(FILL_R, FILL_R + FILL_RGB_RANGE),
  random(FILL_G, FILL_G + FILL_RGB_RANGE),
  random(FILL_B, FILL_B + FILL_RGB_RANGE)
);


Fix last n commits to previous commit automatically

The error messages should go to standard error, rather than standard output:

  if [ -z "$no_of_commits" ]; then
    echo "You must provide a number of commits to fixup!" >&2
    return 1                                              ### HERE

I don't think there's a good case for returning distinct error codes for missing argument and invalid argument.  Are you ever going to make use of the different status values?


activerecord, refactoring the source code

class User < AR::Base
  has_many :lexemes, :dependent => :destroy
  has_many  :words, :through => :lexemes
end

class Lexeme < AR::Base
  belongs_to :user
  belongs_to :word
end

class Word < AR::Base
  has_many :lexemes
  has_many :users, :through => :lexemes
end

You should normally be able to create word by following code but it seems there is a bug in Rails.

word = @user.words.find_or_create_by_word(token)

Therefore I have changed the model to following. You may remove it when the bug is fixed.

class User < ActiveRecord::Base
  has_many :lexemes
  has_many :words, :through => :lexemes do
        def find_or_create_by_word(token)
            find_by_word(token) || create(:word => token)
        end
  end
end


Merge all text files in a directory and save a temp file

Without going into implementation details, I would suggest looking into the following performance optimisations.

Use buffered reads. If you actually read a line at the time it's pretty time consuming.
Use buffered writes. Instead of writing each new line, collect in a buffer and write in chunks.

For coding review comments, this might be applicable.

The method does 3 different things - merging, syntax checking and bounding rectangle. It might be simpler to maintain and extend the code, if this was refactored into minor helper methods.
Based on the method name, I would be be able to guess what it does.
The initial comments say the method calculates the bounding box, but as the files contain 3d data, would it not be more correct to include the z value.
If the method only need to calculate the bounding rectangle (x,y), is there a need for the merged file to contain the third dimension data ?


Abstract factory design for different cars

The factory in itself is nice (except for one thing), but I have one big problem with your code.

Approach:

You are heavily relying on inheritance over composition. Instead of something so complicated as running that against a Factory, where you return types after a switching an enum you should IMO do the following:

public abstract class Car
{
    private Manufacturer _manufacturer;
    public Manufacturer Manufacturer
    {
        get
        {
            return _manufacturer;
        }
        set
        {
            _manufacturer = value;
        }
    }

    private CarType _carType;
    public CarType CarType
    {
        get
        {
            return _carType;
        }
        //You can even make that stuff read-only by removing the setter
        set
        {
             _carType = value;
        }
     }
}

Implementation:

When you pass an invalid CarType to the Factory you silently return null. That's somewhat unfriendly to the user. Factories are expected to either return a meaningful value or throw an exception. If you allow returning of null, you make the user of the factory do additional null-checks. That is not nice...

Instead you should do the following:

default:
    throw new IllegalArgumentException("CarType not found");


Find neighboring PINs on a numeric keypad

We can simplify this quite a bit.  At a high level, note that all you are doing is:

Converting each digit of the input to an array of possible neighbors.
Now you have an array of neighbor arrays.
The answer is simply the cartesian cross product of those neighbor arrays.
Sort them.
Turn the into back into strings.

The cartesian cross-product is a simple utility method.

The neighbor possibilities are more compactly expressed as a JS object than by a switch statement, and this representation also makes it easy to map over them.

Putting it all together we get:

function xprod(...arrays) {
  return arrays.reduce((m, x) => m.flatMap(
    results => x.map(elm => results.concat([elm]))
  ), [ [] ])
}

function possibleCodes(code) {
  const neighbors = {
    '1': [1, 2, 4],
    '2': [1, 2, 3, 5],
    '3': [2, 3, 6],
    '4': [1, 4, 5, 7],
    '5': [2, 4, 5, 6, 8],
    '6': [3, 5, 6, 9],
    '7': [4, 7, 8],
    '8': [0, 5, 7, 8, 9],
    '9': [6, 8, 9],
    '0': [0, 8],
  }
  const possibilitiesByDigit = code.split('').map(x => neighbors[x])
  return xprod(...possibilitiesByDigit).map(x => x.join('')).sort()
}


Using the XOR operator to calculate a checksum

There are situations where an infinite loop while (true) is warranted, this is not one of them. The code implies that the loop shall be broken when dividerPost reaches zero. Say it explicitly:

        while (dividerPos > 0) {
            if (idx == dividerPos) {
                count += (length - dividerPos);
                --dividerPos;
                idx = 0;
                continue;
            }

            checksum ^= count;

            ++idx;
            ++count;
        }
        return checksum;

Now it is easy to see that the body of the loop is another loop in disguise. Again, be explicit:

        while (dividerPos > 0) {
            for (idx = 0; idx < dividerPos; idx++, count++) {
                checksum ^= count;
            }
            count += (length - dividerPos);
            --dividerPos;
        }

Now it is clear what the code is doing, and what it is doing inefficiently. An immediately identified bottleneck is an inner loop. What it does, it compute an xor of a range of numbers The first hit for a xor of a range query is this discussion. Study it, and see how it is applicable here. That itself will give your code a boost. Then try to optimize the outer loop.

PS: It is crucial to understand that the language doesn't matter.

PPS: Sorry if I sound harsh, but when I say study, I mean study. Don't skim. Understand how it works. Prove that it works correctly.

PPPS: Both answers in the page you've linked miss the point.


Embolden parts of auto-complete suggestions that don't match the query

Based on the current context available, if your query is not to be treated as a regex/custom pattern, I think a simple string.split should be enough. I am not that familiar with conventions in the JS world, but the last time I had worked with it, function names used to be in camelCase.

Also note that I am using the template literals when returning from bolden function; which should actually be named unemphasize (or unbold or normaliser).

function bolden(value, query) {
  if (!value) return;
  let splt = value.split(query)
  return splt.join(`<span style="font-weight:normal">${query}</span>`)
}

let tests = new Map([
  ['some', 'e'],
  ['things', 'thi'],
  ['other', 'te'],
  ['looooooooong', 'o']
])

for (let [v, q] of tests)
  console.log(bolden(v, q))


First of all, using the tag to distinguish between views is almost everytime (there are exceptions) a bad idea. It's much cleaner to use your own variable (pointers to view, BOOL flags).

10 is a magic number. What does it mean? Use a constant.

Use methods. Four levels of if are terrible. Extract the code into methods.

if ([self isVerticalScrollingDisabled] || [self isHorizontalScrollingDisabled]) {
    return;
}

[super setAlpha:alpha];

By the way, changing the behavior of a method in a subclass (the method sets alpha only if some conditions are valid) is smelly from architecture point of view. Declaring a special method, e.g. setAlphaIfScrollingEnabled: would be better.


Obfuscation of email and phone using JavaScript

First of all, ES2015+ onwards have template literals forw easier interpolation of string and data. For instance:

function fix_m_link(){
  var item1 = '@'
  var item2 = '.'
  var m_clear_text = `test${item1}example${item2}com`
  document.getElementById('m_link').innerHTML = `<a href="mailto:${m_clear_text}">${m_clear_text}</a>`
}

Also, JavaScript uses camel case for naming. So you might want to change fix_m_link and m_clear_text.

Putting code in one line makes it hard to read. If you have a build step, let a minifier do this. If the code is very short (like in your question), the extra kilobytes saved from omitted newlines is not worth making the code unreadable. Write code for humans to read.

Now if you really want to obscure your email, use a contact form instead. Some CMSes support this out of the box. And if your site is static, there are third-party services that allow you to embed a contact form. Most of them also support captchas, which will deter automated form submissions.


Python snippet for finding word in string

I don't like the name of your function. Find what in string? Something like find_all_substring_indices() better describes what the function does
You aren't finding words, you're finding substrings. Your code would find the word "car" twice in "carcar" even though we would consider "carcar" a single word. You mention the re package. Presumably, you're talking about word boundaries. They behave a little differently (punctuation can be a word separator). But, since your original question doesn't behave that way, it is not a refactoring for me to suggest how to do that (nor is it on topic, "how do I replicate regex word boundaries?" is a question for StackOverflow)
Indices should be snake_case. Only class names are UpperCamelCase
Don't use a tuple for indices! Every time you append to it you have to create a new object because tuples are immutable. In fact, you are creating two: one for the (i,) and then another one when you do indices + (i,). Use a list: indices = [] then indices.append(i)! That's what they're meant for!
range(0, len(string)) can just be range(len(string))
string[i:i+wordlength] == word is the same thing as (and much less clear than) string[i:].beginswith(word)
All of this slicing is really inefficient, especially given there is also a string method that does what you want: index
You should unittest your code! I suspect you have a bug in that if your "word" is "FooFoo" it will be found twice in "Little bunny FooFooFoo" (once at the beginning of "FooFooFoo" and once three characters into "FooFoo"). Surely, words shouldn't be able to overlap like this.
Add """Docstrings.""" to document what your function does.

You should just be repeatedly using index until you read the end of the string. This is more efficient than doing slicing by yourself or sliding the substring character by character along your string. Stealing mostly from SO:

def find_all_substrings(string, sub):
    start = 0

    while True:
        try:
            start = string.index(sub, start)
        except ValueError:
            break

        yield start
        start += len(sub)

This is a generator, if you still want a tuple returned you can just build one up instead (but at a list first!):

def find_all_substrings(string, sub):
    indices = []
    start = 0

    try:
        while True:
            start = string.find(sub, start)
            indices.append(start)
            start += len(sub)
    except ValueError:
        pass

    return tuple(indices)


How to refactor this function to solve cyclomatic issue?

You could try using a hash that maps "locations" to "fa-building", "monitored_places" to "fa-globe", and so on, with a default value of "fa-diamond".


var users = service.getUsers();
        List<User> value = new ArrayList<User>();
        var usersPreferences = _userRepo.findAll();

Personally, I dislike var with a passion because of exactly such usage. I can't see half-the types, so I have to make a few assumptions here.

for(int i =0; i < users.size(); i++){

First, I'm against using single-letter variable names, with the only exception being dimensions. Having said that, you can most likely use a for-each loop here (I'm not seeing the type of users, but I assume that it is a List).
for (User user : users) {

List<User> value = new ArrayList<User>();

This variable name could be better, because it doesn't make much sense.

            boolean[] isFound = {false};
            usersPreferences.forEach(prefUser -> {
                if(prefUser.getId() == user.getId()){
                    User newUser = new User(user, prefUser);
                    value.add(newUser);
                    isFound[0] = true;
                }
            });
            if(!isFound[0]){
                User newUser = new User(user);
                    value.add(newUser);
            }

Instead of using a lambda, you could use a simple for-each loop:
            boolean isFound = false;
            for (UserPreference userPreference : userPreferences) {
                if(prefUser.getId() == user.getId()){
                    User newUser = new User(user, prefUser);
                    value.add(newUser);
                    isFound = true;
                }
            }
            if(!isFound){
                User newUser = new User(user);
                value.add(newUser);
            }

Even better would be if you would extract the second loop into its own function, as that would reduce the complexity of your logic:
private User createUserWithPreferences(User user, List<UserPreferences> userPreferences) {
    for (UserPreference userPreference : userPreferences) {
        if (userPreference.getUserId() == user.getId()) {
            return new User(user, userPreference);
        }
    }

    return new User(user);
}

List<User> createdUsers = new ArrayList<>();

for (User user : users) {
    createdUsers.add(createUserWithPreferences(user, userPreferences);
}


Like I said before, the reason why this takes a lot of time is because the number of steps is proportional to the square of the number of disks.

But there are some other improvements to be made to this code.

range

list(reversed(range(1, args.disks + 1))) can be done more easily as list(range(disks, 0, -1))

Global variables

Your image saving algorithm uses a lot of global scope (args.filename, steps,...), and with the src.reverce() even modifies these global variables, which is a sure way to introduce difficult to find bugs. If your function needs those parameters, pass them as arguments, and certainly don't change them.

You can prevent SOURCE, HELPER, TARGET to need in global scope, by passing these along in a dictionary. You can also use a namedtuple:

source = list(range(disks, 0, -1))
target = list()
helper = list()
state = dict(
    source=source,
    target=target,
    helper=helper
)
hanoi_gen(disks, source, helper, target, state)

Variable naming

I had to look really well at the code to find out what certain variables were. cells for example is the width of the image, peg is the maximum with of a peg etc. Name your variables clearly. s, h, t in zip(src, hlp, trg) is another example that can do with better names.

Immutable variables

You use lists throughout your code. The advantage of lists is that they are mutable, but this is also the disadvantage. To make sure other code doesn't inadvertently change your data, use immutable containers like tuple where appropriate. So instead of SOURCE[:], I used tuple(...).

Generator

Instead of instantiating all those lists at the same time, you can work with generators:

def hanoi_gen(disks, source, helper, target, state):
    if disks:
        yield from hanoi_gen(disks - 1, source, target, helper, state)
        target.append(source.pop())
        yield tuple(state['source']), tuple(state['target']), tuple(state['helper'])
        yield from hanoi_gen(disks - 1, helper, source, target, state)

def solve_tower(disks):
    source = list(range(disks, 0, -1))
    target = list()
    helper = list()
    yield tuple(source), tuple(target), tuple(helper)
    state = dict(
        source=source,
        target=target,
        helper=helper,
    )
    yield from hanoi_gen(disks, source, helper, target, state)

steps = tuple(solve_tower(2))
assert steps == (
    ((2, 1), (), ()),
    ((2,), (), (1,)),
    ((), (2,), (1,)),
    ((), (2, 1), ()),
)

Magic numbers

There are some magic numbers in your code, 10, 40, 5, ...

Better is to extract global constants from this:

BUFFER_PEG = 10
LINE_WIDTH = 1
BUFFER_STEP = 5
WHITE = 1
BLACK = 0

And use them like:

image_width = disks * 2 * 3 + 4 * BUFFER_PEG

BLACK and WHITE can also be done with an enum.IntEnum:

from enum import IntEnum
class Color(IntEnum):
    BLACK = 0
    WHITE = 1

DRY

Compartmentalize!

There is a lot of repeated code, which makes this hard to maintain and test:

from itertools import repeat

def whitespace(width, image_width):
    return repeat(Color.WHITE, width * image_width)

def line(width, image_width):
    return repeat(Color.BLACK, width * image_width)

Create easy to use generators to add whitespace or black lines.

Pad the disk

def pad_disk(disk_width, num_disks):
    blank_width = num_disks - disk_width
    yield from repeat(Color.WHITE, blank_width)
    yield from repeat(Color.BLACK, disk_width * 2)
    yield from repeat(Color.WHITE, blank_width)

Centrally pads a disk to twice the number of disks in play.
This can be easily tested: the portion of a disk of width 1 in a stack of 4 disks:

assert tuple(pad_disk(1, num_disks=4)) == (1, 1, 1, 0, 0, 1, 1, 1)

Format a row

def buffer_peg():
    return repeat(Color.WHITE, BUFFER_PEG)

def format_row(disks, num_disks):
    yield from buffer_peg()
    for disk_width in disks:
        yield from pad_disk(disk_width, num_disks)
        yield from buffer_peg()

This can be easily tested like this:

row = [2, 0, 1]
num_disks = 4
assert tuple(format_row(row, num_disks)) == tuple(chain(
    buffer_peg(),
    (1, 1, 0, 0, 0, 0, 1, 1,),
    buffer_peg(),
    (1, 1, 1, 1, 1, 1, 1, 1,),
    buffer_peg(),
    (1, 1, 1, 0, 0, 1, 1, 1,),
    buffer_peg(),
))

Format individual steps

Here, I use a small helper function to reverse the peg, and pad it with 0s:

def pad_left_reverse(peg, size, fillvalue=0):
    yield from repeat(fillvalue, size - len(peg))
    yield from reversed(peg)

Then all of this:

src = step[0]
hlp = step[1]
trg = step[2]
size = max(len(src), len(hlp), len(trg))
for _ in range(size - len(src)):
    src.append(0)
for _ in range(size - len(hlp)):
    hlp.append(0)
for _ in range(size - len(trg)):
    trg.append(0)
src.reverse()
hlp.reverse()
trg.reverse()

Can be replaced with:

def format_step(step, num_disks):
    pegs = map(
        lambda peg: pad_left_reverse(peg, num_disks, fillvalue=Color.WHITE),
        step
    )

And on the plus-side, this doesn't reverse the original input.

I replaced the size = max(len(src), len(hlp), len(trg)) with the number of disks, to keep all the steps equally high. If you can live with the uneven heights, size = len(max(step, key=len)) is an alternative formulation.

    for row in zip(*pegs):
        # print(row)
        yield from format_row(row, peg_width)

Replaces the next 20 lines.

step = [2, 1], [5,4,3], []
num_disks = 5
step_data = list(format_step(step, num_disks))

Outputs something like:

1111111111111111111111111111111100000011111111111111111111111111111111
1111111111111100111111111111111000000001111111111111111111111111111111
1111111111111000011111111111110000000000111111111111111111111111111111

Format the steps

def format_steps(steps, image_width, num_disks):
    for step in steps:
        yield from whitespace(BUFFER_STEP, image_width)
        yield from format_step(step, num_disks)
        yield from whitespace(BUFFER_STEP, image_width)
        yield from line(LINE_WIDTH, image_width)

This speaks for itself.

Context managers

If you open resources that need closing afterwards, like a file or a PIL.Image, use a with-statement.

The main

if __name__ == '__main__':
    num_disks = 5
    steps = solve_tower(num_disks)
    image_width = num_disks * 2 * 3 + 4 * BUFFER_PEG
    data = list(format_steps(steps, image_width, num_disks))
    with Image.new('1', (image_width, len(data) // image_width)) as image:
        image.putdata(data)
        name = 'my_hanoi.png'
        image.save(name)

All-in-all this code is slightly longer than your code, and will not necessarily be much faster, it is a lot clearer for me, and a lot more parts can be individually tested.

The full code can be found here, and some tests here.


Writing my first binary search by myself

Avoid deeply nested if-statements
Deeply nested if-statements are hard to read. You can reduce the amount of nesting here by inverting the first if-statement and returning early, and avoiding the else-statement by using the fact that the if part already returns:
int binarySearch(int arr[], int low, int high, int n)
{
    if (low > high)
    {
        return -1;
    }

    int i = (high + low) / 2;
    if (arr[i] == n)
    {
        return i;
    }

    if (arr[i] > n)
    {
        return binarySearch(arr, low, i - 1, n);
    }
    else
    {
        return binarySearch(arr, i + 1, high, n);
    }
}

Use size_t for array indices
When dealing with sizes, counts and indices, prefer using size_t to hold their values, as that type is guaranteed to be big enough to cover any array that can be addressed by your computer.
size_t is unsigned, so it might look like you can't return -1, but it turns out that integer promotion rules make it work regardless: you can return -1, and the caller can check if (binarySearch(...) == -1), although perhaps better would be to create a constant for this, similar to std::string::npos.
Try to make it more generic
Your binary search algorithm works for plain arrays of integers, but it doesn't work for anything else. What if you want to search in an array of floats? What if you want to search in a std::vector? The standard library provides std::binary_search() which can work on a variety of containers holding any type that can be compared. It might be good practice to try to make the interface to your binary search implementation similar to that of std::binary_search(). It is not as hard as it looks! You can start by making it a template for arrays of different types:
template<typename T>
size_t binarySearch(T arr[], size_t low, size_t high, const T &n)
{
    ...
}

Once you have done that excercise, try to have it take two iterators, and return an iterator to the element if it's found, or last if not (assuming last now points to right after the end of the range to search):
template<typename It, typename T>
It binarySearch(It first, It last, const T &n)
{
    ...
}

This is a bit more advanced; you have to work within the limitations of the iterators.
Last you might want to add another template parameter, typename Comp, so you can provide a custom comparison operator.


Calculate course module credits from individual assessment scores

Minor stuff: your backticks are distracting, and unnecessary in most (all?) cases. I'd delete them.
Your use of TRUNCATE seems like a formatting concern and not a query concern. I'd expect that a query like this just return a full, floating-point number, and leave it up to the application as to whether rounding or truncation needs to be performed.


"Who are you, and where do you live?" — a Q&A exercise

I have found a couple of things that could help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Avoid the use of global variables

I see that a and b are declared as global variables rather than as local variables. It's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable. It's a bit strange because you have done that with variable c in your _tmain function.

Use meaningful variable names

The variable names a, b, and c are not at all descriptive. Better names might be name, age and address.  Doing so makes your code easier to read, understand and maintain.

Don't use system("cls")

There are two reasons not to use system("cls") or system("Color 1A").  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named cls or Color, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a separate functions cls() and color() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++.

General portability

This code could be made portable if, in addition to the changes in the previous point, you omit the Windows-only include files #include "stdafx.h" and #include <Windows.h> and use the standard int main() rather than the Windows-only _tmain.  See this stackoverflow question for a longer explanation.

Fix your formatting

There are abundant examples here of C++ code that is well formatted.  This code has peculiar indentation that makes it difficult to tell when a function begins and ends.  Fixing that would help.

Make it clear when loops end

The code currently uses while (true) in a number of places, but it doesn't really loop infinitely.  It's better, generally, to have the loop exit condition explicitly stated.  For example we could rewrite your enterName() function:

string enterName()
{
    do
    {
        cout << "what is your name?: ";
        getline(cin, a);
        if (a == "")
            cout << "Let's try that again." << endl;
    } while (a == "");
    return a;
}

Variable range checking

Your verifyAge() routine seems to think that it's impossible for people to be 95 year old or older, but I personally know people that old who still use a computer.  A number of 130 might be a safer bet to use as an upper range.

In all, the program actually functions as intended, so you are indeed on your way.


A good way to think about this problem is to list the different cases when a customer is encountered in the list:

The person arrives and there is a bed available => the person gets a tan and the number of available bed decreases by one
The person arrives and there is not a bed available => the person won't tan
The person leaves and they got a tan => the number of available beds increases by one
The person leaves and they didn't get a tan => nothing special happens

When there are no more customers then we need to return the number of people who didn't tan.

This is embodied by the following function:

def step(avail: Int, tanned: Set[Char], not_tanned: Set[Char], customers: List[String]): Int = {
  customers match {
    // case 3 above
    case c::cs if tanned(c) => step(avail+1, tanned, not_tanned, cs)
    // case 4 above
    case c::cs if left(c) => step(avail, tanned, not_tanned, cs)
    // case 1 above
    case c::cs if avail > 0 => step(avail-1, tanned+c, not_tanned, cs)
    // case 2 above
    case c::cs if avail == 0 => step(avail, tanned, not_tanned+c, cs)
    // exit condition, no more customers
    case Nil => not_tanned.size
  }
}

Since the problem statement says that no customer visits more than once and everyone who doesn't get a tan leaves before the people getting tans do it isn't necessary to remove people from the sets or maintain a list of waiting customers in case a bed opens up.

The step function above needs to be called with an initial state which, assuming needs is the number of beds in the salon and customers is the string specified in the problem, is

step(needs, Set(), Set(), customers.toList)

It is possible to transform the step function into a fold which would remove the explicit list traversal, but in my opinion that would hurt the readability of the code.

A complete version of the code is

object tanning {
  def howmanyleft(nbeds: Int, customers: String): Int = {
    def step(avail: Int, tanned: Set[Char], not_tanned: Set[Char], customers: List[Char]): Int = {
      customers match {
        case c::cs if tanned(c) => step(avail+1, tanned, not_tanned, cs)
        case c::cs if not_tanned(c) => step(avail, tanned, not_tanned, cs)
        case c::cs if avail > 0 => step(avail-1, tanned+c, not_tanned, cs)
        case c::cs if avail == 0 => step(avail, tanned, not_tanned+c, cs)
        case Nil => not_tanned.size
      }
    }
    step(nbeds, Set(), Set(), customers.toList)
  }
  def main(args: Array[String]) {
    println(howmanyleft(2, "ABBAJJKZKZ"))
    println(howmanyleft(3, "GACCBDDBAGEE"))
    println(howmanyleft(3, "GACCBGDDBAEE"))
    println(howmanyleft(1, "ABCBCA"))
  }
}


Microservice that fetches data from REST repository endpoints on Github

The two functions you broke out (LanguagesCounter, and RepoListLanguages) both could be simplified significantly using list comprehension. You seem to be thinking in terms of loops and appending to lists instead of generating them in one go which is more pythonic. Add in the Counter function from collections and RepoListLanguages becomes a relatively trivial one liner.
Those are both at the top of the rewrite below so you can see them in action.
Beyond that, the only real changes I made were using lower_camel_case per pep8 guidelines, changing a few variable names for clarity, and pulling the messy code at the bottom into functions. Functions and clear structure make reading the code much easier for anyone who needs to even if they don't change how it works.
import urllib.request, urllib.parse, urllib.error
import json
import sys
from collections import Counter
from datetime import datetime, timedelta, date
from tabulate import tabulate

from collections import Counter

def language_counter(data):
     return Counter(repo["language"] for repo in data["items"])

def repo_languages(data, list):
    return {
        key: [
            repo["html_url"] for repo in data["items"]
            if key == repo["language"]
        ]
        for key in list
    }

def new_url():
    last_month = datetime.date(datetime.now()) - timedelta(days=30)

    return 'https://api.github.com/search/repositories?q=created:%3E' + last_month.isoformat(
    ) + '&sort=stars&order=desc&page=1&per_page=100'

def get_data(url):
    data_connection_request = urllib.request.urlopen(url)

    unicoded_data = data_connection_request.read().decode()

    try:
            json_data = json.loads(unicoded_data)
    except:
            json_data = None

    return json_data

def validate_or_quit(json_data):
    if not json_data or json_data["total_count"] < 1:
        print(json_data)
        sys.exit('######## Failure To Retrieve ########')

def pretty_print_list(data):
    for key in data:
        print(key, ' language used in')
        for _, item in enumerate(data[key]):
            print(" " * 27, item)

def pretty_print_dict(data):
    data_list = [[key, value] for key, value in data.items()]
    print(
            tabulate(
                    data_list,
                    headers=('Language', 'number of Repo using it'),
                    tablefmt="grid")
    )

if __name__ == "__main__":
    json_data = get_data(new_url())
    validate_or_quit(json_data)

    lang_counts = language_counter(json_data)
    repo_langs = repo_languages(json_data, lang_counts)

    pretty_print_list(repo_langs)
    pretty_print_dict(lang_counts)


We need only 5 maximum elements, for that we don't need to sort whole array. We can use alternative approach

Approach 1: Use 5 local variables and keep track of minimum element in it.

Approach 2: Use Min-heap and insert first 5 elements of array in min-heap, then iterate on array from index = 5, if heap-root is smaller than number in array then extract that number from min-heap, and insert new.


Store nested json repsonses in relational database

You don't use typing properly. Parametrizing generic types should be done using brackets notation (aka __getitem__) not parenthesis (aka instantiation).

You also don't use any feature of dataclasses in your defined classes, so you might as well drop that dependency. Or you could use it properly so that Country(**json_data) will build the whole thing; but:

Keys in the JSON data are not valid python identifiers, you would need to convert them;
You would need to handle converting children "manually" after the __init__ took place;
You will need to swap the order in which you define classes due to scope evaluation.

The closest we would come should be something along the lines of:

from dataclasses import dataclass
from typing import List

def convert_keys(dct):
    return {name.replace('-', '_'): value for name, value in dct.items()}

@dataclass
class Street:
    city_id: int
    name: str
    street_id: int

@dataclass
class City:
    state_id: int
    name: str
    city_id: int
    streets: List[Street]

    def __post_init__(self):
        self.streets = [Street(**convert_keys(street)) for street in self.streets]

@dataclass
class State:
    country_id: int
    name: str
    state_id: int
    cities: List[City]

    def __post_init__(self):
        self.cities = [City(**convert_keys(city)) for city in self.cities]

@dataclass
class Country:
    country_id: int
    name: str
    states: List[State]

    def __port_init__(self):
        self.states = [State(**convert_keys(state)) for state in self.states]

Initiate the call using Country(**convert_keys(json_data)). But this solution doesn't necessary feel cleaner than yours.

Now as regards to using these classes as a mean to store data into a relational database, we need to examine usage.

The DB API 2.0 tells us that you can expect to be able to:

cursor.execute('INSERT INTO Street VALUES (?, ?, ?)', (city_id, name, street_id))

Which means that we need to:

Be able to convert these classes to tuples;
Remove the reverse relationship that we had so much troubles parsing properly Country.states, State.cities, and City.streets).

So here we go, trying to patch our approach. We could use dataclasses.astuple to convert or objects to proper parameters for our query, but we would still need a specific parser to recursively traverse nested JSON layers. Coupling that with the invalid identifiers issue, I don't think storing the data into intermediate classes makes much sense. Instead I would rather write them directly in the database:

def parse_country(cursor, json_data):
    country_id = json_data['country-id']
    name = json_data['name']
    cursor.execute('INSERT INTO Country VALUES (?, ?)', (country_id, name))
    for state in json_data['states']:
        parse_state(cursor, state)

def parse_state(cursor, json_data):
    state_id = json_data['state-id']
    name = json_data['name']
    country_id = json_data['country-id']
    cursor.execute('INSERT INTO State VALUES (?, ?, ?)', (state_id, name, country_id))
    for city in json_data['cities']:
        parse_city(cursor, city)

def parse_city(cursor, json_data):
    city_id = json_data['city-id']
    name = json_data['name']
    state_id = json_data['state-id']
    cursor.execute('INSERT INTO City VALUES (?, ?, ?)', (city_id, name, state_id))
    for street in json_data['streets']:
        parse_street(cursor, street)

def parse_street(cursor, json_data):
    street_id = json_data['street-id']
    name = json_data['name']
    city_id = json_data['city-id']
    cursor.execute('INSERT INTO Street VALUES (?, ?, ?)', (street_id, name, city_id))

And that's pretty much your original code except the data is now in DB and not in memory. Usage being:

conn = # create appropriate DB connection here
with conn:
    parse_country(conn.cursor(), json_data)


If you need to check if a certain method exists you can also check if the object supports it via respondsToSelector: like this:

if ([object respondsToSelector:@selector(openURL:options:completionHandler:)]) {
    [object openURL:...options:...completionHandler:...];
} else {
    [object openURL:...];
}

I think this approach is more flexible than checking the OS version. I've seen many people doing this.

This is similar to how JavaScript programmers check existence of certain JS features: if they checked the browser version instead, the code would be unmaintainable as there are a lot of browsers and they constantly evolve.


remove kth last element from singly-linked list - Follow up

In the function del_element_from_last, when removing the first element of the list, you update llist->head. However, when removing the last element of the list, you do not update llist->tail.
If keeping track of the tail of the list is only intended for building the list, and is not intended to be updated by the function del_element_from_last, then you should not pass the entire struct xllist to the function del_element_from_last. Rather, you should change the function signature to the following, so that the function only has access to the head:
bool del_element_from_last( xlnode **pp_head, int k )

According to the task description, k is guaranteed to be smaller than the list. This means that the list is guaranteed to be not empty. In that case, the line
if(llist->head)
in the function del_element_from_last is redundant, because the condition will always be true.
On the other hand, defensive programming is good programming style. Therefore, it may still be appropriate to keep it.
However, if you decide to keep it, your program should handle both cases properly. If the condition is false, your program will cause undefined behavior, because you read the uninitialized value of last. Therefore, you should probably instead immediately return false when the condition is false.
An alternative to the if statement would be to use the assert macro, like this:
assert( llist->head );
That way, you don't have to provide code to handle both cases. Instead, a diagnostic error message will appear if the variable does not have the expected value (only on debug builds though, not on release builds).


I would say that for it to be semantically accurate, the author should be a part of the blockquote, perhaps using a footer.
You should include a cite attribute if the quote has a source.
The quote content should be inside a paragraph element.
I guess now you don't need the wrapper any more.

&ldquo;Such cool. Much awesome. WOW&rdquo;

       &ndash;
       Doge,
       The Moon

To make it look the same I had to change these bits of CSS:

blockquote {
  font-size: 22px;
  margin: 0;
}

blockquote p {
  background-color: rgb(255, 255, 255);
  border-radius: 6px;
  font-family: Georgia, serif;
  line-height: 1.4;
  padding: 17px;
}

footer.author {
  background-color: transparent;
  font-weight: 500;
  font-size: 22px;
  line-height:22px;
  margin: 24px 0 0 18px;
}

Here's the result.


Your code definitely doesn't work with any number except 3, and it's quite likely you'll make an error if you'll be changing the code to another number. So I'd use

public LinkedList sortMod(int a[], int number)

instead. Also, the code returns null when there's no numbers of any modulus. I.e. sortMod(new int[]{1}) returns null as well as sortMod(new int[]{1, 4, 7, 10, 13}).

You can also try to use Streams, feature of Java 8. For example, the single line

return map.values().stream().map(ArrayList::new).collect(Collectors.toList());

does a lot of job, effectively replacing 10 lines of your code. You can try to make the task in two lines using Java 8 features. Also it works fine with sortMod(new int[]{1, 4, 7, 10, 13}).


Implementing 3Blue1Brown's description of Fourier transform in Python+numpy

As I already mentioned in a comment below your question, scipy has contribution guidelines that tell you what they expect from your code before even thinking about including it into scipy. The major keywords are:

Unit tests
Documentation
Code style

Testing

The first point of this list would also help you to answer your question about the algorithm's correctness automatically. This answers to What data should I use to test an FFT implementation, and what accuracy should I expect? on the Signal Processing Stack Exchange can help you to get an idea on how that might look like. The documentation of the relevant functions (e.g. numpy.fft.fft) in the scipy stack and their associated tests can provide further hints. Since my knowledge on FT, DFT, FFT, WTF (;-) ), and the likes is a bit "rusty", you maybe have to look for ressources more appropriately matching what you intend to do.

Documentation

The documentation part is comparatevely simple. Again, there are guidelines on how to document code associated with the scientific Python stack (everything surrounding numpy/scipy). An example:

def polar_to_complex(radii, angles):
    """Return r-phi coordinates to complex numbers

    Parameters
    ----------
    radii, angles: array_like
        radial and angular component of the polar coordinates. Both input have
        to have the same shape

    Returns
    -------
    out: ndarray
        complex representation of the given r-phi coordinates
    """
    return radii * np.exp(1j * angles)

This is also commonly called numpydoc oder NumPy-style documentation. It's a very feature rich style and I highly recommend to have a look at the ressource linked above to learn more.

Regarding type annotations: they are just that, annotations or hints. They are not checked during runtime, i.e. the Python interpreter does not care about your carefully crafted type hints. Static code analysis tools like mypy and pylint are the tools that would make use of them to tell you about flaws that can be checked without actually running your code, hence the name "static code analysis". If you really want to make sure that all the inputs are how you expect them to be, you will have to write your own validation code raising appropriate exceptions at runtime to tell whoever uses your library incorrectly that they're doing so.

Style

The contribution guidelines clearly describe that your code is supposed to conform to PEP 8 conventions. There is also a hint to use automatic tooling in order to check your code in that regard. In case you don't like there suggestion on what tool to use, fear not! This answer on Code Review meta lists quite a few other tools that can help you in your endeavours to write beautiful Python code. Among others, they should tell you to use lower_case_with_underscore names for function and variable names, avoid whitespace around = when used in keyword-arguments, and that there should be two blank lines between functions at the module level.

Performance

I have not actively checked the performance of your implementation compared to what's already implemented in numpy/scipy, but from my experience and since Fourier transformations are a very widely used tool, I highly suspect that such a simple implementation will be no match for current state-of-the-art implementations likely present in numpy/scipy. As I said, I did not check, so I might be wrong here.

If I were to guess, sorting is likely the single most costly operation in your algorithm, but again I have not measured it. If you are willing to look into this, cProfile and timeit are likely the modules to look at.


You could just do:

def published?
  !hidden? && published_at.present? && published_at < DateTime.now
end

However I would probably define something like:

def visible?
  !hidden?
end

or possible even

def visible?
  !hidden? && published_at.present?
end

And then

def published?
  visible? && published_at < DateTime.now
end


The algorithm should be:

Lose any unimportant contest where doing so does not lose luck.
Win any contest where doing so does not lose luck.
Lose the up to k contests where winning would cost most luck.

At the moment, you assume winning never gains luck and losing never loses luck.

You do a full sort each iteration for point 3, which with a cost of \$O(k*\log(k))\$ leads to \$O(n*k*\log(k))\$.
Using a fixed-length priority-queue instead only needs \$O(\log(k))\$ per insert / replace, resulting in \$O(n*\log(k))\$, a factor of \$k\$ better.
While C++ doesn't have exactly that, <algorithm> provides pop_heap() and push_heap() which is enough to replace the head if the new item is less expensive. A custom replace_heap() or exposed down_heap() would be slightly more efficient, but for that you have to branch out.

Now the form:

<bits/stdc++.h> is non-standard and likely far more than you actually need. Unless coupled with use of precompiled headers, it will slow down compilation at least, if not bloat the resulting executable. Replace it with the standard includes. See "How does #include <bits/stdc++.h> work in C++?".
Never import wholesale any namespace which isn't designed for it. Doing so leads to conflicts, silent changes of behaviour, and generally brittle code. See "Why is “using namespace std” considered bad practice?".
Don't use a std::vector if all you need is an array of statically-known length.
Such overkill costs. Anyway, a std::tuple<int, bool> or std::pair<int, bool> would be an even better fit.
If one can rely on anything, it's that if there is a way to screw something up, it will be done, at the most inconvenient time. Like the input. As it is under the coders control, it isn't quite a fatal defect though.
return 0; is implicit for main().
Small trivial types like char should not be passed by constant reference without good reason, but by value. Doing so avoids the pitfalls of aliasing, and is slightly more efficient. Happily, the compiler should fix that by inlining.
Getting and storing input in the loop-condition is actually idiomatic. And it avoids error-prone repetition.
This:

size_t i = 0;
size_t pos = input_string.find(delimiter);

while (pos != string::npos) {
    splits.push_back(input_string.substr(i, pos - i));

    i = pos + 1;
    pos = input_string.find(delimiter, i);
}

Could simply be:

for (size_t i = 0, pos; (pos = input_string.find(delimiter, i)) != string::npos; i = pos + 1)
    splits.push_back(input_string.substr(i, pos - i));

The final call to .substr() needlessly contains a complicated calculation for the second argument. Just leaving it out will do the right thing.

splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

As an aside, split_string() would be better off accepting a std::string_view and returning a std::vector<std::string_view>. Less allocation-overhead.
There is no reason to pass the contests by copy. Either move them, pass a constant reference, or preferably use a std::span (C++20 or GSL (Guideline Support Library)).
Yes, there's no need to forward-declare functions defined before first use, which is a good thing. But above all, please try to be consistent which option you use.

Finally your code:

There's no reason at all to keep track of parts of the result-sum separately. Just combine them already.
Using auto instead of explicit types avoids errors and reduces clutter. Thus, almost always auto. That also counts for the form.

The rest was handled in the algorithm section.

Using the better algorithm:

int luckBalance(int k, vector<vector<int>> contests) {
    // Keeping the bad interface because they force it
    auto r = 0;
    const auto heap = std::make_unique<int[]>(k);
    for (const auto& x : contests) {
        if (!x[1] || x[0] <= heap[0]) {
            r += std::abs(x[0]);
        } else {
            std::pop_heap(heap.get(), heap.get() + k, std::greater());
            r -= heap[k - 1];
            heap[k - 1] = x[0];
            std::push_heap(heap.get(), heap.get() + k, std::greater());
        }
    }
    return r;
}

Could be improved by not pre-filling the heap with zeroes, but I'm too lazy.


Stop hammering XKCD server

You basically wrote a denial-of-service attack, since you try to connect as fast and as often as possible to the server.
By sharing this code on CodeReview, it becomes a distributed denial-of-service.

Just in case it wasn't clear : don't do that.

I suppose the load of XKCD servers is high enough that your code won't make any noticeable difference. Still, the primary goal of your code should be to stay under the radar. Seen from outside, there shouldn't be any difference between launching your script and casually browsing https://xkcd.com/.

It isn't just as a courtesy to fellow developers : you might be banned by the remote servers if you send too many requests too fast.

Solutions

Wait at least one second before downloading any picture. The desired pause might be defined as Crawl-delay in robots.txt.
Remove multi-threading or at least limit the number of threads.
Don't download a file again if it is already in SAVE_DIRECTORY. You can check if it's here, if its size is larger than 0 or if it is indeed a PNG file.

Unrelated note

You know the id for each comic. You should probably write it in the filename : geologic_time.png could be called 2187_geologic_time.png or 02187_geologic_time.png.

This way, comics are sorted chronologically inside SAVE_DIRECTORY.


Add one to a number represented as an array of digits

What you did well
I like that you have:

decently named varaibles
you use good backward looping through the data
the formatting and style is good.

Issues

you are doing a lot of manual copying... Arrays.copyOf() is your friend.
you should be declaring variables where you need them, not at the beginning of the method (temp).
the algorithm is not a natural fit for the problem.... too complicated, and that is why there is the odd offset in your results.

Alternative...
Consider this code alternative, which uses a standard adder-with-carry:
public static final int[] addOne(int[] digits) {
    int carry = 1;
    int[] result = new int[digits.length];
    for (int i = digits.length - 1; i >= 0; i--) {
        int val = digits[i] + carry;
        result[i] = val % 10;
        carry = val / 10;
    }
    if (carry == 1) {
        result = new int[digits.length + 1];
        result[0] = 1;
    }
    return result;
}

The carry is initialized with the value-to-add 1, and it is added to the least significant value.
If the overall addition results in a carry still, then we add a new digit to the result, and, because the sub being added is a 1, we can make assumptions about the result.
Edit:
My test code:
public static void main(String[] args) {
    System.out.println(Arrays.toString(addOne(new int[]{})));
    System.out.println(Arrays.toString(addOne(new int[]{1})));
    System.out.println(Arrays.toString(addOne(new int[]{9})));
    System.out.println(Arrays.toString(addOne(new int[]{3, 9, 9})));
    System.out.println(Arrays.toString(addOne(new int[]{3, 9, 9, 9})));
    System.out.println(Arrays.toString(addOne(new int[]{9, 9, 9, 9})));
    System.out.println(Arrays.toString(addOne(new int[]{9, 9, 9, 8})));
}

and my results:

[1]
[2]
[1, 0]
[4, 0, 0]
[4, 0, 0, 0]
[1, 0, 0, 0, 0]
[9, 9, 9, 9]


Compared to a solution using the upper/lowerCased() string methods,
your approach has some disadvantages:

It does not work for many letters in non-english alphabets:

print(solve("ćœßπĆŒΠ"))  // çĳ¿ΠæĲ΀

It transforms non-letters as well, to some unexpected output:

print(solve("a b,c")) // A@BLC

Even if the code is only needed for ASCII letters ("A" ... "Z", "a" ... "z"),
it can still be improved.

Defining a global function instead of a closure variable increases the
legibility. You should also use a better function name, solve() is pretty
non-descriptive:

func toggleCase(_ str: String) -> String {
    // ...
}

An alternative would be an extension method:

extension String {
    func caseToggled() -> String {
        // ...
    }
}

which resembles the existing upper/lowerCased() methods.
A disadvantage is the possibility of name conflicts if some imported
framework happens to define the same extension method.

The use of "magic numbers" – like 32 and 96 in your code – should be
avoided. At least use a constant with an explaining comment:

let delta = 32 // Difference between upper case and lower case Unicode scalar values of ASCII letters.

Better, compute it from the actual values, which makes it self-explaining:

let delta = UnicodeScalar("a")!.value - UnicodeScalar("A")!.value

A switch-case statement allows to transform only the ASCII letters,
with a well-defined behavior for other characters.

Finally, instead of creating an intermediate [Character] array,
you can append to the unicodeScalar view of the result string
directly.

Putting it together, the function could look like this:

func toggleCase(_ str: String) -> String {
    let delta = UnicodeScalar("a")!.value - UnicodeScalar("A")!.value
    var result = ""
    for ucs in str.unicodeScalars {
        switch ucs {
        case "A"..."Z":
            result.unicodeScalars.append(UnicodeScalar(ucs.value + delta)!)
        case "a"..."z":
            result.unicodeScalars.append(UnicodeScalar(ucs.value - delta)!)
        default:
            result.unicodeScalars.append(ucs) // Leave unchanged
            // Alternatively:
            // break to ignore other characters
        }
    }
    return result
}

Example:

print(toggleCase("AB c De")) // ab C dE

If you have to toggle the case of arbitrary letters (from any language) then
the upper/lowerCased() string methods must be used, as there is no
simple "arithmetic operation" which does this transformation.

If performance is the first priority then you should work on the UTF-16 view
of the string, because that is what String stores internally. (However, that
is an implementation detail and might change in the future.)

func toggleCase1(_ str: String) -> String {
    var utf16Result: [UInt16] = []
    utf16Result.reserveCapacity(str.utf16.count)
    let upperCaseA = UInt16(65)
    let upperCaseZ = UInt16(90)
    let lowerCaseA = UInt16(97)
    let lowerCaseZ = UInt16(122)
    let delta = lowerCaseA - upperCaseA

    for u in str.utf16 {
        switch u {
        case upperCaseA...upperCaseZ:
            utf16Result.append(u + delta)
        case lowerCaseA...lowerCaseZ:
            utf16Result.append(u - delta)
        default:
            utf16Result.append(u)
        }
    }
    return String(utf16CodeUnits: utf16Result, count: utf16Result.count)
}

Note how reserveCapacity() is used to avoid array reallocations.

Performance comparison: The test was done on a MacBook (Retina, 12-inch, Early 2016, 1.2 GHz Intel Core m5 processor),
with the program compiled in Release configuration:

let str = String(repeating: "abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWXYZ", count: 100_000)

do {
    let start = Date()
    let _ = solve(str)
    let end = Date()
    print("solve:      ", end.timeIntervalSince(start) * 1000)
}

do {
    let start = Date()
    let _ = toggleCase(str)
    let end = Date()
    print("toggleCase: ", end.timeIntervalSince(start) * 1000)
}

do {
    let start = Date()
    let _ = toggleCase1(str)
    let end = Date()
    print("toggleCase1:", end.timeIntervalSince(start) * 1000)
}

Result:

solve:       496.731996536255
toggleCase:  319.347023963928
toggleCase1: 189.152002334595


First of all a bug, Repository property has to be an instance property, not static. Not that big issue because you're working with a singleton but it defeats the purpose of its surrounding code. Don't go to fix this, wait for our refactoring...

Class itself should be sealed, I don't see any chance to extend it (and you probably want to avoid it). Again, wait little bit more...

Note that, according to C# version you're using, you may write read-only properties as:

public FileRepository Repository { get; }
public static FileSingleton Instance => lazy.Value;

About Application_Start. I do not see surrounding code then I'm guessing but I have few perplexities. HttpContext.Items is usually handy to share data between HTTP modules and/or HTTP handlers. In this case you're storing an instance of FileSingleton, it means that each user has to know that type. In this case they can directly access FileSingleton.Instance.

As last note I'd consider to merge FileSingleton and FileRepository (if you own that code and it can be changed). Consider that to access FileRepository methods you need to write something like this:

FileSingleton.Instance.Repository.DoSomething();

Isn't it too verbose? It should be:

FileSingleton.Repository.DoSomething();

Or:

FileRepository.Instance.DoSomething();

If possible I'd go with the last one to do not introduce another type with the only responsibility to keep an instance of something else. If not then I'd refactor your code to:

public static class FileSingleton
{
     private static readonly Lazy<FileRepository> _repository =
        new Lazy<FileRepository>(() => new FileRepository());

     public static FileRepository Instance => _repository.Value;
}


Determining position of point W.R.T to given line equation

Note to potential future reviewers: This code appears to be suitable for Python 3 only.

Let's structure your code a little and see if we can fix the timing problem.

I propose the following order:

Global variables
Helper functions
Main function

Input
Actual calculations

if __name__ == '__main__':

The latter may not look familiar to you, but it's an include guard. It's a good practice to start using those, especially if you ever want to re-use parts of your code. Now your main only gets executed if the script is called directly, not when it's called by import.

Which leaves us after the first couple of edits with the following:

x = []
y = []

def ask_amount():
    return int(input())

def ask_lines(amount):
    for i in range(amount):
        l = list(map(int, input().split()))
        x.append(l[0])
        y.append(l[1])

def ask_queries(amount):
    return list(map(int, input().split()))

def main():
    ask_lines(ask_amount())
    q = ask_amount()
    for i in range(q):
        p = ask_queries(q)
        L = p[0]-1
        R = p[1]-1
        X = p[2]
        Y = p[3]
        flag = 0
        for i in range(L, R+1, 1):
            if(Y - x[i]*X - y[i] < 0):
                print("YES")
                flag = 1
                break
        if(flag == 0):
            print("NO")

if __name__ == '__main__':
    main()

Which still isn't much, but the structure is getting better. Note that I made your comma's breath ((L,R+1,1) is more readable when written as (L, R+1, 1) and there's no longer a ; behind your break. It's Python, we don't need semi-colons after break/continue etc.

One of the major things fixed now is your code was executing before you finished reading your input. That's usually a bad idea unless you're in some kind of do until told otherwise loop, which this wasn't. Now it waits for all input before it executes the rest.

I/O used to be:

2
-1 3
-2 -4
3
1 2 0 0
YES
1 1 0 0
YES
2 2 0 0
NO

Now it is:

2
-1 3
-2 -4
3
1 2 0 0
1 1 0 0
2 2 0 0
YES
YES
NO

There's still a couple of problems with it. We're now iterating an extra time, which can't be helpful for the time it takes to execute. But at least it looks better now, so we can see what we're doing. It still fails just as many test cases as your original code did, so at least we didn't do noticeably worse.

What else can we do better?

    L = query[0]-1
    R = query[1]-1
    X = query[2]
    Y = query[3]
    flag = 0
    for i in range(L, R+1, 1):

R = some value minus one. The actual value we need is R plus one. Since the description of the challenge says L and R are given (not L+1 and R+1), it doesn't make sense to modify them.

Let's go from L-1 to R instead.

    L = query[0]
    R = query[1]
    X = query[2]
    Y = query[3]
    flag = 0
    for i in range(L-1, R, 1):

Another thing we don't need is this entire flag business. Let's use return values instead:

x = []
y = []

def ask_amount():
    return int(input())

def ask_lines(amount):
    for i in range(amount):
        l = list(map(int, input().split()))
        x.append(l[0])
        y.append(l[1])

def ask_queries(amount):
    return list(map(int, input().split()))

def does_line_exist(query):
    L = query[0]
    R = query[1]
    X = query[2]
    Y = query[3]
    for i in range(L-1, R, 1):
        if(Y - x[i]*X - y[i] < 0):
            return True
    return False

def main():
    ask_lines(ask_amount())
    q = ask_amount()
    queries = []
    for i in range(q):
        queries.append(ask_queries(q))
    for query in queries:
        if does_line_exist(query):
            print("YES")
        else:
            print("NO")

if __name__ == '__main__':
    main()

Poof! No more flag.

But wait, this still doesn't solve your TLE problem! No, I'm afraid not and I'm going to tell you why. The author of the problem has made the constraints so narrow that the only acceptable solutions are those which use the Convex hull trick. It basically boils down to checking whether a value is < -y instead of < 0.

I'll leave the actual implementation of said trick to you. Feel free to post a follow-up question once you've implemented it.


Python functions to fetch spreadsheets through SFTP and from Dropbox

From looking at the code, some things seem off:

valid_extensions is defined, but not used
connect_to_sftp(), self.remote_dir, io.BytesIO(), sftp.getfo(), pd, self.close_sftp_connection() and a bunch of other functions/fields are not defined

That being said, the core problem is addressed by creating a parent class which both your classes can inherit from. It'd look something like this:

class FileHelper:
    def parse_fetched_file(self, file_name, data, sheet_name):
        valid_extensions = ['csv', 'xls', 'xlsx']
        extension = file_name.split('.')[-1]
        if extension == 'csv':
            return pd.read_csv(io.BytesIO(data.content))
        return pd.read_excel((io.BytesIO(data.content)), sheet_name=sheet_name)

class SftpHelper(FileHelper):
    def fetch_file_from_sftp(self, file_name, sheet_name = 0):
        sftp, transport = self.connect_to_sftp()
        remote_path = self.remote_dir + file_name
        data = io.BytesIO()
        sftp.getfo(remote_path, data, callback=None)
        file_df super(SftpHelper, self).parse_fetched_file(file_name, data, sheet_name)
        self.close_sftp_connection(sftp, transport)
        return file_df

class DropBoxHelper(FileHelper):
    def read_file_from_dropbox(self, file_name, sheet_name = 0):
        dbx = self.connect_to_dropbox()
        metadata, data = dbx.files_download(file_name)
        return super(DropBoxHelper, self).parse_fetched_file(file_name, data, sheet_name)

I'm not 100% sure that it's the most efficient syntax, but it gets the job done.


Idea of 'parser' to make the writing of asynchronous functions chains easier

Interesting question,

I find this code hard to read, I wonder what you consider unreadable code.

Some remarks on

pp_chain_function = function (fname,condition_string) {
var queue=this;
var prec_result = 'result_'+queue.queue_length;
queue.queue_string += !condition_string ? '.then(function(){return '+fname+'();})'
        :'.then(function('+prec_result+'){if('+prec_result+condition_string+'){return '+fname+'();}return $.when();})';
queue.length++;

return queue;
};

Use jsbeautifier.org, always
Prefixing with pp makes no good sense
Postfixing with _string makes little sense
prec_result <- What does prec stand for
var queue=this;, you only need to re-assign this if you work with closures
Consider a templating function for your string building
That long ternary statements looks horrendous, consider splitting it over multiple lines

Some remarks on

queue_object = {
    pp_chain : pp_chain_function,
    pp_fail : pp_fail_function
};

You use queue_object as a prototype, consider changing the name to reflect, also, JavaScript ought to be written in lowerCamelCase: queue_object -> queueObject -> queuePrototype

Some remarks on

var chain = pp_begin(); //init the chain
    chain.pp_chain('async_0').pp_chain('async_1');  //add two standard async functions
    if(condition two){chain.pp_chain('async_2','.length>0');} //if external conditions and async_1 gave a result with length>0, execute async_2
    chain.pp_fail('fail_handler');  //add fail handler
    console.warn(chain);  //replace with eval if you want to actually run it

Indenting is messed up
You are putting conditions in strings..
I am fairly certain that either by making async_1 fail if length < 1 or putting your check inside async_2 you could replace this with

$.when( async_0, async_1 )
  .then( async_2, fail_handler );

The biggest elephant in the room is of course eval, you loose proper stack-traces, debugging, tooling ( jshint, jsbeautifier ), and open yourself up to all kinds of pain. I would suggest that you post one of your unreadable scripts, perhaps we can show you how to use Q so that they become readable without resorting to .. this.


Currently, you are overlooking one of the advantages in using lxml with its fully compilant W3C XPath 1.0 (even XSLT 1.0) language modules.

Right now, your code really follows the syntax of Python's built-in etree, without any xpath() calls that can run dynamic parsing off node names.

Below iterates through all <basic> and <expert> tags and retrieves their child <name> and <email> all in one loop or list comprehension. And to retrieve their position we count their preceding siblings with count(preceding-sibling::*).

from lxml import etree

myXML = "data.xml"
tree = etree.parse(myXML)

user = []

# FOR LOOP
for i in tree.xpath("//*[name()='basic' or name()='expert']"):
    user.append([i.xpath("count(name/preceding-sibling::*)"),
                 i.find("name").text,
                 i.xpath("count(email/preceding-sibling::*)"),
                 i.find("email").text])
print(user)
# [[0.0, 'f.bar', 1.0, 'foobar@me.com'],
#  [0.0, 'm.bob', 3.0, 'm.bob@email.com'],
#  [0.0, 'm.bab', 3.0, 'm.bab@email.com']]

# LIST COMPREHENSION
user = [[i.xpath("count(name/preceding-sibling::*)"),
         i.find("name").text,
         i.xpath("count(email/preceding-sibling::*)"),
         i.find("email").text]
        for i in tree.xpath("//*[name()='basic' or name()='expert']")]

print(user)
# [[0.0, 'f.bar', 1.0, 'foobar@me.com'],
#  [0.0, 'm.bob', 3.0, 'm.bob@email.com'],
#  [0.0, 'm.bab', 3.0, 'm.bab@email.com']]


Simple JS OOP - Clicking the box to fetch and display object content

OO-Design

  key question Identify how and where I can typically use OOP more in my job (as I can usually just use arrays and don't need objects

In your transformation towards OOP, you're still in the habit of resorting to arrays.
You let each new instance of this class be registered in some global array.

class Animal {
  constructor (name, description) {
    this.name = name;
    this.description = description;
    animalsObj.push(this);
  }
}

Don't do this as it pollutes your object-oriented design.

class Animal {
  constructor (name, description) {
    this.name = name;
    this.description = description;
  }
}

If you wish to store these instances in the array, let the consumer code handle it. This way, you can decide by use case how instances of objects should be handled.

const animals = [];
const animal = new Animal("Roger", "my pet");
animals.push(animal);

This would also keep you from instantiating an object without storing the instance in a variable, because the magic no longer happens behind the screens.

new Animal(name, description);  // no longer registers to a global array