Creating a bijection between integers and a set of strings

Since what you want is something a little more complicated than what a normal dictionary can do, I think you want to encapsulate all of this in a class that behaves the way you want the dict to behave.  You can make it "look like" a dict by implementing __getitem__, something like:

from typing import Dict, List, Set, Union, overload

class StringTable:
    """Associate strings with unique integer IDs."""

    def __init__(self, strings: Set[str]):
        """Initialize the string table with the given set of strings."""
        self._keys: List[str] = []
        self._ids: Dict[str, int] = {}
        for key in strings:
            self._ids[key] = len(self._keys)
            self._keys.append(key)

    @overload
    def __getitem__(self, o: int) -> str: ...

    @overload
    def __getitem__(self, o: str) -> int: ...

    def __getitem__(self, o: Union[int, str]) -> Union[str, int]:
        """Accepts either a string or int and returns its counterpart."""
        if isinstance(o, int):
            return self._keys[o]
        elif isinstance(o, str):
            return self._ids[o]
        else:
            raise TypeError("Bad argument!")

    def __len__(self) -> int:
        return len(self._keys)

Now you can use it like:

strings = {"foo", "bar", "baz"}
bijection = StringTable(strings)
for s in strings:
    print(s, bijection[s])
    assert bijection[bijection[s]] == s

etc.


meta-charset should come before title

The meta-charset element would ideally be the first element in head (details about the order in head).

So it could be:

  <meta charset="utf-8">
  <title>Salon Sociel | Hair-Nails-Unisex</title>
  <link rel="stylesheet" href="style/main.css">

Wrong use of section and h3

You have:

Salon Sociel

Hair-Nails-Unisex

Neither is the section correct here (it only contains headings, and by using it the h1 is no longer the heading of the body), nor is it correct to use a heading element for a subheading (details).

So it should simply be:

Salon Sociel

Hair-Nails-Unisex

(Your structure would have been correct if using hgroup instead of section, but this element was removed from W3C’s HTML.)


Rails: Setting a transient attribute on a set of objects from one model based on information from a junction model

The problem is that the data to render does not match the modelling. You call it "task", but if it includes a completed_on it's not a task, it's something more of a user_task. I definitely wouldn't use an accessor to accomplish this, that's messing with Task, this model should know nothing about completion dates of a particular user.

Even if you call it "tasks" in the frontend, conceptually in your app you should be rendering a collection of user_tasks. Something to start with (make sure, using includes or whatever, that user_task_by doesn't hit the DB repeatedly):

user_tasks = Task.where(...).includes(:users_tasks).map do |task|
  task.user_task_by(user) || task.user_tasks.new
end

Now you'd override UserTask#as_json to build a hash with the mixed structure (getting some attributes from task and completed_on from user_task).

Was this any help?


Such while-loops that don't offer an advantage are unpythonic. And harder to understand. In your solution, the information about what the loop goes through is spread over six (!) lines. And I actually I need to read all 8 (!) lines, since I need to read the if/print as well in order to see that they don't affect the loop. Better use a for-loop, where it's all cleanly in one line.

If you do use such a while-loop, then there should be an empty line above your num_1 = 1, not under it. Because it belongs to the solution, not to the input.

Floating-point in general has precision issues, better avoid it if you can. Here it's simple to use just integers.

For num = 1, you don't print anything. You should print 1, 1.

Unless you have an actual reason for that formatting, keep it simple and don't format. If you use the output of your program as input for something else, it might also very well be easier to parse without that extra comma.

Resulting code:
from math import isqrt

num = 498

for i in range(1, isqrt(num) + 1):
    if num % i == 0:
        print(i, num // i)


We should definitely go ahead and use @objc and make the methods optional that make sense to be optional.

In Swift, it's actually not nearly as bad to check whether or not a delegate is set up or responds to a selector.  In Objective-C, it was a big if statement.  In Swift, we can use optional chaining.

Suppose that didUpdate is an optional method.  Calling it on our delegate then looks like this:

self.delegate?.didUpdate?()

The only difference here is the ? before the parenthesis.

What this line of code says is basically:

if delegate is not nil and if delegate responds to selector "didUpdate"
    call "didUpdate" on delegate
else
    do nothing

The other important thing here is that we need to be sure that we're making our reference to the delegate a weak reference, which can only be done if our protocol is specified as @objc.  In almost every case, the object acting as our delegate is already holding a strong reference to the class that needs the delegate.  If this class also holds a strong reference back to the delegate (which you're currently doing), we've creating a retain cycle.  The memory can never be released without annoying setting each other's reference to the other to be nil... and the hard part is often times figuring out when to do that.

So, let's make our protocol be an @objc protocol and use a weak reference to our delegate, and then use optional chaining to take care of the optional methods.


You simply need to understand what's going on when you write:

    logging.basicConfig(format=LOG_FORMAT,
                        level="NOTSET",
                        stream=Devnull(),
                        )

This creates a root logger with level NOTSET and a default handler which won't log anything thanks to Devnull. I think this also has the added benefit of settings the level of all future loggers to NOTSET.

But you don't want a root logger! You're defining your own logger with your own handlers and so on. So basicConfig() is doing more harm than good here. Remove it!

Now there's one remaining issue: if you do this, you won't see debug logs, because the default log level is WARNING. So you need to add self.main_logger.setLevel(logging.DEBUG): the logger will accept all log levels, and each handler will decide whether or not to process the log record depending on the log level of the record and its own log level. (In other words, you're back to the original code you used which worked very well.)


Bug

SinglyLinkedList.delete called on the tail node doesn't really delete it: the previous node still holds the reference.
Interface

SinglyLinkedList.insert and SinglyLinkedList.delete require a handle to a Node object, which is quite hard to obtain. It seems that the only way is to manually iterate the list breaking on a condition. I recommend prepend, append, insert to return a newly created instance. A find method would also be useful.


Is there a better or more elegant way to code this CSV cell-parser (using CSVReader)?

Declare your BUSINESS constant as final
readFile will currently always return 'true', barring some unforeseen exception. Seems like you could make it a void method as well.
validateFile is a bit bad method name. Imagine it being used elsewhere: if( x.validateFile() ) { /* do something */ }. That looks like you're asking whether to validate a file or not. If you want to call the method that, make it return void and make it throw an exception if the validation fails. Otherwise call it something like isFileValid().
All the methods in your class are defined as public, which makes little sense. You could make them all but one private and enter the File and date in a constructor. Or you could just make one static method there which would call the other methods. As far as I can see there's no need for a FileValidator object to actually have a state.
validateFile() makes a fancy but redundant boolean array of all the validation results. In reality you do not need to call all the validators if the first one of them fails. Try this instead:

private boolean validateFile() {
    return checkNumColumns() && checkIfEmpty() && checkDate() && checkFileName() && checkBusiness();
}

Your checkIfEmpty() method has a possible NullPointerException: it first trims header[i], and only afterwards checks for null, at which point it's too late. Also, String comparisons with "=="s is just wrong, as that checks that the memory locations of the two strings are the same, saying nothing about their contents. string == "" would anyway be the same as string.length() == 0 if it worked. Besides, nowadays the correct way to check for an empty string is `string.isEmpty()".
checkDate() does not need an if-else block: just do return header[0].equals(date);. (A completely other thing is that representing dates with Strings isn't necessarily the best idea ever when java.util.Date exists as well.)
The previous point also applies for checkFileName(). Those header[1] names are not readable anyway, you will want to pass the "header[1]" as an argument to the method (which should be static and private) and then call the argument "filename".
checkBusiness() is pretty good as it stands, just have it take the business as an argument instead of using "header[3]", just like I noted about the previous method.
Don't forget to write unit tests for your class.


Having a single main function that reads from os.stdin and writes the unrelated prompt to os.stdout is a bad architecture. In Python it is easy to create reusable modules, by using the following structure:

def censor(text, banned_words):
    """
    Returns a copy of the given text in which all words from
    banned_words are replaced with asterisks of the same length.
    """

    # TODO: insert some code here.

def main():
    # contains all the input/output stuff
    # TODO: insert some code here.

if __name__ == "__main__":
    main()

Programmed this way, other Python code can just import censor and then use the censoring code, no matter where the set of banned words comes from.

Having the code split into two separate functions also makes sense for understanding what the code does. If you're interested in how censoring works, look at the censor function. If you are interested in reading and writing to files, look in main.

Some other random remarks:

text = open(name, "r", encoding="latin_1")

Please don't use the latin_1 encoding if possible. It's been en vogue in the 1990, nowadays we prefer to use the full Unicode character set (including Arabic, Bengali, Chinese, Devanagari, Emoji, and many more) and UTF-8 to save Unicode text into byte-oriented files.

Most probably that file contains only ASCII characters anyway since CS50 takes place in the USA, where foreign languages and writing systems are often ignored.

text = open(name, "r", encoding="latin_1")
if not text:
    ...

This will not work since the open function either succeeds by returning a file object, or it fails and throws an exception. It never returns None. That's probably a leftover from your last exercise in the C programming language. But Python is very different from C.

Whenever you open a file, you must also close it when you're done with it. The simplest way is:

with open(name, 'r', encoding='UTF-8') as f:
    lines = f.readlines()

The with statement will automatically close the file at the end. It's not visible in the source code, you have to just know this.

toCensor = input("What message would you like to censor? ")

Be sure to only ever run this program in Python 3, since in Python 2 the input function behaves differently.

The name toCensor should rather be to_censor since in Python variable names and function names are written in snake_case instead of camelCase.

In the sentence This is BAD, BAD, BAD., assuming that BAD is a bad word, what would the expected output be? How can you change your program to do the expected thing? What should it do about BADABOOM?


Retry loop for asynchronous HTTP requests

I would rewrite your code into a while (true) loop, that can only be exited using the return in your try or using a throw; inside a condition in your catch:

while (true)
{
    try
    {
        return await PutAsync(url, content, authenticationHeaderValue, mediaTypeWithQualityHeaderValue);
    }
    catch
    {
        numberOfAttempts++;
        if (numberOfAttempts >= TotalNumberOfAttempts)
            throw;
    }
}

This way, you don't need ExceptionDispatchInfo or the useless  (but required by the compiler) throw at the end.

I also changed catch (AggregateException ex) to catch all exceptions, because await usually doesn't throw AggregateException (unlike task.Wait() or task.Result).


Function that returns value based on specific category

After that I realized defining menu variable will run every function in the object to store the value in the properties which is not what I'm trying to do.

What you have looks like it would work just fine.  Declaring the menu structure does not execute the functions you've assigned as properties.  It just defines the functions and assigns them as properties (waiting to be called later).

You could save a little execution overhead by moving the static menu definition outside the function so it just gets defined once (I'm assuming this is private module scope so moving the symbol outside the function is fine) and change it to const.

You can also remove the async and await since neither add anything here.  You're just returning a promise anyway so you can just return the promise directly without async and await.  I also added more explicit error checking for the category name.

const methodMap = {
    'feed': () => steem.api.getDiscussionsByFeed(query),
    'blog': () => steem.api.getDiscussionsByBlog(query),
    'new': () => steem.api.getDiscussionsByCreated(query),
    'hot': () => steem.api.getDiscussionsByHot(query),
    'trend': () => steem.api.getDiscussionsByTrending(query)
};

const getContent = (category, tag) => {
    const query = { 'tag':tag, 'limit':10 };
    if (methodMap.hasOwnProperty(category)) {
        return methodMap[category]();
    } else {
        return Promise.reject(new Error(`Unknown Category: ${category}`));
    }
}

You could also remove some redundancy from the table by making the table only be the steem method name you want to call.

const methodMap = {
    'feed': 'getDiscussionsByFeed',
    'blog': 'getDiscussionsByBlog',
    'new': 'getDiscussionsByCreated',
    'hot': 'getDiscussionsByHot',
    'trend': 'getDiscussionsByTrending'
};

const getContent = (category, tag) => {
    const query = { 'tag':tag, 'limit':10 };
    if (methodMap.hasOwnProperty(category)) {
       return steem.api[methodMap[category]](query);
    } else {
        return Promise.reject(new Error(`Unknown Category: ${category}`));
    }
}

This layout also does more explicit error checking on a "supported" category being passed in.


This is Python and you do not need the Semi-Colons (;)

Your code looks absolutely non-pythonic like that, it looks like it is trying to morph into Java or something.

You should also separate some more code into methods/functions like this one here

print "=" * 78;

I believe that this is to separate the game from the ending notifications.

What gave this away was 78 I have no clue what that is, and if I have different settings on my console/IDE then this won't look right anyway.  78 is a magic number and should be dealt with so that I know what it means


Test if Excel is open without relying on catching an error

As was pointed out in chat earlier, a module called Utils might as well be called Helpers or DumpAnythingYouWantHere.

You should prefer using vbNewLine over vbCrLf: vbNewLine will produce a platform-specific new line, while code that uses vbCrLf might only produce correct results under Windows, which means your comment about it being platform-independent is a false assumption.

I get the GetObject(, "Excel.Application") call to tap into the current instance (what happens when there are 2 or more instances already opened?), but the CreateExcelApp function could be much, much more straightforward than this:

Private Function CreateExcelApp() As Excel.Application
' Returns New instance of Excel
On Error GoTo ErrHandler

    Set CreateExcelApp = CreateObject("Excel.Application")

CleanExit:
    Exit Function
ErrHandler:
    ShowErrorMessageBox
End Function

Consider:

Private Function CreateExcelApp() As Excel.Application
    Set CreateExcelApp = New Excel.Application
End Function

At which point I'd question the need for this CreateExcelApp function! Why not simply handle that in GetExcelApp? Like the comments say, if it doesn't exist, creates one to return:

Public Function GetExcelApp() As Excel.Application
' Returns open excel instance.
'   If it doesn't exist, creates one to return
On Error GoTo ErrHandler
Const ERR_APP_NOTRUNNING As Long = 429

    Set GetExcelApp = GetObject(, "Excel.Application")

CleanExit:
    Exit Function
ErrHandler:
    If Err.number = ERR_APP_NOTRUNNING Then
        Set GetExcelApp = New Excel.Application
        Resume CleanExit
    Else
        ShowErrorMessageBox
    End If
End Function

I don't like ShowErrorMessageBox. It's Private and single-use, with a hard-coded message that's only relevant for an error occurring in GetExcelApp. I'd get rid of that method.


Python Minimization Functions: Is the code optimal?

PEP-8 Violations

The Style Guide for Python Code enumerates many conventions that all Python code should follow.  You have deviated from these conventions in several areas:

mixedCase is discouraged.  Function names, methods and variable should all be snake_case.  This means thetaMax should be called theta_max.  (Exceptions are allowed for things like Da, where consistency with mathematical notation is more important than consistency with Python style.)
return is not a function call; it should not have parenthesis.  Ie) return(result) should be written as return result.
if is also not a function call, nor is Python a C-like language; it should not have parenthesis.  if(method == 'mle'): should be written as if method == 'mle':
Binary operators should have one space before and after it.  This is only violated by the division operation in gpcm from my quick perusal of the code.
Commas should be followed by one space.
The equal sign used in keyword=parameter should not have a space before or after it.  This applies both to the function definitions def gpcm(theta, d, score, a, D=1.7): and function calls p = prob3pl(theta, a, b, c, D=D)
Builtin Python identifiers should not be redefined without reason.  object is such an identifier.  A better name should be used.

Truthiness of lists.

A container used in a boolean context is True if the container is not empty, and False if the container is empty.  There is no need to fetch the length of the container, test that value is greater than zero:

if x1:

is more "Pythonic" than:

if(len(x1) > 0):

Ranges Start at Zero by Default

By default, all ranges start at 0.  This means range(0, len(x2)) is much more commonly written as range(len(x2)).

Iteration over a container

Python is a scripting language, where the script can assign its own implementation for many operations including subscripting, and iteration.  This makes it impossible for Python to optimize code like:

for i in range(0, len(x2)):
    ... use the value x2[i] ...

It will usually be more efficiently written as:

for x2_i in x2:
    ... use the value x2_i ...

If the index is needed along with the values, then enumerate() is used for the most efficient result:

for i, x2_i in enumerate(x2):
    result[i] = gpcm(theta, d=d[i], score=x2_i, a=1, D=D)

Iterating over two (or more) parallel list (d and x2) would be done using zip:

for d_i, x2_i in zip(d, x2):
    ... = gpcm(theta, d=d_i, score=x2_i, a=1, D=D)

And if the indices are also needed, enumerate(zip(...)):

for i, (d_i, x2_i) in enumerate(zip(d, x2)):
    result[i] = gpcm(theta, d=d_i, score=x2_i, a=1, D=D)

But building up a complete array is more commonly done with list comprehension:

result = [ gpcm(theta, d=d_i, score=x2_i, a=1, D=D) for d_i, x2_i in zip(d, x2) ]

which eliminates the need for the result = [0] * len(x2) pre-allocation.

Keyword Arguments

What arguments can be passed to thetaMax()?

The answer is "any".  The user has no way of knowing what is possible, or allowed.  You can pass optimization_level=18 without error ... and without effect.

It would be safer to define the function with the allowed keyword arguments explicitly:

def thetaMax(x, indDichot, a, b, c, D, d, method='mle', *, mu=None, sigma=None):

    if method not in {'mle', 'map'}:
        raise ValueError("Invalid method")
    if method == 'map':
        if mu is None or sigma is None:
            raise ValueError("Both mu= and sigma= keyword arguments must be given")
    elif method == 'mle':
        if mu is not None or sigma is not None:
            raise ValueErorr("Neither mu= or sigma= is appropriate for 'mle'")

As a bonus, having the values already extracted into their own variables is faster than repeatedly looking up optional_args['mu'] and optional_args['sigma'] during each and every call of fn() during the minimize function.

Additional speed may come from defining different fn() functions for the 6 different combinations of len(x1) > 0, len(x2) > 0, and method, thus removing the conditionals from inside the nested calls.


Making the font as big as possible without overflowing each div

No particular comment on the style, but FWIW, I had to implement the same thing recently — also in jQuery — and this is how I did it. Assume we have an outer <div> named time_display_div that we don't want to overflow, and nested immediately inside that we have a <span> named time_display_span that we're trying to make as big as possible.

function effective_fraction(span, div) {
    var x = span.width() / div.width();
    var y = span.height() / div.height();
    return Math.max(x, y);
}

function update_display(msg) {
    // Change the text of the time display,
    // and massage the font size until it fills the screen.
    var div = $('#time_display_div');
    var span = $('#time_display_span');
    var font_size = parseInt(span.css('font-size'));
    span.text(msg);
    while (effective_fraction(span, div) < 0.90) {
        font_size += 10;
        span.css('font-size', font_size + 'px');
    }
    while (effective_fraction(span, div) > 0.90) {
        font_size -= 2;
        span.css('font-size', font_size + 'px');
    }
}

Basically the only difference is that I'm skipping through the sizes at ten times the speed you are; and I'm using .height() instead of .innerHeight(), but I can confirm that at least in Safari it makes no difference which one I use.

So at least if anyone comes up with a better solution here, it'll be useful to more people than just yourself. :)


Memory leak
Consider this (I removed the pointless cast and identity multiplication):

    master[i] = malloc(sizeof ele);
    master[i] = ele;

Here, we allocate memory (if malloc() succeeds), but then immediately overwrite our one and only pointer to it, so we're unable to ever free it.  The first assignment should just be removed, leaving only master[i] = ele.
Another memory leak:

printf("%s\n", smorse("sos"));

The smorse() function returns a pointer to allocated memory, which we need to release when we've finished using it:
const char *m = smorse("sos");
puts(m);
free(m);

(The puts() call is exactly equivalent to using printf("%s\n", m), but more readable and possible more efficient.)
Character coding assumptions
The magic value 97 in a couple of places suggests that we're assuming that characters are encoded as ASCII values.  That's not a portable assumption: C permits a wide range of encodings.  Notably, EBCDIC systems do not have letters in the same positions as ASCII (or even as a contiguous block, so replacing with 'a' doesn't solve the problem).
Also, there's no checking that the input to the function contains only characters that we can handle.  If we pass anything outside of the expected range, then we index master outside its bounds, which is Undefined Behaviour in C.  That means that the program may do anything - if we're lucky, it will simply crash, helping us to identify the problem, but there's no guarantee of that.
We ought to be converting more than just letters - digits have a standard Morse representation, as do certain other useful symbols.
Value conversions
It seems that this has been compiled with a very low level of warnings enabled.  Building with my usual compiler flags results in over a dozen warnings, most about suspect conversions.
To pick a couple of examples:

int end = strlen(str);

strlen() returns a size_t, which is of different signedness to int, and very likely to be bigger, so there's a risk of undefined behaviour here.

char *output = "";

It's dangerous to point a modifiable pointer at constant data (a string literal is of type char const*).

printf("%s\n", smorse("sos"));

Passing a string literal loses constness here - smorse() ought to accept pointer to const instead.


We're missing some pieces, such as the memory_descriptor and far_ptr32 classes and get_cs function and I guessed at the definitions of selector and byte, but with that said, here's what I found that may help you improve your code.

Make the constructor noexcept

It's unlikely that an exception within the constructor would be a welcome event.  For that reason, your constructor should be declared noexcept.

Make function_ptr noexcept

For similar reasons, I'd suggest making function_ptr also noexcept:

using function_ptr = void(*)(unsigned) noexcept;

Be careful with interrupt flags

Instead of disabling all interrupts using sti, it might be better to restore the interrupt flag to whatever it had been.  Although the interrupt could not have been called by hardware if the interrupt flag had been reset (that is, interrupts disabled) but it's not uncommon to chain interrupts by having one hardware interrupt chain to another via explicit call.  In that circumstance, the hardware flag should not be re-enabled lest the interrupt chain be incorrectly interrupted.


For some reason there's a trend among scientific Python users to import things with really short names, like

import numpy as np

This is somewhat bearable when it's np and you use it many times, but you use np once. Further, you

import matplotlib.pyplot as p

and only use this three times. It's not worth it; typing pyplot three times isn't going to make your code unduly long.

You should add more spacing in accordance to PEP 8, and cap line lengths to something less than what you currently have (100 characters should be enough).

random_point can just be

def random_point():
    return random.random(), random.random()

Namely, no brackets needed. You only use it once in

def list_of_random_points(n):
    return [random_point() for _ in range(n)]

so just write

def list_of_random_points(n):
    return [(random.random(), random.random()) for _ in range(n)]

instead. I'd also rename this to random_points. In fact, you only use this once, so I'd remove the function here too.

You only use error_of_point in error_of_list_of_points, so inline it, giving:

def error_of_list_of_points(points, func):
    return sum(abs(y - func(x)) for x, y in points)

You don't actually need a list, so call this error_in_points or similar.

In get_starting_rect, change

function = lambda x: m*x + q

to

def line(x): return m*x + q

I would also put it on two lines for readability. Since you use this so much, it makes sense to do

def line(m, q):
    def y(x):
        return m*x + q
    return y

So you can just do

error_in_points(points, line(m, q))

This also simplified the loop:

for m in range(-10, 10):
    for q in range(-10, 10):
        if error_in_points(points, line(m / 10, q / 10)) < min_error:
            ...

You can then move to using min:

mqs = product(range(-10, 10), range(-10, 10))
mqs = ((m/10, q/10) for m, q in mqs)

return min(mqs, key=lambda mq: error_in_points(points, line(*mq)))

or even

mqs = numpy.mgrid[-1:+1:0.1, -1:+1:0.1].reshape(2, -1).T
return min(mqs, key=lambda mq: error_in_points(points, line(*mq)))

get_approximate_m now looks like

def get_approximate_m(m, q, points, sensibility):
    if error_in_points(points, line(m+sensibility, q)) < error_in_points(points, line(m, q)):
        m += sensibility
    elif error_in_points(points, line(m-sensibility, q)) < error_in_points(points, line(m, q)):
        m -= sensibility
    return m

You should cache error_in_points(points, line(m, q)):

def get_approximate_m(m, q, points, sensibility):
    current_err = error_in_points(points, line(m, q))

    if error_in_points(points, line(m+sensibility, q)) < current_err:
        m += sensibility
    elif error_in_points(points, line(m-sensibility, q)) < current_err:
        m -= sensibility
    return m

This would also be better named adjust_m or similar.

Your approximate_better_m_and_q does:

for _ in range(100):
    m = adjust_m(m, q, points,sensibility)
    q = get_approximate_q(m, q, points, sensibility)

Since this does not change sensibility as it progresses it's likely that this quickly stops doing anything productive, spending most of its time bouncing around a few points. It'll probably work better with a gradual slowing:

def approximate_better_m_and_q(m, q, points, sensibility):
    for _ in range(50):
        m = get_approximate_m(m, q, points, sensibility)
        q = get_approximate_q(m, q, points, sensibility)
        sensibility *= 0.95
    return m, q

Which does tend to improve the results for me even though it has a quater the number of iterations.

plot_rect can trivially use Numpy's broadcasting:

def plot_rect(m,q):
    x = numpy.arange(0, 1, 0.1)
    y = x * m + q
    pyplot.plot(x,y)

plot_rect_and_points can use unpacking (as can main):

plot_rect(*rect)

I hadn't realized that error_in_points is only used with line as the funciton; maybe you should move it into error_in_points to make calling more convenient.

You should split your prints up:

print("The rect generated with brute force of equation y = {}x + {}".format(m, q))
print("has an error of {}".format(error_in_points(points, m, q)))

although the trailing space suggests maybe you didn't realize they were printing on separate lines.

All in all this gives

from __future__ import division

import numpy
import random

from matplotlib import pyplot

def error_in_points(points, m, q):
    return sum(abs(y - (m*x + q)) for x, y in points)

def get_starting_rect(points):
    mqs = numpy.mgrid[-1:+1:0.1, -1:+1:0.1].reshape(2, -1).T
    return min(mqs, key=lambda mq: error_in_points(points, *mq))

def adjust_m(m, q, points, sensibility):
    current_err = error_in_points(points, m, q)

    if error_in_points(points, m+sensibility, q) < current_err:
        m += sensibility
    elif error_in_points(points, m-sensibility, q) < current_err:
        m -= sensibility
    return m

def adjust_q(m, q, points, sensibility):
    current_err = error_in_points(points, m, q)

    if error_in_points(points, m, q+sensibility) < current_err:
        q += sensibility
    elif error_in_points(points, m, q-sensibility) < current_err:
        q -= sensibility
    return q

def approximate_better_m_and_q(m, q, points, sensibility):
    for _ in range(50):
        m = adjust_m(m, q, points, sensibility)
        q = adjust_q(m, q, points, sensibility)
        sensibility *= 0.95
    return m, q

def plot_rect(m,q):
    x = numpy.arange(0, 1, 0.1)
    y = x * m + q
    pyplot.plot(x,y)

def plot_rect_and_points(rect,points):
    pyplot.scatter(*zip(*points))
    plot_rect(*rect)

def main():
    NUMBER_OF_POINTS = 1000
    points = [(random.random(), random.random()) for _ in range(NUMBER_OF_POINTS)]

    m, q = get_starting_rect(points)
    plot_rect(m, q)

    print("The rect generated with brute force of equation y = {}x + {}".format(m, q))
    print("has an error of {}".format(error_in_points(points, m, q)))

    better_rect = approximate_better_m_and_q(m, q, points, 0.1)
    m, q = better_rect
    print("The rect generated with linear regression of equation y = {}x + {}".format(m, q))
    print("starting from the rect generated with brute force has an error of {}".format(
        error_in_points(points, m, q)
    ))

    plot_rect_and_points((m,q),points)
    pyplot.show()

if __name__ == "__main__":
    main()

There is a lot more you can do (particularly vectorization), but this is a good start.


Simple linked hash map in JS (Node/browser)

This is good code! I don't have many suggestions, and those that I do have are mostly minor.

First of all, just consider the general naming. I don't mind the names as they are, but you could consider other names as well. Here are two sets of alternate names for addHead and removeTail:

add / remove — The simple approach. I sort of prefer something a little more explicit.
push / pop — I like this more. It conveys the stack-like nature of the data structure but is more concise.

Now for some more substantive suggestions. None of these functions (except, of course, get) return anything! This is okay, but not ideal. JavaScript lends itself quite well to chaining, and it would be nice to be able to do something like this:

map.push('foo', 'bar')
   .push('baz', 'qux')
   .push('one', 'two')
   .push('red', 'blue');

Make addHead/push return the map!

Next, also add return values for remove and pop/removeTail. These should each return the value removed from the map. This also makes it easy to determine if a removal actually removed something or not.

Also, should maxLength really be required? What if I want an unbounded map? Under your current implementation, I could just pass in null or undefined or -1, but it might be nice to make this functionality more explicit.

Now for some suggestions for additions.

First of all, add some kind of length or size method. Using Object.defineProperty, you could even implement length as a "magic" property a-la array.length.

Second, having access to the actual underlying list seems a little important if you're using this to display anything. The obvious answer would be to add some sort of iterator support, but JavaScript doesn't really have native support for iterators (pre-ES6). For simplicity's sake, a simple keys function that returned the list of keys in list order would be convenient.

Also, you might want to add peekHead and peekTail to complement the existing set of functions, since even with keys, shorthand access is convenient.

Consider adding some error checking. While this is called LinkedHashMap, JavaScript objects only support string keys. This isn't really a problem, and building a more general solution in pure JS would be nontrivial (another thing coming in ES6!). Unfortunately, it wouldn't be unreasonable for someone to accidentally try to use an object as a key. I'd recommend throwing an exception on insertion for non-string keys. Force explicit calls to toString to avoid confusing errors down the line.

Other odds and ends:

Why is removeItem part of the public API? Make it internal. Don't expose it.
Add some inline comments! Most of this code is fairly self-explanatory, so you don't need to write any essays. Just adding something like // insert item at head of list would break up the code and make it easier to follow by dividing it into chunks.
Add tests! Something like this is a textbook candidate for extensive unit testing. Something like a data structure should not go untested.


Reversing k-sized sequences in a linked-list

Brutally honest?
If this is an interview, and you provide this line of code:

Queue linkQueue = new LinkedList();

Your resume gets put in the pile of 'ignore this person if they apply again'... ;-)
Genercis have been around for a decade now (introduced in 2004). You should know them, and use them.
Class Model
The ListNode should not be a public class. The information should be encapsulated within a single class, and not exposed. There should be no need for a user to have to supply a 'head' node to the public ListNode reverseKGroup(ListNode head, int k). This should be a class, say ReversingList which has a method reverseK(int k), and then provides a way to retrieve the re-ordered data (which may be in the format of a new ReversingList instance.
Algorithm
Your algorithm looks really complicated. There should be no need to scan the list before processing it. That indicates some serious inefficiencies.
Additionally, relying on the LinkedList class is a bit of a cheat... but, if you are going to use it, then you may as well go the whole hog, and use its reverse function... (descendingIterator())
How would I do it?
This was the original title of the question... well, how about:
public class SolutionList {

    private static final class ListNode {
        private final int val;
        private ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }

        @Override
        public String toString() {
            return "ListNode " + val;
        }
    }

    // use relatively common trick of having a dummy head node.
    private final ListNode head = new ListNode(0);

    public SolutionList() {
        // default constructor does nothing.
    }

    public void add(int v) {
        ListNode node = head;
        while (node.next != null) {
            node = node.next;
        }
        node.next = new ListNode(v);
    }

    public void addAll(SolutionList toadd) {
        ListNode tail = head;
        while (tail.next != null) {
            tail = tail.next;
        }
        ListNode their = toadd.head.next;
        while (their != null) {
            tail.next = new ListNode(their.val);
            tail = tail.next;
            their = their.next;
        }
    }

    public void reverseKInPlace(final int k) {
        if (k <= 1 || head.next == null) {
            return;
        }
        ListNode[] stack = new ListNode[k];
        int depth = 0;
        ListNode node = head.next;
        ListNode mark = head;
        while (node != null) {
            ListNode nxt = node.next;
            stack[depth++] = node;
            if (depth == k) {
                while (--depth >= 0) {
                    mark.next = stack[depth];
                    mark = mark.next;
                }
                depth = 0;
            }
            node = nxt;
        }
        if (depth > 0) {
            mark.next = stack[0];
        }

    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("SolutionList [");
        ListNode node = head.next;
        while (node != null) {
            sb.append(node.val).append(", ");
            node = node.next;
        }
        if (head.next != null) {
            sb.setLength(sb.length() - 2);
        }
        sb.append("]");
        return sb.toString();
    }

    public SolutionList reverseK(final int k) {
        SolutionList copy = new SolutionList();
        copy.addAll(this);
        copy.reverseKInPlace(k);
        return copy;
    }

    public static void main(String[] args) {
        int[] vals = { 1, 2, 3, 4, 5 };
        SolutionList soln = new SolutionList();
        for (int v : vals) {
            soln.add(v);
        }
        System.out.println(soln);
        System.out.println("Reverse 2 " + soln.reverseK(2));
        System.out.println("Reverse 3 " + soln.reverseK(3));
    }

}


"Compress" the entry set of Integers in a Map to values incrementing by 1

When you are collecting the unique integer values to a sorted list from the values of the original Map<String, Integer>, you are doing work that has already been done, namely the elimination of duplicates by calling distinct() on the stream. You have already filtered out the duplicates when you populated the Multimap<Integer, String>, so instead of collecting the values of the Map<String, Integer>, you could instead collect the keys of the Multimap<Integer, String>.

Also, you are creating a HashMultimap, which stores its values in HashSets (so it's like a HashMap<Integer, HashSet<String>>). This creates unneeded overhead, because the HashSet<String>s containing the values of the multimap eliminate duplicates. But in this case, the multimap can never contain duplicate values in the first place, since its values are obtained from the key set of the original Map<String, Integer>. It would therefore suffice to configure the multimap to store its values in ArrayLists instead of HashSets. By the way, the documentation says that the create methods of the individual Multimap implementations will be deprecated in the future, and that MultimapBuilder should be used instead.

Apart from that, you can omit the List<Integer> entirely by configuring the multimap to behave like a TreeMap instead of a HashMap. This might also save a bit of performance, because you have two functionalities implemented in one data structure, as opposed to using a Multimap for associating each integer with one or more Strings, and an additional List for sorting the integers. Of course, a TreeMap does not index its keys, so you would have to maintain a counter yourself when you iterate over the keys of the multimap.

Finally, the overall structure of your code sample is strange. Unit tests are meant to test whether some code works correctly. But your method mappingTest() not only performs the tests, it also contains the code to be tested. Of course, there's nothing wrong with placing assertions in code to test it. But what you wrote is not a unit test, because it doesn't test any defined unit (for example a method). It just executes some code and then uses assertions to check whether the code did what you thought it would do.

Instead, I suggest that you first write a method that accepts a Map<K, Integer> (or any Map<K, V> where <V extends Comparable<? super V>>) as a parameter and returns a "compressed" version of this map:

public static <K, V extends Comparable<? super V>> Map<K, Integer> compress(Map<K, V> map) {
    //...
}

Then, you write a separate method that tests that method by constructing a map like you did in mappingTest(), passing this map to compress(Map) and then inspecting the returned Map. This would be a unit test, because you are testing the functionality of a unit, i.e. the method compress(Map).


First, your CSS has no errors, which is very good.  You can check for errors at the W3C validator.

Looking through your CSS, it looks very neat, and I would only remove a little bit of unnecessary code.  Also, the display seems to be optimized for IE.  I set it for FireFox and Chrome, and it displays almost correctly in IE.  The trouble is, the box for displaying the output is visibly small in FireFox and Chrome.  With my changes, it is 1 pixel too large in IE, but it is not as noticeable.

First, I would just use the body element here, instead of body > div:

body > div {
    width: 404px;
    border: 1px solid black;
    padding: 8px;
}

Right here, I adding a small padding so the font would have a small amount of space between it and the border:

.header input {
    /* ... */
    padding-right: 2px;
}

I found I could remove the overflow: auto; lines without effecting the display.

In .operations, you don't need to set font-size: 0;.  I do not know why you need to do that to remove the spacing in the .numberFields class, but I was unable to get it working without it.  I do not like that as it is not clear why you need to set the font-size there, and there is probably a cleaner way to do it, but the usual trick of using a negative margin value isn't working, and neither did setting the padding to 0px.

I did not make any other changes; as I said above, your CSS is very clean and neat.


Writing line item information from multiple tables

My thoughts in walking through your code are shown below:

include ('../cfg/connect.php');

This appears to be hard dependency.  You should use require such that this script fails out of you can't load the dependency. Also, your style of adding space between function/method name and opening parenthesis would be considered non-standard by most PHP developers. Typical usage has no space.  This makes reader less likely to confuse this parenthesis with a logical operation.

$s = " : ";
$br = "
";
$ul = "
";
$li = "
";
$_ul = "
";
$_li = "
";

Consider using constants for these, as they don't change during script execution.  You might also find this helps readability of your code when you begin to concatenate with these.

$categoryQry = "SELECT a.itemQty, b.transDate, b.transID, b.amount, a.itemPrice, a.itemCategory, c.catFamily, a.itemName, a.itemSource FROM budget.lineItems AS a JOIN budget.quickEntry AS b ON a.transID = b.transID JOIN budget.categories AS c ON a.itemCategory = c.catName WHERE b.processed = 'y' ORDER BY c.catFamily, c.catName, b.transDate";

This is a horrendously long line of code. You should strive to keep character count on a line under 80.  Break this query up across lines, making it much easier to read.

Example:

$categoryQry = <<<EOT
SELECT
    a.itemQty,
    b.transDate,
    b.transID,
    b.amount,
    a.itemPrice,
    a.itemCategory,
    c.catFamily,
    a.itemName,
    a.itemSource
FROM budget.lineItems AS a
JOIN budget.quickEntry AS b
    ON a.transID = b.transID
JOIN budget.categories AS c
    ON a.itemCategory = c.catName
WHERE b.processed = 'y'
ORDER BY c.catFamily, c.catName, b.transDate
EOT;

$categories = $conn->prepare ($categoryQry);
$categories->execute ();
$categories->store_result ();
$categories->bind_result ($itemQty, $transDate, $transID, $totalPrice, $itemPrice, $category, $family, $itemName, $source);

This all assumes happy-path execution.  What happens if prepare(), or execute() fail?  Last line of code is too long. Break it up

Example:

$categories->bind_result(
    $itemQty, $transDate, $transID, $totalPrice, $itemPrice,
    $category, $family, $itemName, $source
);

if (!isset($data[$transID]['amount'])) {
    $data[$transID]['amount'] = 0;
}
if (!isset($data[$transID]['line'])) {
    $data[$transID]['line'] = '';
}
if (!isset($data[$transID]['line'][$family]['amount'])) {
    $data[$transID]['line'][$family]['amount'] = 0;
}
if (!isset($data[$transID]['line'][$family]['line'])) {
    $data[$transID]['line'][$family]['line'] = '';
}
if (!isset($data[$transID]['line'][$family]['line'][$category]['amount']))
{
    $data[$transID]['line'][$family]['line'][$category]['amount'] = 0;
}
if (!isset($data[$transID]['line'][$family]['line'][$category]['line']))
{
    $data[$transID]['line'][$family]['line'][$category]['line'] = '';
}

$itemCount++;

$qtyPrice = $itemPrice * $itemQty;
$data[$transID]['amount'] += $qtyPrice;
$data[$transID]['transDate'] = $transDate;
$data[$transID]['source'] = $source;
$data[$transID]['line'][$family]['amount'] += $qtyPrice;
$data[$transID]['line'][$family]['line'][$category]['amount'] += $qtyPrice;
$data[$transID]['line'][$family]['line'][$category]['line'][$itemName]
= ['itemQty' => $itemQty, 'itemPrice' => $itemPrice];

I have concern over the overall data structure you are building.  First, I think there are more levels of nesting than is necessary. Second, the repeated use of line as key at different levels of depth seems odd and potentially confusing.

I would encourage you to really rethink your data structure with an object-oriented approach. Think about what are the "real world" properties that should exist for each item in the hierarchy and how you represent the relationship between items.

You might end up with a structure like that shown below (shown using JSON-like notation to indicate object structures - or alternately associative arrays in PHP).  This has 4 levels of nesting instead of 8 as your current model does.  Interestingly enough, you will also note that your logic to output this data structure has 4 levels.  That is because four levels of nesting is what the "real-world" relations between these objects in your hierarchy really dictate.

{
    'transactionid1': {
        'amount': *,
        'date': *,
        'source': *,
        'categories': {
            'categorynameA': {
                'amount': *,
                'lines': {
                    'linenameA': {
                        'amount': *,
                        'items': {
                            'itemnameA': {
                                'qty': *,
                                'price': *
                            },
                            'itemnameB': // more items
                        },
                    'linenameB': // other lines
                },
            'categorynameB': // other categories
        },
    'transactoinid2': // other transactions
}

This isn't exactly optimized for your display loops (which do not require unique lookup capabilities by transaction id, category, etc. as  are required to build this structure from the result set), but I don't think that it makes sense to reconfigure this structure for this simple use case.

There is additionally some confusion on naming of family, categories, lines between the DB and what is being output to user. For example it seems family in DB maps to categories for output which seem strange.  You might consider aliasing your fields in your query to be able to use common terminology throughout both the section of code where you build the data structure and where you output it.

In your output, consider keeping spaces around all . used for concatenation.  This helps make code easy to read and allows for good visual line breaks in editors if a line does happen to go too long while editor is using "word wrapping".

Also, I think using objects (as mentioned in data structure comment above) instead of associative arrays helps in readability.  This along with suggestion to use constants might yield code that looks like the following:

// assume you have constants S, BR, UL, LI, _UL, _LI
foreach ($data as $txn_id => $txn) {
    echo $txn_id . S . $txn->date . S . $txn->source . S . $txn->amount . UL . PHP_EOL;
    foreach ($txn->categories as $cat_name => $cat) {
        echo LI . $cat_name . S .$cat->amount . UL . PHP_EOL;
        foreach ($cat->lines as $line_name => $line) {
            echo LI . $line_name . S . $line->amount . UL . PHP_EOL;
            foreach ($line->items as $item_name => $item) {
                echo LI . $item_name . S . $item->qty . S . $item->price . _LI . PHP_EOL;
            }
            echo _UL . _LI . PHP_EOL;
        }
        echo _UL . _LI . PHP_EOL;
    }
    echo _UL . BR . PHP_EOL;
}

To me, this is much easier to read and a pretty good approach short of going to more of a template approach.


You can use an interface and a generic method to remove the code duplication:

public interface IStatistic
{
    string Country {get; set;}
    DateTime Date {get; set;}
    Decimal Total {get; set;}
}

public static class StatisticExtension
{
    public static void MergeNullAndEmplyCountry<T>(this IEnumerable<T> totalUserStatistic) where T : IStatistic, new()
    {
        foreach (var item in totalUserStatistic)
            if (string.IsNullOrWhiteSpace(item.Country))
                item.Country = "";

        totalUserStatistic = totalUserStatistic.GroupBy(item => new { item.Country, item.Date })
                                                .Select(groupedUser => new T()
                                                {
                                                    Country = groupedUser.Key.Country,
                                                    Total = groupedUser.Sum(item => item.Total),
                                                    Date = groupedUser.Key.Date
                                                }).ToList();
    }
}

Important here is the new() constraint, which allows us to create an instance of T.

If the Total property of a class is int instead of decimal, we can make use of an explicit interface implementation:

public class BlaStatistic : IStatistic
{
    public string Country {get; set;}
    public DateTime Date {get; set;}
    public Int32 Total {get; set;}
    Decimal IStatistic.Total
    {
        get { return Convert.ToDecimal(Total); }
        set { Total = Convert.ToInt32(value); }
    }
}

Also, your extension method should actually return something, because it won't change the IEnumerable<...> you pass in:

public static IEnumerable<T> MergeNullAndEmplyCountry<T>(this IEnumerable<T> totalUserStatistic) where T : IStatistic, new()
{
    ...
    return totalUserStatistic.GroupBy...
}


In Lua, it's not necessary to separate statements by a semicolon (it's not even necessary to do it when writting several statements in the same line). However it's possible to do it.

In this snippet:

for k, v in pairs(self.res.queue) do
    if (not v or not v.f or not v.t) then goto continue end;
    if (v.t ~= self.RESOURCE_FONT) then
        queueChannel:push(v);
    else
        fonts[k] = v;
    end
    ::continue::
end

You're using pairs in several parts of the code to iterate tables which are actually arrays. Variable self.res.queue is an array since:

function GameState:queue(file, arg)
    self.res.loaded = self.res.loaded + 1;
    self.res.queue[self.res.loaded] = <object>;
end

In the cases a table is actually an array is preferred to use ipairs because is way more faster than pairs. In addition to that, it tells other people reading the code the table is actually an array (which is a valuable hint in a dynamic language such as Lua).

At the bottom of GameState:loadQueue:

if (table.size(self.res.queue)-table.size(fonts) > 0) then
    queueThread:start(); else
    queueChannel = nil;
    queueThread = nil;
    return;
end

self.state = self.STATE_LOADING

The return statement in the else branch can be removed if you move self.state up to the then branch. The semantics hold as either queueThread:start() or not.

if (table.size(self.res.queue)-table.size(fonts) > 0) then
    self.state = self.STATE_LOADING;
    queueThread:start();
else
    queueChannel = nil;
    queueThread = nil;
    return;
end


Your implementation is technically correct, but...
There is no benefit in using Task.Run in an web application.
All you're doing is deferring work from one thread to another. So, in fact, not only is there no benefit, you're actually adding overhead.
I'll quote Stephen Cleary, because I could nevet put it better:

There are (at least) four efficiency problems introduced as soon as you use await with Task.Run in ASP.NET:

Extra (unnecessary) thread switching to the Task.Run thread pool thread. Similarly, when that thread finishes the request, it has to enter the request context (which is not an actual thread switch but does have overhead).
Extra (unnecessary) garbage is created. Asynchronous programming is a tradeoff: you get increased responsiveness at the expense of higher memory usage. In this case, you end up creating more garbage for the asynchronous operations that is totally unnecessary.
The ASP.NET thread pool heuristics are thrown off by Task.Run “unexpectedly” borrowing a thread pool thread. I don’t have a lot of experience here, but my gut instinct tells me that the heuristics should recover well if the unexpected task is really short and would not handle it as elegantly if the unexpected task lasts more than two seconds.
ASP.NET is not able to terminate the request early, i.e., if the client disconnects or the request times out. In the synchronous case, ASP.NET knew the request thread and could abort it. In the asynchronous case, ASP.NET is not aware that the secondary thread pool thread is “for” that request. It is possible to fix this by using cancellation tokens, but that’s outside the scope of this blog post.

So, unless you're doing true async I/O, do it synchronously.
Alternatively, if you want to expose an async interface, where the implementation may or may not perform asynchronous I/O, synchronous implementation should use Task.FromResult instead of Task.Run. Example:
interface IRepository<T>
{
     public Task<T> GetByIdAsync(object id)
}

// implementation that uses synchronous I/O
class SyncRepository<T> : IRepository<T>
{
    public Task<T> GetByIdAsync(object id)
    {
        T t = this.Entities.Find(id);
        return Task.FromResult(t);
    }
}

// implementation that uses async I/O
class AsyncRepository<T> : IRepository<T>
{
    public Task<T> GetByIdAsync(object id)
    {
        return this.Entities.FindAsync(id);
    }
}

Read also:

Stephen Toub's Should I expose synchronous wrappers for asynchronous methods?.
Stephen Cleary's Task.Run Etiquette Examples: Don't Use Task.Run in the Implementation


How to tweak Tape Equilibrium assignment on Codility to be of complexity O(N)?

General improvements

Your method can be made static
Your variable name A would be better as input
By using "early return" or "early throw", your intendation level can be improved a bit
Collections.sort(differences, (o1, o2) -> o1.compareTo(o2)); can be just Collections.sort(differences);
You are using A.length < 3 as an edge case, I would just consider A.length <= 1 as an edge case, the rest should be possible to be handled by your algorithm.

Why is your approach \$O(n^2)\$?

Consider what this code is actually doing:

for (int j = 0; j < A.length - 1; j++) {
    int[] subArrayOne = Arrays.copyOfRange(A, 0, j + 1);
    int[] subArrayTwo = Arrays.copyOfRange(A, j + 1, A.length);
    int sumOne = IntStream.of(subArrayOne).sum();
    int sumTwo = IntStream.of(subArrayTwo).sum();

    differences.add(Math.abs(sumOne - sumTwo));
}
Collections.sort(differences, (o1, o2) -> o1.compareTo(o2));

For every index in your array it does the following things:

Create an subarray, which is an \$O(n)\$ operation
Calculate the sum of the two newly created arrays, which is an \$O(n)\$ operation

These operations makes your code become \$O(n^2)\$

Additionally, it then afterwards does a Collections.sort operation which is \$O(n * log(n))\$

How to do it faster

Initialize a variable sum to be the sum of your whole array, and a sum2 to be 0
For every index, decrease sum with the current value, and increase sum2 with the current value. Then create a diff for sum and sum2 and see if it is lower than the previous lowest record.

Spoiler alert: Here is what I ended up with.

public static int solution(int[] input) {
    boolean eachIntegerIsWithinValidRange = IntStream.of(input).allMatch(i -> (i >= -1000 && i <= 1000));
    boolean numberOfElementsIsWithinDesignatedBounds = input.length >= 2 && input.length <= 100000;

    if (!eachIntegerIsWithinValidRange) {
        throw new RuntimeException("There is/are integer that is out of designated bound: -1000 to 1000");
    }
    if (!numberOfElementsIsWithinDesignatedBounds) {
        throw new RuntimeException("Invalid array size. Allowed number of elements is more than 1 and less than 100,001");
    }
    if (input.length == 0) {
        return 0;
    }

    int sum = IntStream.of(input).sum() - input[0];
    int sum2 = input[0];
    int lowestDiff = Math.abs(sum - sum2);
    for (int j = 1; j < input.length - 1; j++) {
        int value = input[j];
        sum -= value;
        sum2 += value;
        int diff = Math.abs(sum - sum2);
        if (diff < lowestDiff) {
            lowestDiff = diff;
        } else {
            return lowestDiff; // diff will not get any lower
        }
    }
    return lowestDiff;
}


Using Curl/Post to execute a HTTP request

Well, I didn't take the time to test my snippets, but here are two suggestions...

#1 (preferred) - Bundle all of your input data into a single array, then pass it to your receiving url with a single curl call.  It is best practice to minimize total calls (avoid iterated calls) so long as the operation works for your project, of course.  This avoids sleepy time too.

$ch = curl_init();
$fields = [
    ['input1' => 'variable1', 'input2' => 'variable2'],
    ['input1' => 'variable3', 'input2' => 'variable4']
];
$COOKIE_FILE_PATH = "/tmp/cookiescron.txt";  // this doesn't appear to be used
$options = [
    CURLOPT_URL               => 'http://127.0.0.1/index.php',
    CURLOPT_POST              => true,  // https://www.php.net/manual/en/function.curl-setopt.php says boolean is expected
    CURLOPT_POSTFIELDS        => http_build_query($fields),
    CURLOPT_TIMEOUT           => 2,
    CURLOPT_RETURNTRANSFER    => false,
    CURLOPT_FORBID_REUSE      => true,
    CURLOPT_CONNECTTIMEOUT    => 2,
    CURLOPT_DNS_CACHE_TIMEOUT => 10,
    CURLOPT_FRESH_CONNECT     => true,
    CURLOPT_HTTPHEADER        => ['Connection: close']
];
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);

#2 - If your requirements obligate the use of iterated curl calls, I'd recommend only updating the CURLOPT_POSTFIELDS value within the loop.  (Again, not tested)

$ch = curl_init();
$fields = [
    ['input1' => 'variable1', 'input2' => 'variable2'],
    ['input1' => 'variable3', 'input2' => 'variable4']
];
$COOKIE_FILE_PATH = "/tmp/cookiescron.txt";  // this doesn't appear to be used
$options = [
    CURLOPT_URL               => 'http://127.0.0.1/index.php',
    CURLOPT_POST              => true,  // https://www.php.net/manual/en/function.curl-setopt.php says boolean is expected
    CURLOPT_TIMEOUT           => 2,
    CURLOPT_RETURNTRANSFER    => false,
    CURLOPT_CONNECTTIMEOUT    => 2,
    CURLOPT_DNS_CACHE_TIMEOUT => 10,
];
foreach ($fields as $data) {
    $options[CURLOPT_POSTFIELDS => http_build_query($data)]; // overwrites previous data
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    sleep(25);
}
curl_close($ch);

The takeaway here is to always try to leave as many processes as possible OUTSIDE of the loop to reduce calls/workload.

Relevant documentation:

https://www.php.net/manual/en/function.curl-setopt.php
https://www.php.net/manual/en/function.curl-setopt-array.php


The names define and defined are too similar, which could lead to mistakes. I suggest renaming the latter to isDefined.

You could flatten some of the conditionals when all branches leave the block. For example:

// If we have already seen this id on the require stack, we've got
// some form of cyclic dependency.
if (stack.indexOf(id) !== -1 && stack.push(id)) {
  throw new Error('cyclic dependency: ' + stack.join(' -> '));
}
stack.push(id);

// If we already have an instance for this module, return it.
if (instances.hasOwnProperty(id)) {
  return instances[id];
}

if (typeof(definitions[id]) === 'function') {
  // Otherwise if our definition is a function, call it and pass the
  // require method to it.
  return instances[id] = definitions[id].call(null, internalRequire);
}

// Otherwise just return the definition itself (useful for objects
// e.g. constants).
return instances[id] = definitions[id];


I would suggest to create following new classes:

User, which stores information about user, like user_id, user_location
Text, which stores the tweet text, the language of the tweet, may be the keywords
Tweet, which contains objects of User ,Text and some other information about the tweet

I am assuming that you will be storing all this data into a database and the above mentioned structure (with some mild changes, based on your requirement) can be used to create a 3-NF database.

Another suggestion is "not" using stdin. Create a new file "Twitter.py" having function readTweet which will return tweet. This makes it easier to change the source of the tweet in the later part of the development. Suppose you want to directly take tweet from twitter API, then you just need to change the function

Your main function will look like following:

def main():

    for tweet in Twitter.getTweets():

        tweet_time = tweet.getTime()

        if tweet.isRetweeted:
            print "do something 0"
        elif tweet.hasEntities and len(tweet.Usermentions) > 0:
            for mention in tweet.userMentions:
                print "do something 1"
        else:
            print "do something 2"


Fetching BasicInfo, BillingInfo, and DocumentInfo objects

The template method pattern seems useful here:

Create a base class with a get_by_profile_id method that calls a get_queryset method to get the at appropriate QuerySet object to work with
The base class doesn't implement get_queryset, it's the job of the subclasses. This is the template method

Something along the lines of this in the base class:

def get_by_profile_id(self, profile_id, is_versioned):
    queryset = self.get_queryset().filter(profile_id=profile_id).order_by('-version')
    if is_versioned:
        return queryset
    return queryset[:1][0]

And in the subclass for BasicInfo:

def get_queryset(self):
    return BasicInfo.objects

Notice that I eliminated another duplication in the following and ordering logic. Note that Djangi will not execute the query until elements are accessed in the query set, so when I initialize queryset before the if condition, that doesn't hit the database.


Duplicate code in similar classes where I cannot add more inheritance

Interesting question. The most simple and direct way to approach this problem (not necessarily the wisest) - implement Select(), From(), Join() etc. as extension methods on the interfaces ISelectable, IFromable, IJoinable, etc. The ability to write extension methods to interfaces is a powerful and fascinating language feature with many implications...


Generally looks good. Except

    final BigInteger squaredTerm = new BigDecimal(Math.pow(currentTerm.doubleValue(), 2)).toBigInteger();

There is absolutely no reason to cast Math in. The computations are supposed to be exact, which Math is notoriously lacking. I recommend

    final BigInteger squaredTerm = currentTerm.multiply(currentTerm);


Fahrenheit / Celsius temperature converter

I don't know enough bash to offer you a technical review.

But, more philosophically: Have you considered writing this more in the style of a "program" than a "Press 1 to convert another"-type interface? Like:

~$ temperature c 30
86 ˚F
~$ temperature F 105
40 ˚C

My reasoning is that the above is easier and more flexible to use programatically, you don't need to write input loops at all and you can condense down to your core functionality:

#!/bin/bash

case $1 in
    [Ff] ) echo "$(( ($2 - 32) * 5 / 9 )) ˚C"; break;;
    [cC] ) echo "$(( $2 * 9 / 5 + 32 )) ˚F"; break;;
    *    ) echo "Usage: $0 c|f num"
esac


Flipping True or False values to save typing and time

I'd replace the if-then-elses with DBGrid1.Columns[i].Visible := not DBGrid1.Columns[i].Visible - i.e. use the not keyword instead of your Flip function.

And you probably can store references to the relevant columns in an array, TList or similar. Then you don't need to loop all columns and check their names.


User defined literal for std::integral_constant

Usage of "fat" templates

I would try to avoid using full-blown class templates when there's an elegant alternative solution with alias templates or constexpr functions. Note that I didn't measure this, so take it with a grain of salt: lightweight constexpr functions and alias template can be faster to instantiate. Using constexpr functions might reduce the number of instantiations to a minimum of 1 (the literal operator template) or two (the constexpr function template with a single template type parameter).

Algorithm

By changing the order of operations, you can get rid of the pow function (template) entirely: Pass the current result to the next step, then multiply and add. The shifting (in base 10) will be done on the fly.

Sketch:

constexpr int combine(int p)
{
    return p;
}

template<class... TT>
constexpr int combine(int val, int p0, TT... pp)
{
    return combine(val*10 + p0, pp...);
}

constexpr int parse(char C)
{
    return (C >= '0' && C <= '9')
           ? C - '0'
           : throw std::out_of_range("only decimal digits are allowed");
}

template<char... Digits>
constexpr auto operator"" _c()
-> std::integral_constant<int, combine(0, parse(Digits)...)>
{
    return {};
}

Literals in other bases

Your parse function currently rejects hexadecimal, octal, and in C++1y binary literals, as well as C++1y's digit separators. Supporting the bases < 10 is fairly simple because you only need to change the "shifting" factor. I.e. multiply by 8 or 2 instead of 10. For base 16, you also need to add some code to the character -> digit conversion. IIRC, it's not guaranteed that the letters are contiguous in the basic execution character set (as opposed to the digits), so this could be rather painful w/o a switch or lookup-table. Also, upper/lower case.

Automatically growing literal type

Normal C++ literals automatically adjust their types according to their value. If they don't fit into an int, they'll try long, long long etc. Maybe one of the user-defined literals should mimic that behaviour for convenience.

Operators

Unfortunately, the StdLib doesn't provide operators for std::integral_constant. Therefore, -23_c will not be a std::integral_constant<int, -23> but rather an int (via the implicit conversion operator). I find that surprising.

Consider using a custom type, possibly derived from / convertible to std::integral_constant and provide (metaprogramming) operators for this type.

Side remark:

lit<45> is much easier to implement:

template<std::uintmax_t N>
using lit = std::integral_constant<std::uintmax_t, N>;


Toggle menu under specified screen width

Feedback

The code looks pretty good. The Javascript code waits until the DOM is ready, then caches references to DOM elements in variables before using those variables in the functions later on.

I initially thought some of the CSS could be consolidated (e.g. many common styles under .menu-link and .menu a but then I realized that might be tricky with the SCSS...

  I want to invoke a function only once if the window's width is smaller than a given breakpoint. Should I use some boolean variable, or is there a better solution?

One technique for this is to use a debounced function callback. There are jQuery plugins for that, or that article mentions ways to achieve it on your own (like I suggested in this SO answer).

Suggestions

Toggle the display using .toggle()

The .show() and .hide() calls can be replaced with a single call to .toggle(). Also, using the second form of .toggleClass(), the class name toggled can be added/removed depending on whether the menu button is being displayed or not (i.e. if the width is less than the break point). Thus the function changeMenuStyle() can be reduced to two lines (or one if you move the conditional out of a variable):

function changeMenuStyle() {
    var LTBreakpoint = $window.width() < breakpoint;
    $menuBtn.toggle(LTBreakpoint).toggleClass('toggled', LTBreakpoint);
}

Remove closure just to call function

The resize callback can simply be the name of the function - i.e.

$window.on('resize',function() {
    changeMenuStyle();
});

Can be simplified to:

$window.on('resize', changeMenuStyle);

Though be aware that the event parameter would get passed to the function, which could have adverse affects if the function is expecting other parameters.

CSS media query

I should have mentioned this, as Rotora did- CSS media queries can be used to eliminate much of the Javascript code (like you did in the CSS for this post).

Adding this CSS:

/* default settings ( width >= 800px) */
#menu{
    display: block;
}
[href="#menu"] {
    display: none;
}
/* only when screen width is less than 800px */
@media (max-width: 799px) {
    #menu{
        display: none;
    }
    [href="#menu"] {
        display: block;
    }
}

Can allow the JS to be simplified to:

$(document).ready(function() {
  var $menuBtn = $('[href="#menu"]'),
      $nav = $('#menu');

  $menuBtn.on('click',function(e) {
    e.preventDefault();
    $nav.slideToggle();
  });
});

$(document).ready(function() {
  var $menuBtn = $('[href="#menu"]'),
      $nav = $('#menu');

  $menuBtn.on('click',function(e) {
    e.preventDefault();
    $nav.slideToggle();
  });
});
* {
  box-sizing: border-box;
}

body {
  background: #485373;
  font-family: "Lato", sans-serif;
  font-weight: 300;
}

.container {
  max-width: 940px;
  margin: 0 auto;
}

.menu-link {
  display: block;
  color: #fff;
  background: #202332;
  width: 100%;
  padding: 20px;
  text-decoration: none;
}
.menu-link i {
  display: inline-block;
  margin: 0 10px;
}

.menu {
  overflow: hidden;
}
.menu i {
  display: block;
  font-size: 25px;
  padding: 10px 0;
}
.menu ul {
  width: 100%;
}
.menu li {
  width: 20%;
  float: left;
  text-align: center;
}
.menu a {
  display: block;
  padding: 20px;
  width: 100%;
  background: #323A51;
  color: #fff;
  text-decoration: none;
  border-bottom: 2px transparent solid;
}
.menu a:hover {
  background: #202332;
  border-bottom: 2px #fff solid;
}
.menu.toggled i {
  display: inline-block;
  margin-right: 10px;
  padding: 0;
  font-size: 15px;
}
.menu.toggled li {
  width: 100%;
}
.menu.toggled a {
  padding: 10px;
}

main {
  padding: 50px;
  color: #fff;
}
main h1 {
  font-size: 30px;
  font-weight: 400;
  line-height: 40px;
  margin: 10px 0;
}
/* default settings ( width >= 800px) */
#menu{
    display: block;
}
[href="#menu"] {
    display: none;
}
/* only when screen width is less than 800px */
@media (max-width: 799px) {
    #menu{
        display: none;
    }
    [href="#menu"] {
        display: block;
    }
}

    Menu

Home

About

Services

Team

Contact

Toggle menu

Vestibulum tempus at ipsum a finibus. Mauris pharetra eleifend odio quis lacinia. Pellentesque ullamcorper, dolor vel congue tincidunt, mi nisl suscipit metus, nec bibendum elit ligula vitae leo. Integer volutpat semper iaculis. Mauris fermentum, enim ac finibus scelerisque, magna nibh volutpat dolor, vitae sodales mi augue molestie augue. Aliquam ultricies eget mi vel viverra. Morbi id tortor purus. Vivamus sed pretium justo. Fusce porttitor eu neque quis volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ultrices metus a aliquet tincidunt. Ut pellentesque dui nec ipsum fringilla ultricies.


Your question is why does it take a long time to update the Application.StatusBar 10,000,000 times?  The answer is that you are updating the Application.StatusBar 10,000,000 times.

Using the Timer from TheSpreadSheetGuru, I calculated that it takes roughly 1 sec to do 10,000 updates.  So it will take roughly 10,000,000/10,000/60 minutes just to do the updates.  That is roughly 16.667 minutes.

Sub CalculateRunTime_Seconds()
'PURPOSE: Determine how many seconds it took for code to completely run
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
    Dim x As Long
    Dim StartTime As Double
    Dim SecondsElapsed As Double

    'Remember time when macro starts
    StartTime = Timer

    '*****************************
    'Insert Your Code Here...
    For x = 1 To 1000
        Application.StatusBar = x
    Next
    '*****************************

    'Determine how many seconds code took to run
    SecondsElapsed = Round(Timer - StartTime, 2)

    'Notify user in seconds
    MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation

End Sub


Design pattern to implement Database operations

I think you might be looking for an ORM, which provides you with an intermediate layer between your application and the database for the sake of clarity.

Since you already mentioned that EntityFramework is not an option, you should consider developing your own library. It's going to take a while, but you surely won't have any headaches while hunting down the bugs of a library you didn't write or don't understand.

In your code, you are calling the delete, insert and update methods on the instances themselves, which is a bad idea per se, since these methods are executed on the database and not on that particular instance. Instead, you could solve this by refactoring your code.

I suggest you recreate the structure of your database server in your application too: you have one database server, within a server there are multiple databases (eg. abstract class for DatabaseEntity) and within a database there can be multiple tables (eg. abstract class for TableEntity). If you execute actions on a table, you might want to do this the following way:

public class MyServer
{
    // ....
}

public class MyDatabase : DatabaseEntity
{
    // ....
}

public class Account : TableEntity
{
    public int Identifier { get; set; }
}

MyServer Server = new MyServer();

Account MyAccount = Server.Database<MyDatabase>.Select<Account>(x => x.Identifier == 123);

MyAccount.Identifier = 456;
Server.Database<MyDatabase>.Update<Account>(MyAccount);

Server.Database<MyDatabase>.Insert<Account>(new Account());

Within that particular Insert<> function, you can scan through the properties and convert their names and values into an INSERT INTO query and execute it. You can also create an attribute for the primary key, which will be used as global identifier when eg. updating an instance. Most likely the hardest part is going to be the Select<> method. You literally have to examine the expression tree in the parameters, so that this expression:

Server.Database<MyDatabase>.Select<Account>(x => x.Identifier == 123);

can become pure SQL (or whatever db you're using):

SELECT * FROM `MyDatabase.Account` WHERE `Identifier` = 123;

With your own solution, you can shape the structure of your library to perfectly suit all your needs and to keep your code clean and well understandable.

Also, I currently have a weekend ORM project on Github based on the previously mentioned structure, you should check out the source code. Feel free to adapt it to your needs or use useful snippets from it.


Decide if the sum of three numbers is even or odd

First off, you have nice, clean, well-formatted, easy-to-read code. You have even included comments that explain the goal of each instruction. Too much of the time I review assembly-language code, these are the things that go wrong. You've gotten them all correct. Nice job! Now I don't have to pull my hair out trying to read and understand your code.

Unfortunately, were I your instructor, I'd still have to give you a failing score on the assignment because you didn't follow the rules. The assignment says that you must "Do it without actually adding the numbers.", but right off the bat, you ADD the input values together. And we were off to such a good start… :-(

Now, personally, I think these types of assignments are rather silly, so I wouldn't be giving them. If I wanted you to learn how to use the bitwise operators, I'd find something useful and real-world that they are good for, and then give you that assignment. It's not like I'd have to work very hard. The chip designers didn't put them in merely for fun.

Oh well; you have to do the assignment that you were given. So follow the hint, use XOR. Maybe you don't know exactly what that means, so what I'd do is open up a programmer's calculator (all major desktop operating systems have a "programmer" mode for their calculators) and play around with it. Pick random combinations of positive and negative numbers, and compare what the results are when you add them together versus when you XOR them together. Try to get a feel for what XOR does. Then, look up a formal definition of XOR (exclusive-OR). If you're like me, your eyes glaze over at the symbolic logic stuff (which wasn't so great when I took that course in college); feel free to skip over that for the purposes of this assignment. Your real goal here is to find out what XOR actually does at the bit level. There are lots of detailed explanations of bitwise manipulation online, or you may have a textbook that covers this stuff, too.

For example:

    01101101
XOR 11010100
_____________
    10111001

Notice that each column follows the truth table for an XOR operation, which basically just says that the output is 1 (true) whenever the inputs differ. That's the "exclusive" part of the OR.

Eventually, while doing this preliminary research, I suspect you'd come across someone talking about how XOR operations are used to implement parity checks. Mast's answer here already spilled the beans. Parity indicates whether an integer is even or odd, and can be calculated simply by a XOR sum of the bits. Judging from your comments in the code, you already know that for a binary number, the lowest (least significant) bit determines whether it is odd or even.

So the good news is that your code is almost entirely correct. If you change the ADDs to XORs, it will follow the rules of the assignment and produce the correct result. Thus, you would have:

call    read_hex              ; Provided by the teacher. Reads a hexadecimal number from stdin.
mov     ebx,    eax
call    read_hex
xor     ebx,    eax
call    read_hex
xor     ebx,    eax

Now we've XOR-summed all of the bits from the three inputs. All that's left is figuring out the parity of the result—i.e., whether the XOR-sum is odd or even.

You've already implemented one way of doing that, but as Quuxplusone pointed out, it is an unnecessarily complicated way. While it doesn't always hold when you start getting into more advanced things, for simple arithmetic operations, fewer instructions means faster code. Arguably more importantly, it means simpler code, which is more likely to be correct code. Moreover, fewer branches virtually always mean faster code, and certainly code whose flow of execution is easier to follow, and thus easier to debug.

I'd disagree slightly with Quuxplusone here and say that clever is totally fine, as long as your cleverness has some notable advantage. You don't always have to write code the "normal" way, because the "normal" way might be sub-optimal. Generally, if we're dropping down to write in assembly, it's because we want to write the best code we possibly can (either fastest, shortest, or whatever metric we are using to judge "best"), which means that "normal" isn't necessarily an important goal. Sometimes, "readable" isn't even an important goal. But, by the same token, I do agree there's no point in deviating from what is normal if your deviation is inferior, and that's certainly the case here.

Your XOR-sum is in the EBX register. You know that the XOR-sum tells you the parity in the least-significant bit. So what is the obvious thing to do? Mask off everything but the least-significant bit, and that'll be your answer! How do we mask off bits? Use a logical AND operation:

and  ebx, 1   ; mask off all but the low-order bit

Oh, and finally, since we need the result in EAX, we'll do:

mov  eax, ebx

(We could have just as easily done the MOV first, before the AND. It doesn't matter.)

Go through your current code, and prove to yourself that this gives exactly the same results, without needing to flip the bit with the XOR, without needing to involve the carry flag (CF) via ROR, and without needing to do any conditional branching (JC).

Putting it all together, the code is essentially:

call    read_hex              ; Provided by the teacher. Reads a hexadecimal number from stdin into EAX.
mov     ebx, eax
call    read_hex
xor     ebx, eax
call    read_hex
xor     ebx, eax

mov     eax, ebx              ; Move XOR-sum of three given numbers into EAX.
and     eax, 0x1              ; Mask off all but the lowest-order bit.
call    print_eax_binary      ; Provided by the teacher. Prints a binary number in EAX to stdout.

; Exit the process:
push    0
call    [ExitProcess]

Simpler, clearer, faster. Rarely is it possible to say this about any piece of code, but I believe this really is the most optimal way to write this.


Total number of common factors for two numbers LARGE VALUES up to 10^12

long long count = 0, m, n;
    ...
    for (long long int i = 1; i <= ((min(m, n)) / 2) + 1; i++) {

long long or long long int? I'm not a C++ programmer so I don't know whether style guides have a preference, but I'm quite certain that you should be consistent.

  Inputs are two values \$1 \le m , n \le 10^{12}\$. I don't know why my code is taking so long
  ...

   for (long long int i = 1; i <= ((min(m, n)) / 2) + 1; i++) {

There you go. The main loop runs up to \$5 \times 10^{11}\$ times. As a rule of thumb, when brute-forcing a problem I work on the basis that \$10^9\$ is about as high as I want to go.

Solution: change your algorithm. This will require learning some mathematics, and I'm not going to write a detailed tutorial, but there are two things you need:

Basic number theory: unique prime factorisation, greatest common divisor, finding it efficiently;
Sane factorisation of a small number (and \$10^{12}\$ is very small in these terms)

If you wanted to do it properly then you could extend the number theory research and learn about Euler's totient function.


Print input lines longer than 80 characters

Just to elaborate on @ratchet freak's answer, what you need is a two-state program.

In state 1, when fewer than 80 characters have been input on a single line, store these characters in a buffer and increment a counter to reflect the number of characters that have been stored. If you receive a newline character in this state, reset the counter and start again.

As soon as this counter reaches 80, print out the contents of this buffer and switch to state 2, where characters are output as soon as they are received. There is no need to continue buffering in this state. If you receive a newline character, go back to state 1.

With this approach, there's no need to store more than 80 characters in memory (plus one byte for the terminating '\0'), and no possibility of a buffer overflow.

#include <stdio.h>
#define MIN_LENGTH 80

int main(void) {
  char buffer[MIN_LENGTH + 1];
  int c, n=0;

  while (1) {

    c = getchar();
    if (c == EOF) break;

    if (n < MIN_LENGTH) {

      /* State 1: Fewer than MIN_LENGTH characters in line */

      if (c == '\n') n = 0;
      else {
        buffer[n++] = c;
        if (n == MIN_LENGTH) {
          buffer[n] = '\0';
          printf("%s",buffer);
        }
      }
    }

    else {

      /* State 2: At least MIN_LENGTH characters in line */

      putchar(c);
      if (c == '\n') n = 0;
    }
  }

  return 0;
}


Con

Use full names. If it's a connection string then name it ConnectionString especially if it's out of scope and one cannot easily determine what it is.

    using (OleDbConnection conn = new OleDbConnection(Con))
    {
        using (OleDbCommand cmd = new OleDbCommand())
        {

You can join both usings together:

    using (OleDbConnection conn = new OleDbConnection(Con))
    using (OleDbCommand cmd = new OleDbCommand())
    {

for (int s = 0; s < DGVExcel.Rows.Count - 1; s++)

I don't see any reason for not using the i for the index. If it was the r it would at least stand for row but what does the s mean?

Insert INTO ACTB (FirstName, LastName,... VALUES(@First, @Last,

Why do you invent new names for the parameters? Isn't it easier to just copy/paste the one you already have for the columns?

Besides with so many colums consider using an array and build the query dynamically. You can create an array with a collection initializer like this:

var columns = new []
{
    "FirstName",
    "LastName",
    // ...
}

Then you join all names into a string separated by , as column names and another string also separated by commas but with the @ prefix for the values:

var sql =
    $"Insert INTO ACTB ({string.Join(", ", columns)} " +
    $"VALUES({string.Join(", ", columns.Select(x => $"@{x}"))}";

If you create the columns array with the names in the right order (like in your excel sheet) you can even reuse them to populate the parameters. Here's the complete example.

using (var conn = new OleDbConnection(Con))
using (var cmd = new OleDbCommand())
{
    cmd.Connection = conn;
    conn.Open();

    var columns = new[]
    {
        "FirstName",
        "LastName",
        // ...
    }

    var sql =
        $"Insert INTO ACTB ({string.Join(", ", columns)} " +
        $"VALUES({string.Join(", ", columns.Select(x => $"@{x}"))}";

    for (var i = 0; i < DGVExcel.Rows.Count - 1; i++)
    {
        cmd.Parameters.Clear();
        for (var j = 0; j < columns.Length; j++)
        {
            cmd.Parameters.AddWithValue($"@{columns[j]}", DGVExcel.Rows[i].Cells[j].Value);
        }

        cmd.ExecuteNonQuery();
        Console.WriteLine(i);
    }
}


The code reads from a specified offset to the specified number of bytes in a file

Fails with large offset, bytes

read(fd, buf, offset); reads out of buf[] bounds when offset > buf_size.  Same for bytes.  This should be tested.

Unclear why buf[buf_size] is so small (5).  How about 4096 or 1 Meg?

Handle large offset

I'd expect code to handle offsets far larger than the sizeof buf.  Looping on read(fd, buf, offset); if needed.

int math

Files sizes can well exceed INT_MAX.  For offset, bytes, I'd use long long.

Unneeded loop

Rather than a for() loop for (i = 0; i < rlen; i++) putchar(buf[i]);, use write(1, ...).

Missing close()

Function Limitations

OP has "not allowed to use system calls other than open, close, read, write".  What about error(), printf(), atoi(), putchar() - or are those classified differently?

With such a limit, looks like a lot of includes.

Algorithm flaw?

The first while (1) loop looks wrong.

Either the first iteration will get the expect offset number of bytes and proceed to the 2nd while ().

Or

it will read insufficient number of bytes (for reasons other than no -more bytes will ever exist) and loop again, trying to read offset bytes again.  I'd expect that offset would have been reduced by the previous rlen.  Without that reduction, if(len == offset) may never be satisfied as reading too many offset bytes is then possible.

I'd expect 2 while loops that are not nested.  First to read the offset bytes, next to read the bytes.

Further this could be sub-function calls.  Something like:

if (read_bytes(handle, offset, no_echo) == OK) {
  if (read_bytes(handle, bytes, echo_to_stdout) == OK) {
    success();
  }
}
fail();


Copying contents of two files into one file/ bufferedReader close calls

A little bit about code style: it is conventional to surround binary operators with whitespaces(for instance, getApplicationContext().getFilesDir()+"/BirthdayReminders/fileone.txt" should be  getApplicationContext().getFilesDir() + "/BirthdayReminders/fileone.txt") and there should be a whitespace after a closing bracket and before the opening one(that is, } finally { is better than }finally{ and so on).
Yes, you should check that br and r are not null before calling the close method on them. The FileReader constructor can throw an exception. In this case they will be null.  However, you can use try-with-resources(if you have Java 7 or later) to make your code more simple and concise:

try (
    BufferedReader reader1 = new BufferedReader(new FileReader(...));
    BufferedReader reader2 = new BufferedReader(new FileReader(...))
) {
    // do something
} catch (IOException e) {
    // do something else
}

Variable names: r and br are not really descriptive(however, their scope is very narrow so it is not a very big deal in this case). The same holds true for other variables: I would use something like lines instead of list and so on.
This kind of initialization is pointless in my opinion:

BufferedWriter writer = null;
writer = new BufferedWriter(new FileWriter(getApplicationContext().getFilesDir() + "/BirthdayReminders/output.txt"));

This one looks better:

BufferedWriter writer = new BufferedWriter(new FileWriter(getApplicationContext().getFilesDir() + "/BirthdayReminders/output.txt"));

The listWord variable and an index-based loop is redundant:

for (String listWord: list) {
    // do something
}

For-each loop is shorter and simpler.


Speed up query to rank team sales by aggregating data from two databases

Try what's below on for size. The date calculation is moved out of the loop, the TeamSales list capacity is pre-allocated and finally, the two LINQ statements are combined into one and rolled into AddRange rather than the explicit loop.

public static int GetNationalRank(int teamId, int CurrentUserId)
{
    int currentUserRank;
    var startDate = Convert.ToDateTime(DateTime.Now.AddDays(-(DateTime.Now.Day - 1)).ToString("M/d/yyyy"));
    var endDate = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("M/d/yyyy"));
    List<ProPit_User> proPitUsers;

    using (var ppdb = new ProsPitEntities())
    {
        proPitUsers = ppdb.ProPit_User.Where(x => x.SalesRepID != null).ToList();
    }

    var teamSales = new List<TeamSales>(proPitUsers.Count());

    using (var db = new TraegerEntities())
    {
        teamSales.AddRange(proPitUsers
            .Select(user => new
            {
                user,
                total = db.Orders.Where(o => o.DateCompleted >= startDate
                    && o.DateCompleted < endDate
                    && (o.Status == 1 || o.Status == 2)
                    && o.Kiosk != 0
                    && o.SalesRepID == user.SalesRepID).Select(o => (decimal?)o.OrderTotal).Sum() ?? 00.0M
            })
            .Select(userTotal => new TeamSales { userId = userTotal.user.userID, TotalSales = userTotal.total }));

        var rank = teamSales
            .OrderByDescending(x => x.TotalSales)
            .FindIndex(x => x.userId == CurrentUserId);

        currentUserRank = rank == -1 ? 0 : rank + 1;
    }

    return currentUserRank;
}


How to add exceptions in a class that reads a config file?

Throwing

Yes, just throw it:

if (val1 < 0)
  throw MissingConfigValueException("getVal1() failed or val1 < 0");

Don't print an error message before throwing. Printing is left to whoever catches the exception. For many exceptions (such as missing config values), there may be nothing wrong, so no need to print anything.

When you do print error messages, print to std::cerr — error messages belong on standard error, not standard output.

failedGetValue is not needed, since all it would do is throw an exception.

Catching

Catch exceptions where you can handle them. If the code that calls getVal1 can recover from a missing config value (perhaps by using a default), then it should catch the exception and proceed:

try {
  foo = config.getFoo();
} catch (MissingConfigValueException &e) {
  foo = DEFAULT_FOO;
}
doSomethingWith(foo);

If the caller can't handle the exception, then don't catch it. Just let it propagate up automatically. You don't have to do anything; that's the point of exceptions.

You don't have to catch all exceptions in main, because the default handler should print the exception and exit. You might do this if you want to handle them differently — for example, if you want to abort an operation rather than exiting, or if you want to log exceptions to somewhere other than standard error.

try {
  do(stuff);
} catch (std::exception &e) {
  std::cerr << "Uncaught exception: " << e.what() << std::endl;
}

Comments on other aspects of the program

If getVal2 is just like getVal1 with a different path, then they should be calls to one function, with the varying parts as parameters:

double getVal1() const { return getVal("path.to.val1"); }
double getVal2() const { return getVal("path.to.val2"); }

Or, even simpler, call getVal directly and don't bother with a separate function for each value.

Two problems with the name MyConfigFileException:

Names generally shouldn't contain My. Everything is MyFeature to someone, so it conveys no useful information. The name of a class should say what its instances represent, not who wrote it.
It doesn't say what the problem is. Exception names should say what's wrong, not just which component had a problem. In this case the problem is that a config value is either missing (MissingConfigValue) or invalid (InvalidConfigValue).

It would be nice to distinguish missing values from invalid ones, perhaps using ptree::get_optional. That would let you use the default (when there is one) in place of missing values, but reliably detect invalid values.

MyConfigFileException should derive from std::runtime_error, since it indicates a problem with the environment (specifically the config file), not a bug in the program. Actually, in a small program, I wouldn't bother with a new exception class — I'd just throw a runtime_error with an appropriate error message.

PTree does all this for you

Actually, you needn't check for missing values or throw an exception yourself, because ptree already does it.

The one-argument form of ptree::get throws an exception when the value is missing, and the two-argument form takes a default which is returned instead. This is exactly what you want for config values that have a default: get<int>("foo.bar", 5) returns the configured value of foo.bar, or 5 if there isn't one. When there is no default, get<int>("foo.bar") returns the configured value, or throws an exception.

ptree is intended for storing things like config files, and it's designed to make this convenient. Its authors have done your work for you!


IMHO the code looks fine so far.

However, I see few improvements:

Class Design

The instance variables _configItems and _configFile should be readonly
There is no need to implement IDisposable because you don't reference resources that must be disposed.
It makes sense to pass the file as constructor argument to make the class reusable for any ini files.
Maybe it makes sense to provide also a constructor that receives a stream, so that the class can be used with embedded resource ini files and so on.
In method LoadConfig you could create the FileInfo object once and use it subsequently (File.Exists and IsFileLocked)

Behavior

The method IsConfigurationLine could be turned into a more tolerant version when trimming the line string before (to support comments where the '#' is not on the first position)
If the value contains also '=' characters, your method returns only the part between the '=' that separates the key and the value and the first occurring '=' in the value.
The class kills the application if loading the configuration file fails. That may be a valid behavior for your application, but it is nothing that should be decided by the method that loads the configuration code. IMHO a better approach is to throw the exception and let the calling code handle the behavior.
The key is case sensitive. I am not sure if that is desired, otherwise you can simply change that by defining the comparer when initializing the dictionary: _configItems = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);