import requests
import re
from BeautifulSoup import BeautifulSoup
from datetime import datetime
class cricket(object):

Python conventions state that classes should CamelCase.

    def getMatches(self, url):

Python convention states that methods should be lowercase_with_underscores. Also, there isn't really a reason to have this method in a class anyway. Seems to me that it should be a function.

        """ Scrape the given url for match schedule """

        headers = {'Accept':'text/css,*/*;q=0.1',
        'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
        'Accept-Encoding':'gzip,deflate,sdch',
        'Accept-Language':'en-US,en;q=0.8',
        'User-Agent':'Mozilla/5 (Solaris 10) Gecko'}

I'd move this out of the function into a global constant.

        page = requests.get(url, headers = headers)
        page_content = page.content
        soup = BeautifulSoup(page_content)

I'd combine these three lines

soup = BeatifulSoup(request.get(url, headers = headers).content)

        result = soup.find('div', attrs={'class':'bElementBox'})
        tags = result.findChildren('tr')

I'd avoid non-descriptive names like result. Tags is a bit better, but not by a whole lot. I'd also combine these two lines

tags = soup.find('div', attr={'class':'bElementBox'}).findChildren('tr')

        match_type_list = ['TEST', 'ODI', 'T20']
        match_info = []

        for elem in range(1,len(tags)):

It'd make more sense to process things two rows at a time.

            dict_ = {}

Useless name alert.

            x = tags[elem].getText()
            x = x.replace(r'&nbsp;', '')

At this point, you extract the text and throw out the html. But the data is divided in table cells, so why in the world wouldn't you want to take advantage of that? At this point you drop down to trying to extract data straight from the text which much harder then if you can use the tags as hints.

            if 'Venue' in x:
                for a in match_type_list:
                    if a in x:
                        match_type = a

                x = x.replace('Venue', '')
                if 'Result' in x:
                    x = x.replace('Result', '')
                    x = x.split(': ')
                    # print x
                    venue = x[1]
                    result = x[2]

All this work to extract data from the string is something you really should use a regular expression for. This is exactly the kind of situation it excells at.

                    dict_.update({'venue':venue,'result':result,
                        'match_type':match_type})

Its not clear why you would choose to update rather then simply assign. There is no way that any other line of code in this loop can assign to it.

                else:
                    x = x.split(': ')
                    venue = x[1]
                    dict_.update({'venue':venue})

            else:
                match = re.search(r'\b[AP]M', x)
                date_time = x[0:match.end()]
                date_time = date_time.replace(',','')[4:]
                teams = x[match.end():].split('vs')
                home_team = teams[0].strip()
                away_team = teams[1].strip()

                # print date_time, home_team, away_team

                time_obj = datetime.strptime(date_time, '%b %d %Y %I:%M %p')

Organization seems a little suspect. You jump from working on the date, over to the teams, and then back to the date. I'd stick with date until it was finished. You also spend a bunch of lines massaging the date. However, strptime lets you specify any format you want, so you should just be able to have it parse the data

                timings = time_obj.strftime('%Y-%m-%dT%H:%MZ')

If I'm parsing, I wouldn't convert the time back into a date in another object. I'd keep it as a date object.

                dict_.update({'home_team':home_team,
                    'away_team':away_team,
                    'timings':timings
                })

            match_info.append(dict_)

        # print match_info

        final_list = []     # final list of dicts that we need

        for i in range(0, len(match_info), 2):
            final_list.append(dict(match_info[i].items() +
                match_info[i+1].items()))

I'd do this:

for i in range(0, len(match_info), 2):
    left, right = match_info[i:i+2]
    final_list.append( dict(left.items() + right.items() )

I think it makes things a bit clearer.

        # for i in final_list:
        #     print i
        # print final_list

this function probably needs to return that list or something.

if __name__ == '__main__':
    url = 'http://icc-cricket.yahoo.net/match_zone/series/fixtures.php?seriesCode=ENG_WI_2012' # change seriesCode in URL for different series.
    #url = 'http://localhost:6543/lhost/static/icc_cricket.html'
    c = cricket()
    c.getMatches(url)

Good

Here is my reworking of your code:

def get_cricket_matches(content):
    """ Scrape the given content for match schedule """

    soup = BeautifulSoup(content)

    all_rows = soup.find('div', attrs={'class':'bElementBox'}).findChildren('tr')

    match_info = []

    for index in range(1, len(all_rows), 2):
        rows = [row.findChildren('td') for row in all_rows[index:index+2]]

        data = {
            'match_type' : rows[1][0].findChildren('b')[1].getText(),
            'home_team': rows[0][2].getText(),
            'away_team' : rows[0][5].getText(),
            'match_time' : datetime.strptime(rows[0][0].getText(), '%a, %b %d, %Y %I:%M %p'),
        }
        for line in rows[1][1].findAll('b'):
            content = str(line.nextSibling)[1:]
            if line.getText() == 'Venue':
                data['venue'] = content
            else:
                data['result'] = content

        match_info.append(data)

    return match_info

  Personally, I don't like dependencies (in this case requests and
  BeautifulSoup). Why just not to use the standard modules?

Here I have to strongly disagree with @cat_baxter. Dependencies are the best part of python. That is, the availability and ease of installing all these different libraries to make it easier to write code is a great asset of Python. You should never be worried about taking on dependencies that are easy to install if it helps.

Having said that, you don't get a whole lot out of the requests module. So an argument can be made that this code would be better off using urllib.

But then the question is whether its a good idea to parse HTML with regex. With scraping you can get away with using a regex because regardless of the technique you use, changes to the page's structure will probably break it. The question at that point is which version has simpler and easier to write code.

Compare:

re.match('
.+
(.+).+
.+
', page).group(1)

and

soup.find('div', attrs={'class':'bElementBox'})

The HTML parser method takes advantage of knowing the structure of html to make it fairly easy to find the element. Is the regex entirely correctly? (Technically no, because simply regex can't parse HTML correctly, but is it good enough for job? I assume so, but I have more confidence in the HTML parser.)

columns = re.compile('(.*?)	', re.DOTALL | re.M).findall(table)

An equivalent would be

columns = table.findall('td')

Again, HTML parser wins hands down.

        'home_team' : columns[index + 2],

VS:

        'home_team': rows[0][2].getText(),

The difference between rows[0][2] and columns[index + 2] is the fact that I choose to structure the parser after the rows, whereas cat_baxter decided to throw away the rows and look just at the columns. Either approach can be done either way, so that's incidental to this question. But here the HTML parser method is slightly more complicated because it has to use .getText()

        'venue'     : re.match("Venue: ([\s,\w\']+)", columns[index + 7]).group(1),

m = re.match('.+Result:([\w, ]+)', columns[index + 7])
if m:
   row['result'] = m.group(1)

Vs

    for line in rows[1][1].findAll('b'):
        content = str(line.nextSibling)[1:]
        if line.getText() == 'Venue':
            data['venue'] = content
        else:
            data['result'] = content

I think this one is hard to call. I think my lines of code have less going on in them, but I think it might be somewhat more obvious what is happening in the regular expression.

My ending conclusion is that HTML parsers for scraping is often much nicer then using a regex, and sometimes a little worse. On the balance, I think its a way better idea.


Multiple regex matches to correct OCR output

I see something that bugs me in your code, that being default return values and some unused regex expressions declared, for example in the following function:

private string CheckInvertColor(string input)
{
    if (yes.IsMatch(input))
    {
        return "Yes";
    }

    else
    {
        return "No";
    }
}

Why do you only check if the yes regex is a match, what if the input is different from the one that matches the no answer? What do you expect the code to do in this case? You return a "No" in any case that the yes regex does not match, then why have the no regex declared at all?

This also applies to the "USB device" and "csv data" of their respecting functions, you are not actually checking those values yet have them declared still.

I stress this because in my opinion, you should prevent unexpected inputs from returning a value for which you are expecting a specific input for. Instead the code should throw an exception or a value which then you can manage elsewhere to notify that an unexpected input has been fed to the function.

In regards to tiding up your code, there are some options you can use but the one that suits your needs is the following one:

Dictionaris

Although you may already know, a dictionary is a class that returns a value if the key supplied exists in said dictionary, with it your regex declarations would look like in the following:

private Dictionary<Regex, string> formatDictionary = new Dictionary<Regex, string>()
{
    {new Regex(".bmp.8...."),"bmp(8-bit)"},
    {new Regex(".bmp.24...."),"bmp(24-bit)"},
    {new Regex(".png.24...."),"png(24-bit)"},
    {new Regex("raw"),"Raw"},
    {new Regex("....setup"),"Trace & setup"},
    {new Regex(".csvd...."),"csv data"},
}

private Dictionary<Regex, string> inversionDictionary = new Dictionary<Regex, string>()
{
    {new Regex("y.s"),"Yes"},
    {new Regex("n."),"No"}
}

private Dictionary<Regex, string> storageDictionary = new Dictionary<Regex, string>()
{
    {new Regex(".nte..."),"Internal"},
    {new Regex("e.ase"),"Erase"},
    {new Regex("t.ansf."),"Transfer"},
    {new Regex("usbdev."),"USB Device"}
}

This way, with a LINQ query, you can check the validity of the input:

if (!storageDictionary.Any(x => x.Key.IsMatch(input)))
    throw new Exception("the input is not valid");

This way you can ensure that the input matches at least one of the Regex you defined, now you can recover the corresponding value:

return storageDictionary[storageDictionary.Where(x => x.Key.IsMatch(input)).First().Key];

Your functions would end up looking like this:

private string CheckInvertColor(string input)
{
    if (!storageDictionary.Any(x => x.Key.IsMatch(input)))
        throw new Exception("the input is not valid");

    return storageDictionary[storageDictionary.Where(x => x.Key.IsMatch(input)).First().Key];
}


Loading, parsing, and displaying a JSON file

handleFileSelect is an Impure Function
handleFileSelect has in your code snippet a dependence to fr which is decleraded outside of the function. To make the function pure you can pass fr as argument.
// impure..
function handleFileSelect (evt) {
    fr.readAsText(evt.target.files[0])
}

// pure
function handleFileSelect (fr, evt) {
    fr.readAsText(evt.target.files[0])
}

Put Side Effects Into a Wrapper

A pure function returns for the same input always the same output.

The function writeInfo contains side effects because we access the DOM. We could wrap the DOM functions in to a wrapper called IO which will always return a function - always the same function.

const IO = x => ({
    map: (fn) => IO(x(fn)),
    run: () => x()
})

// more about compose and the benefits on
// https://medium.com/javascript-scene/composing-software-an-introduction-27b72500d6ea
const compose = (f, g) => x => f(g(x))

const getElementById = id => IO(() => document.getElementById(id))
const writeInnerHTML = value => element => IO(() => element.run().innerHTML = value)

const selectAndWrite = value => compose(
  writeInnerHTML(value),
  getElementById
)

const writeInfo = data => IO(() => {
  selectAndWrite('Traveler: ' + data.traveler_num)('traveler_num').run()
  selectAndWrite('First Name: ' + data.first_name)('first_name').run()
})

// ONLY this call is impure
writeInfo({
  traveler_num: 500,
  first_name: 'Steven'
}).run()

Either You Can Parse to a JSON or Not..
In the following I want to introduce a functor calles Either which is split into to functors Left and Right. If we can parse a string succesfully we will return a Right with the parsed value otherwise we will return Left with an error message.

const Left = x => ({
  map: (fn) => Left(x),
  get: () => x
})

const Right = x => ({
  map: (fn) => Right(fn(x)),
  get: () => x
})

const tryFunction = (errorMessage, fn) => x => {
  try {
    return Right(fn(x))
  } catch (error) {
    return Left(errorMessage)
  }
}

const parseToJson = tryFunction('Can\'t pase to JSON', JSON.parse)

console.log('should be {"name": "Random Name"}:', parseToJson('{"name": "Random Name"}').get())
console.log('should be "Can\'t pase to JSON":', parseToJson('{name: Random Name}').get())

References
The free online book mostly-adequate-guide is very good
The series composing-software is a good way to start


Extracting key and array value from javascript object?

A more concise approach would be to use Object.entries to get the 0th key and value at once:

const [stageName, stageValues] = Object.entries(sleepStage)[0];

Yes, the [0] looks weird, but unless you know the keys and/or in advance, you have to use a method which iterates over them, and then you need to extract the first item. In Javascript, there's no good way of avoiding the [0] - there's nothing like Object.prototype.getFirstEntry.

You could nest the destructuring on the left side, but that looks much less readable IMO:

const [[stageName, stageValues]] = Object.entries(sleepStage);

Ideally, in this sort of situation, you would fix the input data so that the keys are predictable and static:

const sleepStages = [
  { name: 'deep', values: Array(40) },
  { name: 'light', values: Array(40) },
  { name: 'rem', values: Array(40) },
  { name: 'awake', values: Array(40) },
]

Then, in the loop, you could do:

const { name, values } = sleepStage;


Creates a series of folders from a given starting date

OK let's look at your code.
Unused Imports
pathlib was imported but I don't see any use of it in the codebase, I understand that this might be as a result of testing out approaches to a problem. pylint can help mitigate this by catching unused modules. It also catches some PEP guidelines which your code breaks.
Avoid Globals
You have lots of global variables. A common approach whenever you want to use a global is asking yourself some questions; "How do I express myself with code whilst avoiding this global variable". When in doubt,  prefer objects that holds state to global variables.
Code Review
On first glance,  I can see you are manually parsing dates. This doesn't look good, you introduce bugs when reinventing the wheel. Right now,  your code contains a bug,  it accepts invalid dates,  I can easily create a date like this
date = "12-03-202022"
The above code generates no error, this can be disastrous.
A common alternative is using python  datetime module. This simplify everything, we can move the dates by periods easily,  creating directories becomes quite easy.
NOTE: datetime  module checks for invalid dates.
A simple way of creating a date from a string is given as
from datetime  import datetime
date = datetime.strptime(start_date, "%d/%m/%y")

This simple line of code simplifies everything,  the full code can then be written as
"""Directory creating program"""

import os
from datetime import datetime, timedelta

def next_date(date, period):
    """Increase the date by timedelta
        date: datetime object
        period: timedelta to increase our date by
    """
    new_date = date + timedelta(days=period)
    return '/'.join((str(new_date.day), str(new_date.month), str(new_date.year))), new_date

def make_directories(home_dir, start_date, instances, period):
    """Create sub directories in the home_dir

        home_dir: base directory
        start_date: date to append to directories created
        instances: number of directories to create
        period: difference between two dates
    """
    date = datetime.strptime(start_date, "%d/%m/%y")

    for i in range(instances):
        start_date = start_date.replace('/', '-')
        dirpath = os.path.join(directory, start_date,'Documentation')
        try:
            os.makedirs(dirpath)
        except FileExistsError:
            print('Directory {} already exists'.format(dirpath))
        else:
            print('Directory {} created'.format(dirpath))

        start_date, date = next_date(date, period)

if __name__ == "__main__":
    directory = "/Users/myName/Box Sync/SAFAC/Budget Requests/2020-2021/Weekly/"
    make_directories(directory, '3/1/20', 10, 5)


DailyProgrammer 280 Easy: Counting on Fingers

Overall, your code is really good :) Good job.

The thing that bothers me is the inconsistent weird indentation, but that's probably because of copying and pasting.

The 2 verifying conditions do the same thing, you can put them together, which reduces maintenance in the long term, although for such a small project it's not really important.

if (((input[a] - '0') > (input[a + 1] - '0') && (a + 1) < oneHandLength) ||
    ((input[a + oneHandLength] - '0') < (input[(a + oneHandLength) + 1] - '0') && a + oneHandLength > oneHandLength + 1));

Depending on the architecture, int is not guaranteed to cover the entire range of std::size_t, so you should use that as a type instead of int to avoid overflowing. This is not a problem now because you only have 10 fingers, but if you decide to add more... :)

std::size_t oneHandLength = (input.length() / 2) - 1;
//'auto' would also be possible if you want to

Don't use integers as booleans. It is better to clearly state that you want to check if the integer is greater than 0 (or equal to 1 in this case):

if (input[b] - '0' == 1);

Although using parenthesis reduces confusion, I think you are using too many of them:

if ((input[b] - '0')){
    ^              ^

if(((input[a] - '0') > (input[a + 1] - '0')) && ((a + 1) < oneHandLength)){
   ^^              ^   ^                  ^^    ^^     ^                ^

You have inconsistent spacing, choose one and be consistent:

for(int a = 0; a <= oneHandLength; ++a){
int main () {
if ((input[b] - '0')){
if(isValid){

You aren't including a newline after the last output, which can be a "problem" when run in a shell:

$ ./hands
$ 0111011100 is valid: 37 $ (command here - on same line!)

Minor thing: You don't need to return 0;, so you can remove it if you want to.


I was the one who recommended vectorizing.  I think the first approach would be to convert your code to using 2D indexes.  I think this will make the vectorizing clearer:

for j in range(rows):
    for i in range(cols):
        i1 = i+1 if i<cols-1 else i-1
        i2 = i-1 if i>0 else i+1
        j1 = j+1 if j<rows-1 else j-1
        j2 = j-1 if j>0 else j+1

        w1 = U[j, i]
        w2 = U[j, i-1] if i > 0 else U[j, i]
        w3 = V[j, i]
        w4 = V[j-1, i] if j > 0 else V[j, i]

        p = parray[j, i]
        p1 = parray[j, i1]
        p2 = parray[j, i2]
        p3 = parray[j1, i]
        p4 = parray[j2, i]

        zarray[j, i] = (w1 + w2 + w3 + w4)*p - (w1*p1 + w2*p2 + w3*p3 + w4*p4)

So, if I am reading this code right, you are shifting some rows and columns around.  So the next step is to re-implement this by making copies of the arrays that follow the same patterns:

U1 = np.empty_like(U)
V1 = np.empty_like(V)
parray1 = np.empty_like(parray)
parray2 = np.empty_like(parray)
parray3 = np.empty_like(parray)
parray4 = np.empty_like(parray)

U1[:, 1:] = U[:, :-1]  # this is w2
V1[1:, :] = V[:-1, :]  # this is w4
U1[:, 0] = U[:, 0]
V1[0, :] = V[0, :]

parray1[:, :-1] = parray[:, 1:]  # this is the result of k1
parray2[:, 1:] = parray[:, :-1]  # this is the result of k2
parray3[:-1, :] = parray[1:, :]  # this is the result of k3
parray4[1:, :] = parray[:-1, :]  # this is the result of k4

parray1[:, -1] = parray[:, -2]
parray2[:, 0] = parray[:, 1]
parray3[-1, :] = parray[-2, :]
parray4[0, :] = parray[1, :]

zarray = (U+U1+V+V1)*parray - (U*parray1 + U1*parray2 + V*parray3 + V1*parray4)

You could also use np.hstack and np.vstack instead of slices:

U1 = np.hstack([U[:, :1], U[:, :-1]])
V1 = np.vstack([V[:1, :], V[:-1, :]])

parray1 = np.hstack([parray[:, 1:], parray[:, -2:-1]])
parray2 = np.hstack([parray[:, 1:2], parray[:, :-1]])
parray3 = np.vstack([parray[1:, :], parray[-2:-1, :]])
parray4 = np.vstack([parray[1:2, :], parray[:-1, :]])

zarray = (U+U1+V+V1)*parray - (U*parray1 + U1*parray2 + V*parray3 + V1*parray4)


Queuing e-mail notifications in a background thread

I would always advocate SingleOrDefault() over FirstOrDefault() if the
  intent of the query is to only expect 0..1 data objects returned.

And to explain further.....

My comments are mainly around the use of FirstOrDefault().  To me your code isn't wrong as such and the use of FirstOrDefault will produce what you are looking for.

However, there are two problems I see with it.

Intent

When I read FirstOrDefault() I read that to mean that there could potentially be multiple items (0..n) returned from a query.  So that means there is a business reason behind this decision and I would expect the rest of the application to be able to adhere and follow this decision without problems.

So in your case I read this line

context.Users.FirstOrDefault(u => u.Id == userId)

to mean something along the lines of

  There might potentially be more than one user in the database with an
  Id that matches the userId supplied.  However I'm only interested in
  the first one so I will ignore all other users.

Masking potential problems

Using FirstOrDefault() from past experience is typically used because developers don't want an exception to be thrown if the criteria constraint is violated i.e. they don't want to see a bug come through.

However this may also mean that an error occurs somewhere further down stream because of this.  You will then find yourself debugging errors that in fact relate to model data violations and might have nothing to do with the code you are debugging.

The problem should ideally be fixed at the point where the model data violations were made, rather than the rest of the application having to worry about it.

Summary

I would always advocate SingleOrDefault() over FirstOrDefault() if the intent of the query is to only expect 0..1 data objects returned.

So use what you expect the data state to be in.  Unless of course you want to handle bad data state yourself and then I would expect error handling to occur if this was violated.


Optimizing my solution for problem #23 - project Euler

I would like to optimize my solution.

Really? It's already pretty fast and there isn't much to gain, given that Java has some start up overhead. I'd save my power for later Eulers.
Set<Integer> abundantNumSet = new LinkedHashSet<Integer>();

Do you need "Linked"? I don't think so, so we've a tiny optimization.
    abundantNumSet.add(12);
    for (int i = 13; i < 28124; ++i) {
        if (isAbundant(i)) {
            abundantNumSet.add(i);
        }
    }

I really wouldn't do it. You're testing nearly 30k numbers, so is it worth to optimize the first 13? Moreover, the saved tests are the fastest.
You should use no magic constants like 12, 13, 28124. Define constants and give them proper names. This will help you to avoid unworthy optimizations. :D
    int total = 276; // sigma 23, since 24 = 12 * 2
    for (int i = 25; i < 28124; ++i) {

Another unworthy optimization, more magic numbers. What's worse, a repeated magic number. One day, in a big project you save a second by copying some numbers instead of defining constants. Another day, you change them all (it's easy, isn't it?). Yet another day, you'll be hunting a bug caused by having changed a completely unrelated number which by accident had the same value.
        boolean isRep = false;

The loop body is big enough for an own method. Then you can drop the variable, instead of spending time on naming it properly (isRep is not properly).
            // iterating through half of the numbers in the set is enough

This is a promise, you didn't keep. No problem, as this part takes much less time than the other, so speeding it twice helps nothing.
I'd go for a method like this (untested):
private boolean isSumOfTwoAbundants(int n) {
    for (int i : abundantNumSet) {
         if (i > n - i) {
             break;
         }
         if (abundantNumSet.contains(n - i)) {
             return true;
         }
    }
    return false;
}

When using things like this
    int end = (int) Math.sqrt(n);

be aware of how it get rounded. I always prefer Guava's
   IntMath.sqrt(int, RoundingMode)

as it's explicit about it.
    if (sum > n) {
        return true;
    }

    return false;

Do you really mean return sum > n?
I guess, isAbundant could be sped up by factorization:

Similarly to the Sieve of Eratosthenes, you can precompute one factor for all numbers up to 28124.
For every number n, you get one factor, which you can divide out and get another number and another factor etc., till you have the factorization of n.
Having all prime factors (with their exponents), you can trivially compute the number of divisors.

This would probably help a lot, however, your code is already more then fast enough. While I love optimizing, I did about nothing for this problem and it took one second only (yours is about 10 times faster, do I care?).
Summary
You can optimize, but now it's time to learn not to optimize. Otherwise you can get quickly lost in the root of all evil.


I would not return IStopwatch from Start/Stop/etc. This IStopwatch is not an immutable Value Object, like String for example: it would be easier to set expectations by having just this:

public interface IStopwatch
{
    bool IsRunning { get; }
    TimeSpan Elapsed { get; }
    void Start();
    void Stop();
    void Restart();
    void Reset();
}

SystemStopwatch would be a way shorter:

class SystemStopwatch : IStopwatch
{
    Stopwatch Stopwatch { get; } = new Stopwatch();
    public bool IsRunning => Stopwatch.IsRunning;
    public TimeSpan Elapsed => Stopwatch.Elapsed;
    public void Start() => Stopwatch.Start();
    public void Stop() => Stopwatch.Stop();
    public void Reset() => Stopwatch.Reset();
    public void Restart() => Stopwatch.Restart();
}

As for the MockStopwatch (sounds better than Debug one for me) – it could be a little bit shorter:

class MockStopwatch : IStopwatch
{
    public MockStopwatch(params TimeSpan[] intervals)
        : this(intervals.AsEnumerable())
    {
    }

    public MockStopwatch(IEnumerable<TimeSpan> intervals)
    {
        Interval = intervals
            .Prepend(TimeSpan.Zero)
            .ToList()
            .GetEnumerator();

        Reset();
    }

    IEnumerator<TimeSpan> Interval { get; }
    public bool IsRunning { get; private set; }
    public TimeSpan Elapsed =>
        !IsRunning
        ? Interval.Current
        : Interval.MoveNext()
            ? Interval.Current
            : throw new InvalidOperationException("You did not define enough timestamps.");

    public void Start() => IsRunning = true;
    public void Stop() => IsRunning = false;

    public void Restart()
    {
        Stop();
        Reset();
        Start();
    }

    public void Reset()
    {
        Interval.Reset();
        Interval.MoveNext();
    }
}

Where you might need to define Prepend (.net core LINQ has one already):

static class PrependAppend
{
    public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item) =>
        Enumerable.Concat(new[] { item }, source);

    public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T item) =>
        Enumerable.Concat(source, new[] { item });
}

Updated Elapsed

What do you say about this one? Looks cleaner for me.

    public TimeSpan Elapsed => IsRunning ? NextElapsed : SameElapsed;
    TimeSpan SameElapsed => Interval.Current;
    TimeSpan NextElapsed => Interval.MoveNext()
        ? Interval.Current
        : throw new InvalidOperationException("You did not define enough timestamps.");


Use of Exception to log execution stack trace

It seems like you're working harder than you need to. Instead of this:

public void warn(Exception cause, String message) {
    String output = message + "\n" + stackTrace(cause);
    log.warn(output);
}

I think you could do this, and no need for the stackTrace method:

public void warn(Exception cause, String message) {
    log.error(cause.getMessage() + " " + message, cause);
}

Moreover, notice how common libraries use a String as the first parameter of logging methods, and a Throwable as the second. I suggest to follow that example and reorder your parameters.


EXIT_SUCCESS and EXIT_FAILURE are defined by stdlib.h. I think you need not define them.

You can add the const qualifier to arguments of logging_function(). Those strings are not going to be modified.

You can call fprintf() twice, once with the strftime() output and then with input_string[] and avoid the strcat().


This function sorts an array and returns the unique items

Remove duplicates from the array using Array#filter
Sort the array using Array#sort

Code:

function uniques(arr) {
    // Remove the duplicate elements from the array
    return arr.filter(function (element, index, arr) {
        return arr.indexOf(element) === index;
    }).sort(function (a, b) {
        return a - b;
    });
}


@EOF commented that InterlockedCompareExchange (and its gcc counterpart, __sync_val_compare_and_swap) returns the initial value of the destination address. This allows to remove one memory load from the retry loop.

Here is the new version with this optimization:

__forceinline void atomic_float_add(volatile float* ptr, const float operand)
{
    assert(is_aligned(ptr, 4));

    volatile LONG* iptr = reinterpret_cast<volatile LONG*>(ptr);
    LONG expected = *iptr;

    while (true)
    {
        const float value = binary_cast<float>(expected);
        const LONG new_value = binary_cast<LONG>(value + operand);
        const LONG actual = InterlockedCompareExchange(iptr, new_value, expected);
        if (actual == expected)
            return;
        expected = actual;
    }
}

Here is the corresponding assembly:

?atomic_float_add@foundation@@YAXPECMM@Z PROC

    mov eax, DWORD PTR [rcx]
    mov r8, rcx
    mov DWORD PTR value$2[rsp], eax
    movss   xmm0, DWORD PTR value$2[rsp]
    addss   xmm0, xmm1
    movss   DWORD PTR new_value$1[rsp], xmm0
    mov edx, DWORD PTR new_value$1[rsp]
    lock cmpxchg DWORD PTR [rcx], edx
    je  SHORT $LN16@atomic_float_add
    npad    13

$LL3@atomic_float_add:
    mov DWORD PTR value$2[rsp], eax
    mov edx, eax
    movss   xmm0, DWORD PTR value$2[rsp]
    addss   xmm0, xmm1
    movss   DWORD PTR new_value$1[rsp], xmm0
    mov ecx, DWORD PTR new_value$1[rsp]
    lock cmpxchg DWORD PTR [r8], ecx
    cmp eax, edx
    jne SHORT $LL3@atomic_float_add

$LN16@atomic_float_add:
    ret 0

?atomic_float_add@foundation@@YAXPECMM@Z ENDP

Interestingly, the compiler decided to do one iteration before entering the loop. I'm not sure I understand the benefit of this...


Your code is simple and just works. For that reason, you can be happy and there is not much comment to give. However, being very picky just for the sake of learning, one could say various things.

print statements

You are using print without parenthesis. This is the one and only reason why your code wouldn't work on Python 3. Just to be future (well, actually Python 3 is not the future, it is the present) proof, you might as well add the 2 parenthesis.

String formatting

Instead of using the % format, you could use the format method. You'll find more information online. Also using named place holder makes things easier to read and avoid duplicated values.

You'd get something like :

template = '''\
{idx} {x} on the {y}
{idx} {x}
Take one down, pass it around
{prev} {x} on the {y}
'''

for n in range(n, 0, -1):
    print(template.format(idx=n, prev=n-1, x=x, y=y))

Error handling

You should probably check the number of arguments provided and tell the user if anything is wrong.

Variable names

Even though n is acceptable, x and y do not convey much information, a better name can probably be found.


Method to encode ordinary characters into html format

You can make the loop more efficient by using the StringBuilder and using the Aggregate extension:

return m2.Value.Aggregate(
    new StringBuilder(),
    (current, next) => current.Append($"&#{next};")
).ToString())

You don't need the new MatchEvaluator, just the m is OK:

textRegex.Replace(contents, m => ..

You can even compress it by removing all returns:

return textRegex.Replace(contents, m =>
    innerRegex.Replace(m.Groups["Text"].Value, m2 =>
        m2.Value.Aggregate(
            new StringBuilder(),
            (current, next) => current.Append($"&#{next};")
        ).ToString())
    );

Regex textRegex = ..
Regex innerRegex = ..

I'm not sure about these two variables if they are not recompiled each time the method is called. It might be better to put them outside the method and make them static.

One final thought. You could split this method into three so that you can create finer tests and reuse any of them.

This method assembles both helpers to encode html.

public string EncodeToHtml(string contents)
{
    return ReplaceHtmlText(contents, m => EncodeText(m.Groups["Text"].Value));
}

This method just allows you to replace the text:

public string ReplaceHtmlText(string text, MatchEvaluator m)
{
    return textRegex.Replace(text, m);
}

This method allows you to encode the text:

public string EncodeText(string text)
{
    return encodeRegex.Replace(text, m =>
        m.Value.Aggregate(
            new StringBuilder(),
            (current, next) => current.Append($"&#{next};")
        ).ToString());
}


Running arbitrary number of mongo queries in nodejs

I'm pretty sure Mongo has native Promise support, that in conjunction with async/await would really tidy this up

async getFieldsFromCollection (collection, socket) {
  try {
    const db = await MongoClient.connect(MAIN_DB);
    const c = db.collection(collection);
    const doc = await c.findOne({}, {});
    if (!doc) throw new Error('document is null');

    const alphaFields = Object.keys(doc).filter(k => /^[A-Z]/.test(doc[k]));
    const alphaFieldsValues = {};
    const subQueries = alphaFields.map(async (f) => {
      const docs = await c.distinct(f);
      alphaFieldsValues[f] = docs;
    });
    await Promise.all(subQueries);
    return socket.emit('getFieldsFromCollectionReply', {
      alphaFields,
      alphaFieldsValues
    });
  } catch (e) {
    return log(e);
  }
}


This function for populating the attributes of a class, using a DB model and REST API

GeoIPUtils being a utility of methods, with the CamsModel being more of an object? camsModel could then accept an instance of GeoIPUtils rather than assigning in the separate procedural logic below:

$geoUtils = new GeoIPUtils();
$loginIps = $this->camsModel->getLoginIpsFromLoginHistory($this->loginHistory);
$this->loginIpInformation = $geoUtils->getIPAddressInfo($loginIps);

CamsModel always benefit from a GeoIPUtils instance? If so could be in the constructor. If wish to keep CamsModel, GeoIPUtils responsibilities better separated, add more indirection with a separate object which uses instances of CamsModel and GeoIPUtils as needed. Refactor generateReport into a Report object which requires a CamsModel instance, a GeoIPUtils instance, and your current this state. Creating a new Report object would replace:

$this->camsModel->getLastIntTransactionsByUser($this->userId, 20);

with:

report.getTransactions();

or:

report.getTransactions(20);

If the CamsModel class changed, then your current this or class in the question code above wouldn't need to be modified. Suppose the new version of CamsModel did not have a getIDUrl method. Only Report would be concerned with the details of CamsModel. Your this would depend only upon whatever methods Report provides. GeoIPUtils and CamsModel are now divorced from your current this class.

Replace 20, 100000 and any other literals in code with meaningful constants.

report.getTransactions(USERID_LIMIT);

Writing unit tests would be done first before crafting the object or method code, except for empty placeholder stub classes and methods. Get known input, desired output or object state for the non-existent class or method. Write tests which require that output or object state.

unit tests begin with comparison for equality. Simple String or other literals of the desired output or values are compared with your new object's envisioned getter methods, if( report.getChargebackTotal() != 959.30) failTest("Charge back total invalid");. Once unit test is written, then at this point begin writing the actual code to produce that output.

Will rewrite this code repeatedly, adding new objects and methods, painfully deleting code just typed, but writing the unit tests first is well worth the effort. Add unit tests for unexpected input, boundary testing, very small, large, negative values. Use regular expressions to whitelist and reject all input before validating by blacklisting. Protect against buffer overflow, exceeding array boundaries, numeric and String types. Modify code to validate all input, all return values. Fail immediately whenever out of range or unexpected.


Rendering three types of events as HTML elements

The simplest refactor would be to simply pull out the common functionality, and pass in the array for each case, as well as a function used to create your div content from the current item in the loop.  Assuming dtInt is global:

function checkDtInt(arr, funcToCreateDiv) {
    if (dtInt in arr) {
        var arrEventsV1 = arr[dtInt];
        for (var v1 = 0; v1 < arrEventsV1.length; v1++) {
            var travelEvent = arrEventsV1[v1];
            $("#dateCupcake" + i).append(funcToCreateDiv(travelEvent));
        }
    }
 }

checkDtInt(calendarEventDict, function(item) {
   return "
" + item.DisplayName + "
"
});

checkDtInt(vacationEvents, function(item) {
   return "
" + item.PersonName + "
"
});

checkDtInt(travelEvents, function(item) {
   return "
" + item.TravelRequest.Person.LastName + ", " + item.TravelRequest.Person.FirstName.Substring(0, 1) + " visiting " + item.TravelRequest.TechnicalCentre.Name + "
 "
});


Like @wb9688 mentioned in the comments, the way you currently determine the winner is fine and working, but it does not scale very well. If you wanted to add two more possible moves (for example lizard and spock), your if..else tree will become very large and hard to maintain.

It would therefore be better to just save which move beats which other move (for example in a dictionary):

beats = {'paper': 'scissors',
         'rock': 'paper',
         'scissors': 'rock'}

Then you can just do:

computer_choice = getComp()
user_choice = getUser()

if user_choice == beats[computer_choice]:
    print "{} beats {}, you win!".format(user_choice, computer_choice)
elif computer_choice == beats[user_choice]:
    print "{} beats {}, computer wins!".format(computer_choice, user_choice)
else:
    print "Tie."

If you also want to add the verbs, just add a dictionary for that as well:

verb = {'rock': 'smashes',
        'paper': 'smothers',
        'scissors': 'slices'}

And then do:

if user_choice == beats[computer_choice]:
        print "{} {} {}, you win!".format(user_choice, verb[user_choice], computer_choice)
...

You can have a look at my answer to a similar question on how easy it is to extend this framework to more moves: Stone, Paper, Scissors in Python

Note that you would have to change the structure of verb to a nested dictionary, because "Paper disproves Spock" instead of "Paper smothers Spock".

Your function getUser should be modified, as well. Right now, you call it recursively in case the user enters an illegal move. However, you never return the result of that recursive call!

In python, using a while loop is usually preferred in this case, because Python does not do tail recursion and so will hit a maximum recursion depth at some point:

def getUser():
    while True:
        user_input = raw_input("Make a choice: {} ".format(beats.keys()))
        if user_input in beats:
            return user_input
        print "Invalid choice."

Note: In Python-3.x, use input instead of raw_input and print(x) instead of print x.

Finally, in your function getComp, you can just return the result right away. However, it needs to be modified to use the keys of beats, instead of integers:

import random

def getComp():
    return random.choice(beats.keys())


Ruby script that deletes servers from Red Hat Satellite

The params hash seems like a verbose way to write four variables.  You never use params as a whole.  Furthermore, params[:use_ssl] is completely unused.

Using XMLRPC::Client.new_from_uri(…) lets you specify the host, path, and protocol in just one variable.

Instead of opening ARGV[0] yourself, just use ARGF — it's even better, in that it can also read its input from STDIN.  Instead of using line as the block parameter name, use something descriptive like system_name.

system_ids = Array.new followed by many system_ids.push(…) calls would be better written using map, in my opinion.

def prompt_auth():
  …
end

user, pass = prompt_auth()
uri = 'http://tcecapm1r6cm01.ecap.cciio/rpc/api'

client = XMLRPC::Client.new_from_uri(uri)
session = client.call('auth.login', user, pass)

system_ids = ARGF.map do |system_name|
  system = client.call('system.getId', session, system_name)
  system[0]['id'] unless system.nil? || system.empty?
end.compact
client.call('system.deleteSystems', session, system_ids)


Breadth-first search in Java: competitive style

Correctness.

The parent of the source node is initially -1, and buildPath relies on that. However, if the source node belongs to a cycle, its parent will be eventually reassigned, breaking the contract. Now buildPath will misbehave.
Efficiency.

Since the algorithm assumes an unweighted graph, the distance array seems redundant. In the implementation only one value is used, only to hint buildPath on the size of the path array. Meanwhile, the distances are incremented likely \$O(V)\$ times, and surely more than P = pathLength times. Instead you can let buildPath to compute P, trading \$O(V)\$ increments for \$O(P)\$ path length computation.


How to properly add some new arguments in a subclass?

As @Peilonrayz said in the comments: You can just write

class CustomList(list):
    def __init__(self, *args, setitem_callback, **kwargs):
        self.setitem_callback = setitem_callback
        super().__init__(*args, **kwargs)

    def __setitem__(self, *args, **kwargs):
        super().__setitem__(*args, **kwargs)
        self.setitem_callback()

def callback():
    print('callback')

l = ['a', 'b', 'c']
custom_list = CustomList(l, setitem_callback=callback)
custom_list[1] = 'd' # prints 'callback'

as long as you're okay with slightly different behavior when the caller forgets to pass setitem_callback= at all. With your original code, you get a KeyError:

Traceback (most recent call last):
  File "test.py", line 16, in <module>
    custom_list = CustomList(l)
  File "test.py", line 3, in __init__
    self.setitem_callback = kwargs['setitem_callback']
KeyError: 'setitem_callback'

With a proper keyword argument, you get a TypeError with a more tailored message:

Traceback (most recent call last):
  File "test.py", line 16, in <module>
    custom_list = CustomList(l)
TypeError: __init__() missing 1 required keyword-only argument: 'setitem_callback'


Your code reads well and is easily understandable. On top of also finding that you might have too much constant (more on that in a little bit), I just have a few nitpicks:

whitespace in expressions is weird sometimes;
a docstring would help understanding the recursion involved in snowflake_edge;
you don't need the newline continuation (\) inside parenthesis, they already act as an implicit one;
you allow to parametrize write_as_title with a custom font but nothing similar is done with other kind of parameters.

On reducing the similarities between the two drawings
I would have put a call to costum_reset (costum? really?) at the beginning of both write_as_title and snowflake since both drawings need a clear state to begin with.
I would also put time.sleep(WRITING_SLEEPING_INTERVAL) at the end of write_as_title. Considering its value, it won't hurt anyone in an interactive session and is still needed in a program for people to be able to read the text.
This way, the main part would look like:
if __name__ == "__main__":
    turtle.setup(width=WIDTH, height=HEIGHT)
    turtle.hideturtle()
    turtle.tracer(0, 0)

    write_as_title(
        "Constant size, recursion depth increasing.", font=FONT)
    for deepness in range(MAX_DEPTH):
        snowflake(deepness, SIZE_WHEN_CONSTANT_DEPTH)
        time.sleep(DRAWING_SLEEPING_INTERVAL)

    write_as_title(
        "Constant recursion depth, size increasing.", font=FONT)
    for size in RANGE_OF_SIZES:
        snowflake(DEPTH_WHEN_CONSTANT_SIZE, size)

You can even make the two sensible parts two functions if you want to separate the concerns better.
On reducing the amount of constants
Of your 12 constants, a few are really constant, some are arbitrary fixed for the purpose of your application, and some could be tweaked to achieve a better (prettier?) result.
Maybe that allowing to change the latter group using the command line could be more intuitive to tweak the parameters of the display. I personally would keep the following constants:

WIDTH, HEIGHT = 800, 600
FONT = ("Arial", 25, "normal")
WRITING_SLEEPING_INTERVAL = 2.5
SIDES_OF_AN_EQUILATERAL_TRIANGLE = 3
EQUILATERAL_TRIANGLE_INTERNAL_ANGLE = 120
DRAWING_START_X = - 200
DRAWING_START_Y = 150

And use argparse to provide default values or custom ones from the command line for:

DRAWING_SLEEPING_INTERVAL
MAX_DEPTH
SIZE_WHEN_CONSTANT_DEPTH
DEPTH_WHEN_CONSTANT_SIZE
SIZES_LIMIT

Note the use of SIZES_LIMIT which will then create the range object RANGE_OF_SIZES.
All of these last "constants" are only used within the if __name__ == '__main__' so it's pretty easy to adapt.


Maximize the number of PyGame sprites, with collision detection

A quick suggestion. If you look at the implementation of spritecollide, you'll see that it iterates over all the sprites in the group to see if the rectangles overlap. This means that the loop:

for box in boxs:
    # ...
    touch = pygame.sprite.spritecollide(box, boxs, False)

takes time proportional to the square of the number of boxes.

What I would try instead would be to insert the boxes into a spatial index which can find intersections efficiently. For example, put them in an R-tree using the Rtree package, and then call the intersection method. Or put their centres in a kd-tree using scipy.spatial.KDTree and then call the query_pairs method, passing the size of the largest box as the search radius.

Responses to comments

There are ways to update spatial indexes as objects move (typically in games objects don't move very far in a frame, so updates tend to be local). But the simplest thing to do is to rebuild the spatial index each frame — this has cost \$\Theta(n\log n)\$ which is an improvement on the \$\Theta(n^2)\$ approach of comparing all pairs of objects.
Here's an example using scipy.spatial.KDTree. Using this data structure requires three steps. First, take your list of sprites and build a tree containing their centres:

from scipy.spatial import KDTree
tree = KDTree([sprite.rect.center for sprite in sprites])

Second, query the tree for candidate collisions, using an appropriate search distance (in this case the diameter of the largest sprite):

from math import hypot
distance = max(hypot(*sprite.rect.size) for sprite in sprites)
collisions = tree.query_pairs(distance)

Third, not all of the candidates are actually colliding (because we have only queried the distance between their centres), so check to see which ones are real:

for i, j in collisions:
    if sprite[i].rect.colliderect(sprite[j].rect):
        # handle collision between sprite[i] and sprite[j]


You asked for comments on coding style, so here goes:

It's Python style to use CapitalizedNames for classes and lower_case_names for functions, methods and variables.
Functions should have docstrings that describe their arguments and what they do.
Names starting with "get" are normally used for functions that return the value they get. Your function prints the content at the URL, so it would be better to call it something like print_url.
The value of 6 for the timeout argument to urlopen seems arbitrary. It would be better either to leave this out (the caller can always use socket.setdefaulttimeout if they need to set a timeout), or to allow the caller to pass it as a keyword argument.
You can pass the timeout argument as a keyword argument to avoid having to specify None for the data argument.
Having a default value for srcURL is pointless, especially since it's an invalid value! Omit this.
The return value is useless: it's -1 if the argument was an empty string, or 0 if it wasn't. If the caller needs to know this, they can look at the argument they are about to supply. (Or they can catch the ValueError that urlopen raises if passed an empty string.)
The Content object does not get closed if the readline function raises an error. You can ensure that it gets closed by using Python's try: ... finally: ... statement. (Or contextlib.closing if you prefer.)

Applying all of these improvements, plus the one suggested by Lev, yields this function:

def print_url(url, timeout=6):
    """
    Print the content at the URL `url` (but time out after `timeout` seconds).
    """
    content = urllib2.urlopen(url, timeout=timeout)
    try:
        for line in content:
            print line
    finally:
        content.close()


Refactoring conditions in text parsing method

As you probably suspected yourself,
this looks neither readable nor maintainable.

The method makes too many references to outside:
a dozen or so references in regCompare.*,
and a handful variables defined outside (isSearchTokenFound, isParserEngineStop, ...),
and a handful of other methods (keepRecordsNoKeywordPatternToSeekAfterTokenExists, keepRecordsKeywordToSeekAfterToken).

All this indicates that there is no good information hiding in your design.
Too many dependencies on external factors makes an implementation too complex and incomprehensible.
I'm afraid what you have here is effectively spaghetti code.

Fixing this is difficult. It's not unusual in software development that an approach turns into a complete mess and then you need to restart from scratch in a different direction. It can be very difficult to write a good readable parser.

Here are a few ideas to try to improve this code:

Eliminate anything unused: the hasFont variable is unused, and therefore the fontCurrentLine parameter too. Remove them.
Avoid unnecessary calls: if isFileHeader is true, then isFileFooter and isLinesToSkip won't have to be executed. It seems as if you're trying to declare all variables at the top for some reason. In general that's not a good practice. Try to declare and initialize variables right before they are really needed, no need to do far in advance.
Improve the names: hasRegexTokensToSkip sounds like a boolean, but it's actually a String
Early returns might help. The first couple of else-ifs look like guard statements. Sometimes, turning these into if + return might make the code somewhat easier to read by reducing the indent level of the last else block.

After you apply these simple transformations the code might look slightly better.
But in the end, you might be better starting over from scratch.


Encoding a list of frequencies as WAV audio

It is hard to tell without knowing how lst is structured, but here is what I can say from what you have shown:

It is safer and cleaner to open files with the with syntax, since it will safely close the file no matter what happens.
It is better to do imports at the top of a module, rather than in a function.
It is a convention to use ALL CAPS for module-level constants, which you appear to have several of here.  This makes it easier to keep track of what is module-level and what isn't.
You re-define certain constants every time through the loop.  It is clearer and faster to define them once outside the loop.
It is a convention to import numpy as np, rather than N.
This would be much easier using scipy.io.wavfile if you can.  I will assume for now that you can't, though.
Although wave has a link to the struct module, it is, as far as I can tell, undocumented.  Even if it was documented, it would be clearer to use the struct module directly.
You potentially re-use the same struct value many times.  It would probably be easier and quicker to define it once and re-use it.
Along similar lines, you write the same value multiple times.  Since it is just a bytes object, it would probably be easier and cleaner to just duplicate the value.  They are small enough that this shouldn't be a problem.
You use i for two different things in the same loop.  Don't do that.  You should use a more informative name for the first i.
You only use a small bit of the i variable.  You should probably strip that off at the beginning.
Rather than finding a particular value in i and then slicing to that, you can just use i.partition('(') to split it at the first '(', then take the first value returned using i.partition('(')[0].
You don't even want the key, you want the frame, or rather the frequency.
You create variables only to immediately re-name them, then never use the original name.  This doesn't have much effect on performance, but it is confusing.
I don't know what my_code produces, but I will assume for my improvement it is an iterable.  If it isn't, then just put the list() wrapper you have now back in.
Is Syntax.struc.num a numpy array?  If it is, then change freqs = np.array([Syntax.struc.num[key] if key else 0 for key in keys]) to freqs = Syntax.struc.num[keys].
If Syntax.struc.num is already numeric, then you can drop the freqs = freqs.astype(np.float).
If you define your frequencies in a numpy array at the beginning, you can also pre-calculate period and omega much faster in a single step rather than at every point in the loop.
Try to avoid "magic numbers", which are seemingly-arbitrary numbers in your code.  They should be named variables for clarity.
You never use duration or samples.
Numpy has a tobytes method that converts an array directly into binary.
You create ssignal, but then write signal instead.  If you can just write numbers, you don't need ssignal at all, right?
I think it would be easier to read in the future if you use the music.set* functions rather than setting everything in one big function.
Are you sure you want the max value to be 16384? 16 bit wave files can handle 32760.

So this is how I would structure your code, assuming you are not able or not willing to use scipy.

import struct
import wave

import numpy as np

import out

def compiler():
    print("Loaded out.py")
    print("Compiling...")
    lst = my_code(out.code)
    keys = (int(ilst.partition('(')[0]) for ilst in lst)
    freqs = np.array([Syntax.struc.num[key] if key else -1 for key in keys])
    freqs = freqs.astype(np.float)
    periods = FREQ/freqs
    omegas = np.pi * 2 / period
    periods = np.floor(periods)
    print("Compiled!")
    print("Linking...")

    print("Bytes len: {0} = {0} ".format(len(periods), BLEN*len(periods)))

    packed_value = np.zeros(100, dtype=np.int16).tobytes()

    maxamp = 2**14
    maxlen = 400
    nchan = 2
    sampwidth = 1
    nframes = 0

    with wave.open('out.wav', 'w') as music:
        music.setnchannels(nchan)
        music.setsampwidth(sampwidth)
        music.setframerate(FREQ)

        for period, omega in zip(periods, omegas):
            if period < 0:
                music.writeframes(packed_value)
                continue

            signal = maxamp * np.sin(np.arange(period)*omega).
            signal = np.resize(signal, maxlen)  # duplicate up to the correct length
            signal = signal.astype(np.int16).tobytes()  # transform to binary

            music.writeframes(signal)

print("Linked to out.wav!")


Yes, of course. (It's always possible to eliminate unstructured constructs by use of structured programming.) I recommend Kernighan & Plauger's The Elements of Programming Style for developing your own sense of structured programming.

Come on this journey with me!

Step 1: That confusing if at the top of the loop.

while (true) {
    const char c1 = *i;
    if( c1 != '*' )
    {
        i++;
        if( i != fileEnd )
            continue;
        break;
    }

c1 is never used again, so we can eliminate it. Then, breaking the loop means going to the end of the loop and setting a "don't do this loop again" flag; so let's make that flag; we'll call it done. Then continueing the loop means going to the end without setting that flag. So at this point we have

template<class It>
It skipMultilineComment(It it, It fileEnd)
{
    bool done = false;
    while (!done) {
        if (*it != '*') {
            ++it;
            done = (it == fileEnd);
        } else {
            // Found '*' character
        FoundAsterisk:
            ++it;
            if (it == fileEnd) break;
            if (*it == '*') {
                /* Found another '*' character; can be more: ****/
                goto FoundAsterisk;
            } else if (*it != '/') {
                ++it;
                if (it != fileEnd) continue;
                break;
            }
            // Finally, found the closing token, "*/"
            ++it;
            return it;
        }
    }
    logError( "fatal error C1071: unexpected end of file found in comment" );
    throw E_INVALIDARG;
}

Notice that I've cleaned up some whitespace style and renamed i (traditionally a name for an integer loop control variable) to it (traditionally a name for an iterator). I've also made the function a template so that I can get rid of that global-scope typedef at the top.

Okay, let's pull out the next break... or, no, let's skip down to that similar continue/break tangle at the bottom of the loop, and sort that out. Same transformation as before. I'll just show the loop, because nothing outside it has changed.

    while (!done) {
        if (*it != '*') {
            ++it;
            done = (it == fileEnd);
        } else {
            // Found '*' character
        FoundAsterisk:
            ++it;
            if (it == fileEnd) break;
            if (*it == '*') {
                /* Found another '*' character; can be more: ****/
                goto FoundAsterisk;
            } else if (*it == '/') {
                // Finally found the closing token, "*/"
                ++it;
                return it;
            } else {
                ++it;
                done = (it == fileEnd);
            }
        }
    }

Notice that I am also habitually untangling your if/else blocks. You don't want to have if (a == x) ... else if (a != y) ... else if (a == z) ... because that's just plain confusing. if/else chains should read like switch statements: one handler per interesting value. So here we have one handler for *it == '*', and one handler for *it == '/', and then one catch-all "else" handler.

Let's follow that guideline and refactor the outer if (*it != '*') as well.
Notice that once we do that, we don't need the comment // Found '*' character anymore, because it's obvious from the code itself. Getting to remove pointless comments is one of the most satisfying parts of the refactoring process!

    while (!done) {
        if (*it == '*') {
        FoundAsterisk:
            ++it;
            if (it == fileEnd) {
                done = true;
            } else if (*it == '*') {
                goto FoundAsterisk;
            } else if (*it == '/') {
                // Finally found the closing token, "*/"
                ++it;
                return it;
            } else {
                ++it;
                done = (it == fileEnd);
            }
        } else {
            ++it;
            done = (it == fileEnd);
        }
    }

Okay, let's tackle that goto. The fundamental algorithm here is, "While we're looking at a * character, increment it. But if we reach the end of the string, then stop." Normally we'd spell that as

while (it != fileEnd && *it == '*') { ++it; }

Let's see if we can shoehorn that line of code into our function in a natural way.

    while (!done) {
        if (*it == '*') {
            while (it != fileEnd && *it == '*') {
                ++it;
            }
            if (it == fileEnd) {
                done = true;
            } else if (*it == '/') {
                // Finally found the closing token, "*/"
                ++it;
                return it;
            } else {
                ++it;
                done = (it == fileEnd);
            }
        } else {
            ++it;
            done = (it == fileEnd);
        }
    }

Notice that every path to the bottom of the outer loop now ends with done = (it == fileEnd) (except in one case where we already know it == fileEnd and so we just set done = true). So basically we just keep going until it == fileEnd. That's our loop condition.

    while (it != fileEnd) {
        if (*it == '*') {
            while (it != fileEnd && *it == '*') {
                ++it;
            }
            if (it == fileEnd) {
            } else if (*it == '/') {
                // Finally found the closing token, "*/"
                ++it;
                return it;
            } else {
                ++it;
            }
        } else {
            ++it;
        }
    }

Okay, but, now we've got a loop within a loop. You know what? Maybe what we really want here is a simple state machine: Either we've just seen a *, or we haven't. If we have, and the next character is /, then we're done. Otherwise, keep going. That would code up like this:

template<class It>
It skipMultilineComment(It it, It fileEnd)
{
    for (bool seenStar = false; it != fileEnd; ++it) {
        if (*it == '/' && seenStar) {
            return it + 1;
        }
        seenStar = (*it == '*');
    }
    logError( "fatal error C1071: unexpected end of file found in comment" );
    throw E_INVALIDARG;
}

Yes. I like that better. But wait, we can do better than that! All we seem to be doing is looking for the string "*/" inside a longer string. That's string search, and there are library functions for that!

#include <string.h>

const char *skipMultilineComment(const char *it, const char *fileEnd)
{
    if (const char *p = memmem(it, fileEnd - it, "*/", 2)) {
        return p + 2;
    }
    logError( "fatal error C1071: unexpected end of file found in comment" );
    throw E_INVALIDARG;
}

or in C++17,

std::string_view skipMultilineComment(std::string_view text)
{
    size_t pos = text.find("*/");
    if (pos != text.npos) {
        return text.substr(pos + 2);
    }
    logError( "fatal error C1071: unexpected end of file found in comment" );
    throw E_INVALIDARG;
}


Simpler way of showing, hiding & disabling elements

Edit: now that you have shared your html I could make a better response ...     http://jsfiddle.net/EjBW7/2/

There is a lot of repeated code, you could write some functions to avoid repeating the code, the branches in the second block seem redundant. You could use jquery's ability to target multiple elements in one selector.

setCheckboxValue = function (selector, enable)
{
    return $(selector).attr('checked', enable);
}

$("#chReportData").click(function(){

 if($("#chReportData").is(':checked') ){
      console.log('#chReportData show');
     $("#reportDataOptions").show();
 } else {
     console.log('#chReportData hide');

     $("#ReportDataStatusOptions, #reportDataOptions").hide();
     setCheckboxValue('#chkReportPermission, #chReportDataStatus, #chReportDataCummulative, .allowedUpload, .allowedDelete', false);
 }
});

$("#chReportDataStatus,#chReportDataCummulative").click(function() {
  if ($("#chReportDataStatus").is(':checked') ) {
       console.log('#ReportDataStatusOptions show');
    $("#ReportDataStatusOptions").show();
 } else {
     console.log('#ReportDataStatusOptions hide');
    $("#ReportDataStatusOptions").hide();
    setCheckboxValue('.allowedUpload, .allowedDelete', false);
 }
});


To start with, this is not good:

COMPLETE("opted out"),
OPTED_OUT("complete");

Otherwise, this is pretty standard code. There are two things I'd note:

If desc is coming from the database, you may have a risk of NullPointerException if it comes as null once.
Instead of looping and searching, you can create a map from description to value once and use it each time. Since your set of values is so small, performance difference is probably minimal, so this is question of taste.


Overall I think you have all the major pieces there, but I would also taking your find module a step further and create a target if QScintilla is found. You can do this by adding the following:

if(QSCINTILLA_LIBRARY AND QSCINTILLA_INCLUDE_DIR)

  set(QSCINTILLA_LIBRARIES ${QSCINTILLA_LIBRARY})
  set(QSCINTILLA_INCLUDE_DIRS ${QSCINTILLA_INCLUDE_DIR})

  if(NOT TARGET QScintilla::QScintilla)
      add_library(QScintilla::QScintilla UNKNOWN IMPORTED)
      set_target_properties(QScintilla::QScintilla PROPERTIES
           IMPORTED_IMPLIB ${QSCINTILLA_LIBRARY}
           INTERFACE_INCLUDE_DIRECTORIES ${QSCINTILLA_INCLUDE_DIR})
  endif(NOT TARGET QScintilla::QSintilla)

endif(QSCINTILLA_LIBRARY AND QSCINTILLA_INCLUDE_DIR)

Now you can use the library like so: target_link_libraries(MyProject PUBLIC QScintilla::QScintilla). Feel free to change the imported target name.

One minor thing I would suggest (that you can see in the code above ^) it to have your if() conditions match inside the corresponding end() call. So if you have if(condition), the matching end() should also look like end(condition).

As for cross platform support it's difficult to say without trying it on multiple platforms. I'm not sure about your find_path call. The use of ${Qt5Core_INCLUDE_DIRS} should be portable enough but it's tough to say.

One other nuance with find modules that I personally find can be troublesome is that on windows, if the library is a shared library you need to find the path to the .lib file and the .dll since that binary file isn't necessarily on the user's environment path. This is more of a nice to have and something I do for all find modules I write, but I work mostly on windows anyway.


Rustacious way of checking if string ends with any suffix from a selection

You could use Iterator:any to write this in a succinct way:

fn string_ends_with_any(s: String, suffixes: Vec<&str>) -> bool {
    return suffixes.iter().any(|&suffix| s.ends_with(suffix));
}

Because this pattern returns true on first match of the predicate:

for suffix in &suffixes {
    if s.ends_with(suffix) {
        return true;
    }
}
false

Whether this is rustacious remains to be seen. I'm by no means an expert in Rust.


Encrypter - Double Vigenere Cipher in Python

List comprehension

m= input("Text:")
k= input("key - 4 or more char:")

#changes the letters to ascii value
mes= []
for x in m:
    mes.append(ord(x)-32)

key= []
for x in k:
    key.append(ord(x)-32)

This all can be shortened to two list comprehensions:

mes = [ord(x) - 32 for x in input("Text: ")]
key = # Exercise for the reader

Avoid globals in functions

    if(action == "2"):

action should be a parameter of the function.

temp forever

 temp=mes[x]

You name a variable temp and use it 8 lines... please give a sensible name to this important variable.

Super long formula

toapp = (x%(len(key)-1)) + (x/(len(key)-1)) + (key[x%(len(key)-1)]) + (x%3) +(x%5)+(x%53)+(x%7)

Please, put a comment near this huge formula.

Avoid so many assignments

result = cipher(mes,key)

for x in result:
    print(x,end="")

print("")

In python it is idiomatic to avoid extraneous variable assignements and explicit for loops are rarely really necessary, this all can be shortened to:

print(''.join(cipher(mes,key)))

Do not assign junk input

The last line should just be:

input("Enter to continue...")


let -> const
Use the Array methods (filter, every)
Use object destructuring
Use object short-hand
Use a method for the null check so you don't have to write it for every property

if (!error && response.statusCode == 200) {
  const data = JSON.parse(body);

  const filtered = data.articles
    .filter(({ title, publishedAt, urlToImage, description, url }) =>
      [title, publishedAt, urlToImage, description, url].every(
        prop => prop !== null
      )
    )
    .map(
      ({
        title,
        publishedAt: date,
        urlToImage: image,
        description,
        url: link
      }) => ({
        title,
        date,
        image,
        description,
        link
      })
    );

  res.render("index", { filtered });
}

Update: filtered first for lower memory consumption as by @FreezePhoenix suggestion.


Any potential pitfalls with this way of modifying an array?

There certainly are for the user! Your code is not really confirming deletion: The number gets removed even if you press No/Cancel. You need to actually check the return value of the confirm() call:

var confirmation = confirm('Are you sure you want to delete?'); // returns true/false

if(confirmation) {
  // user confirmed, so proceed with removing the item
}

I'd also recommend a more descriptive confirmation message; tell me what I'm about to delete at least. Otherwise, I can't really be sure.

And there are further pitfalls.

For one, you're using the user's input as an element ID. Now, firstly, you don't need an ID. It's not used for anything. Second, IDs are really meant to be unique, but I can add the same thing as many times as I want, and I'll just get a bunch of elements with the same ID (it won't break anything, because - as mentioned - the ID isn't used for anything, but it only makes the IDs more pointless). And third, the input isn't being checked, so the user can input whatever they want, and have it appended directly to the page.

For instance, if you input , you'll get an alert when you click to add it, because you've just added a script element to the page. It'll also add some complete nonsense HTML to the page, because a script tag has suddenly become the ID for a span element, and... well, nonsense. Even if you weren't using the user's input as ID, it'd still behave as described, because you're inserting the input string as-is in the span. If you want to insert as text, use jQuery's .text() to set it. Otherwise it'll be interpreted as HTML.

E.g. you can input the string  and things get very zen.

You can do all this with the JS console of course, but the point remains: Always, always validate and sanitize user input, and insert it in a safe manner.

Also, your arrayList variable is global, meaning anything and everything can modify it in any way (for instance, you can input  and your list will get reset when it should just add something). It can end up not even being an array. In that case, your code will fail, because you can't splice() something that's not an array. Even if it is still an array, it may have been sorted, emptied, or who knows what else, and splice() might remove the wrong thing - or nothing at all.

Really, the trouble here is that the array isn't doing anything useful. You add numbers to the HTML directly, and you remove them from the HTML directly. The array is just a weak, error-prone copy of what's on the page. And you have to manually keep them in sync.

It's much better to have a single source for your data, so there's only one place to keep track of things. In this case, I'd say that that source should be the HTML. If you need to get an array of inputs, you can just use jQuery to fetch all the input so far:

$("#outputBox span").map(function () { return $(this).text() }).toArray()

That line will go through each of the spans, get their text, and return an array with the stuff that's been added so far (provided you remove the extra space in the span, which shouldn't really be there anyway - see below)

Other stuff:

arrayList is not a great name for a variable. Yeah, it's an array, so it's list of some sort... but what's in it?. I'd simply call it numbers or inputs, since that's what it actually represents.
Use jQuery to build the elements to avoid the error-prone string-concatenation
If you're making a list in HTML, make an actual
 or
 list (I'd pick ul as it's an unordered list of user input), and make the individual numbers list items (
).
Doesn't <button type="button" seem redundant to you? Because it is. You only need the type="button" if you're using an <input> element. A <button> element is - by definition - already a button.
You don't need event.preventDefault(), since clicking a button has no default behavior that needs preventing.
Use the $(function () { ... }); shorthand instead of $(document).ready(function () { ... });

In the end, you can do it all like this

HTML

<input id="input" type="text">
<button id="addItem">Add</button>

JS

$(function () {
  // keep the input and output elements around for later
  var input  = $("#input");
  var output = $("#output").on("click", "li", function () {
    if( confirm("Are you sure you want to delete this item?") ) {
      $(this).remove();
    }
  });

  $("#addItem").on("click", function () {
    var value = input.val();
    if(/^\d+$/.test(value)) { // check that the string contains only digits
      output.append($("

").text(value));
      input.val("");
    } else {
      alert("Please enter only numbers");
    }
  });
});

Here's a demo


”check” function – OK to throw in destructor?

Ignoring the throwing out of the destructor (which is a bad idea).

My main problem is with usage:

check(a == 42) << a << " is not equal to 42!";

Here you present a trivial case. But not all error checking is trivial. I think a more realistic case (that will happen more often than you think);

Universe  a;
// .... STUFF
check(a.theMeaningLTUAE(42)) << a << " The truth not reached " << a.checkInvariants();

Here we have calls to functions that will need to be evaluated even if they are never used (specifically checkInvariants() may be expensive (or even the streaming of a)). If the check passes you are still obliged to call it here but its value are simply discarded. I would prefer that the function is never called if no error message is going to be produced.

What you really want is a short cut operator that prevents subsequent operations from happening. Note overloading && and || on a class does not yield short-cut operators.

Or alternatively any functions should be passed as callbacks to operator<< and only evaluated if there output is required.


(when-not (@visited-urls url)more than 1 consumers may be looking at the same unvisited url at this point. They will be crawling the same url which is unexpected but it doesn't seem to break anything.

I don't see any better way with clojure atom. Actually atom doesn't buy you anything here because all it does is to mutate a global state. I think java.util.concurrent.ConcurrentHashMap works better. visited-urls can be a map of URL to boolean representing if the URL has been visited. the condition should be .putIfAbsent(url, true) == null


What is the purpose of the Expression type? Why doesn't expressions just return all the possible results?

This might be useful in other situations (like printing all the possibilities), but I don't see a reason for it here. Basically, it's an unnecessary level of abstraction.

if n < 0L then
    isUgly -n
else
    n = 0L || n % 2L = 0L || n % 3L = 0L || n % 5L = 0L || n % 7L = 0L

You don't need the special case for negative numbers, % works for them too.


Computing average grades for students in a class

For conciseness in Python, the key is to think in terms of applying functions using map and list comprehensions, rather than thinking procedurally.  In this problem, it is very important to define a mean() function.  Once you do that, the calculations themselves are one-liners.

The main objection I had to your code was that you mangled the data structure by appending each student's average at the end of his grades.  Don't do that — student_means() should just return a fresh dict instead.

I've taken out the non-essential prompt for the number of assignments; you can easily put it back.

""" Simple student grade manager"""

from fileinput import input

def mean(list):
    return sum(map(float, list)) / len(list) \
      if len(list) > 0 else float('nan')

def import_student_grades(grades_file):
    """
    Given a filename, reads data into a dict whose keys are student names
    and whose values are grades (as strings).
    """
    line_words = [line.split() for line in input(grades_file)]
    return dict((words[0], words[1:]) for words in line_words)

def main():
    grades_file = raw_input('File name: ')
    student_grades = import_student_grades(grades_file)
    student_means = dict((k, mean(v)) for k, v in student_grades.iteritems())

    print 'class average: %0.2f' % mean(student_means.values())
    for name, grades in student_grades.iteritems():
        print 'name: %(name)s | grades: %(grades)s | average: %(avg)0.2f' % {
            'name': name,
            'grades': ' '.join(grades),
            'avg': student_means[name],
        }

if __name__ == '__main__':
    main()


Find out whether a given text contains any of the prohibited words

I may have missed something. But why don't you just use simple collections ?

// Naive implementation
class Text {
  public Text(String content, Set<String> blacklist) {
    this.words = new HashSet<>(Arrays.asList(content.split("\\s")));
    this.blacklist = blacklist;
  }

  public boolean isSafe() {
    for (String forbidden: this.blacklist) {
        if (this.words.contains(forbidden) ) {
            return false;
        }
    }
    return true;
  }
}


Python retry logic based on return code and output

Without getting into a code golf'esque "shortest possible way to write this function", I'll just note a few alternatives to your particular implementation, and you can consider if you think they're simpler or not.

if ret == 0 is equivalent to if not ret. While that's probably not more legible in the if statement, it might be if you named this variable, e.g. program_failed = not ret.

expected_out in output is just one thing someone might want to do to evaluate if the output was what they wanted (e.g., maybe instead they want to do a regex check). You may want to replace this with a totally freeform function, then just call that function and use its result; e.g., if ret == 0 and output_ok(output):

Building on both of these, it might be prettier to name the conditions:
status_ok = ret == 0
output_ok = check_output(output)
if status_ok and output_ok:  # ...

Due to the nature of the if statement, the else condition is superfluous. It'd be equivalent to write:
if condition:
    break

time.sleep(delay)

You return ret, output whether or not the program succeeds, which may be confusing. Since your function's purpose is to check the output of the program and retry if it fails, it seems odd to return "successfully" if the program fails those checks just because it's run out of retries. Consider raising an exception instead.
for _ in range(retry):
    # ...
    if condition:
        break
    # ...
else:
    raise ValueError("Failed to run program successfully, <some useful information about ret, output, etc.>")
return output  # Only output, since ``ret`` is guaranteed to be 0

Pycharm and potentially other Python stylers might get upset at you for having a named variable you don't use: i. Consider replacing with _:
for _ in range(retry):  # ...

I'm just going to assume the cmd check_output... is just a typo, since Python uses def.

Write a docstring!

Again, you might not think all of the above are improvements, just alternatives. If you did follow them all, you might end up with the following:
def check_output_and_retry(cmd, check_output: lambda out: True, delay=1, retry=3):
    """Runs command until it succeeds. Raises a ValueError if it can't get the program to succeed.

    Args:
        cmd (str): The command to run
        check_output (callable): A function that takes the output string and returns whether or not it's ok
        delay (int|float): The number of seconds to wait between attempts
        retry (int): The number of times to try running the command before failing

    Returns:
        str: The program output. The program return code is guaranteed to be 0.
    """
    for _ in range(retry):
        # Run the given command.
        ret, output = execute_cmd(cmd)
        status_ok = ret == 0
        output_ok = check_output(output)
        if status_ok and output_ok:
            break

        time.sleep(delay)
    else:
        raise ValueError(f"Program failed to execute within {retry} attempts (status: {ret}: {output}")

    # Return value will be cmd output, since the return code is guaranteed to always be 0
    return output


Implementing a generic DropDownList attribute and templating solution

Why not just do this?

public class PhoneNumberViewModel
{
    // ... normal properties and attributes
    [DropDownList("ContactTypes")]  // <-- This is the important one!
    public string ContactType { get; set; }

    public static IEnumerable<SelectListItem> ContactTypes
    {
        get { return new[] { "Home", "Work", "Mobile" }.ToSelectList(); }
    }
}

public static class ExtensionsForSelectListItem
{
    public static IEnumerable<SelectListItem> ToSelectList(this IEnumerable<string> items)
    {
        return items.Select(x => new SelectListItem { Value = x });
    }

    public static MvcHtmlString ContextualEditor(this HtmlHelper html, string expression)
    {

        var model = html.ViewData.Model;

        var propertyMetadata = ModelMetadata.FromStringExpression(expression, html.ViewData);

        switch (propertyMetadata.TemplateHint)
        {
            case TemplateHints.DropDownList:
                var items = (IEnumerable<SelectListItem>)model.GetType().GetProperty((string)propertyMetadata.AdditionalValues["Items"]).GetValue(model, null);
                return html.DropDownList(expression, items);
            default:
                return System.Web.Mvc.Html.EditorExtensions.Editor(html, expression);
        }
    }

}

I didn't test the code to get the items.  But I'm assuming that you had that part working.

I also authored my own HTML Helper Library if you want check out some other examples.

https://bitbucket.org/grcodemonkey/buildmvc


Brute force solution to Project Euler Problem #52

Before I begin: I solved this particular Project Euler problem in 10 seconds without even writing a program, because I had seen a Numberphile video on this concept and I had memorized the number. It's really just a mathematical problem!

Whenever you must do brute force, you have two primary goals:

Reduce the number of trials by eliminating some definitely incorrect cases. In this example, if N and N * 6 doesn't have the same number of digits, they cannot be the permutations of each other. In our case this won't be much useful, but if you did some maths, you would notice that you would only have to check numbers between 100000..~170000, 200000..~270000, because numbers outside those ranges don't satisfy the condition stated above. If we were asked to find a much larger solution, using this approach would have eliminated about 30% of the options right away.
Reduce the amount of effort you must give at each trial. In this case, if 2 * N isn't a permutation of N, you shouldn't check for 3 * N because you know that you aren't getting a solution.

Finally, if I were you, I wouldn't use string operations. You can convert each number into a sorted list of digits in it, and then check for list equality.

Combining all of the above, you could write something like this:

A = sorted list of digits in (current trial)
for i = 2 to 6 inclusive:
    B = sorted list of digits in (current trial times i)
    if A and B are different, fail
succeed! -- can only reach here if all former multiples are permutations


The only reasons I can think of that your code was deemed incorrect are that it doesn't consider 0 as a perfect square, and that you don't consider the possibility that B < A (although maybe the test defined B as being greater than or equal to A and this is not a negligence of you). As for the performance, here are some suggestions:

You don't need to check i * i <= B in the loop, because the termination condition of the for loop already required that i <= upperLimit, and with i being positive, there is no way that i*i > B if i <= sqrt(B).
Taking the above into account, it follows that once the loop reaches an i for which i * i >= A, there is no point in continuing the loop, because all future values of i will have squares that fall within the specified range.
Continuing this trail of thought, it turns out that the solution can simply be expressed as (int) (Math.floor(Math.sqrt(B)) - Math.ceil(Math.sqrt(Math.max(A, 0)))) + 1, provided B is non-negative and B >= A. This expression doesn't really do anything your code doesn't do except floating point arithmetics. I don't know if two calls to Math.sqrt() (which delegates to StrictMath.sqrt(), which is a native method) are faster than using integer arithmetics in a loop, but it's definitely more to the point, coding-wise.


Most of the code in this class just makes no sense and written only because it has been shown in some tutorial as an example for some other class.
In case of a database connection class, there is no use for the database credentials' getters. You never need a database host anywhere outside of the database class. Hence, getServername() method will never be used. Neither such class variables are actually needed as you only need them in the constructor. And of course,  there shouldn't be a setVal() method whic is way too localised to be a part of the database class.
From the above, it can be clearly seen that there is no useful functionality in this class, and for a reason: mysqli is already a class, and not the worst one.
In your case, it would be much, much better to learn how to use vanilla mysqli first.
OO usage of mysqli is simple. All you need to know is the main rule of the database interaction in PHP:
A database connection must be created strictly once!
Therefore, you have to create the mysqli object first, and then use this instance for all the database interactions in your script. The simplest code for this would take just three lines:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // enable error reportig
$conn= new mysqli($host, $user, $pass, $db, $port); // the actual connection
$conn->set_charset($charset); // set connection charset

After this, you can use the instance of mysqli class to run SQL queries OO style:
$sql = "CREATE TABLE example(
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        firstname VARCHAR(30) NOT NULL,
        lastname VARCHAR(30) NOT NULL,
        email VARCHAR(50),
        reg_date TIMESTAMP
        )";
$conn->query($sql);

And it would be the perfect example of using mysqli OO style.
Other OO usage  examples of mysqli can be found in this answer


How to refactor old browser detection JavaScript?

Remarks

It sure is an interesting, hackery approach. Taken into account that this code must be compatible with archaic browsers, I would say it's rather fine. Few remarks:

For readability while() with no body could be rewritten to do {...} while().
Fail safe v <= 9 to avoid potential infinite loop could be added, in case something would change regarding browsers' behavior.
Naming could be better: div could become element to abstract used tag from the purpose of this variable's existence, v could become less-cryptic version.
Variable undef is unnecessary, it's only use occurrence can be replaced with false.
Formatting issues.
Inconsistent indentation, bracket policy and quotation marks.
Unnecessary addition of level of indentation; below ifs can be combined:

if (ie)
{
    if (ie < 9)
        {

If you would use single quotation marks in your alert(), you would have to perform only one escaping, instead of two.
window.parent should be replaced with window.top since parent could be iframe as well.

Rewrite

(untested for positive cases)

var ieVersion = (function() {
  var element = document.createElement('span');
  var version = 3;

  do {
    element.innerHTML = '';
  }
  while (element.getElementsByTagName('span')[0] && version <= 9);

  return version > 4 ? version : false;
}());

if (ieVersion && ieVersion < 9) {
  alert('You are running an older version of Microsoft Internet Explorer:\r\nVersion ' + ie.toFixed(1) + ', which is NOT supported.\r\n\r\nPlease upgrade your web browser to its latest version, or if you\'re still using Windows XP, to Google Chrome, Mozilla Firefox, Apple Safari, or Opera, to view this website, properly.\r\n\r\nClick "OK" to read instructions on how to download and install a newer, more compatible, web browser.');
  window.top.location.href = '/libs/old_browser_detect/current/upgrade_browser.php';
}

Different approaches

Feature-detection

I think it would be best to achieve your goal by using regular feature-detection based method:

var ieVersion = (function getLegacyIEVersion() {
  if (!document.compatMode) { return 5; }
  if (!window.XMLHttpRequest) { return 6; }
  if (!document.querySelector) { return 7; }
  if (!document.addEventListener) { return 8; }
  //if (!window.atob) { return 9; }
  return false;
})();

var IEThreshold = 9;
if (ieVersion !== false && ieVersion < IEThreshold) {
  console.log('Legacy IE');
}
else {
  console.log('Not a legacy IE');
}
/* Demo console styling */
.as-console-wrapper { top: 0; }

Conditional compilation

Another way of achieving the same, would be to use conditional compilation to detect JS engine version. Change ieVersion() function from previous code to:

var ieVersion = /*@cc_on (function() {
  switch(@_jscript_version) {
    case 1.0: return 3; break;
    case 3.0: return 4; break;
    case 5.0:
    case 5.1: return 5; break;
    case 5.5: return 5.5; break;
    case 5.6: return 6; break;
    case 5.7: return 7; break;
    case 5.8: return 8; break;
    case 9: return 9; break;
    case 10: return 10; break;
  }
})() || @*/ false;

Note however, that this method uses @_jscript_version which returns version of JS engine of the browser itself, while in cases of running in compatibility mode it would be desirable to get an actually used engine version, instead. Also, minifiers would get rid of this code, since for browsers other than IE < 11 this is just a comment.


Whenever you find yourself writing code that feels the same, consider whether you can create a function to do it. For example consider using a function for padding to two digits.

Instead of turning newYear into a string so you can split it on digits, consider using the remainder operator (%). That is, var newYear = newDate.getFullYear() % 100;

Although (actually, because) javascript lets you play fast and loose with whether a variable is a string or a number or something else, it's worth avoiding switching between them where possible. It also has the slight advantage that it always gets the last two digits, even if the year had 3 or 5 digits in it. (Of course that won't be relevant for a very long time if it only prints the current date, but you shouldn't bank on that.)

I would be inclined to make this code slightly more general by allowing it to return rather than print out the formatted string, and allowing it to take a Date as a parameter rather than only using the current date. If you do want to print it, you can always do that with the output.

Of course that might actually be marginally longer, but I think that's worth it. Unless you're in a smallest number of characters competition, it is better to have readable, flexible code than short code if they conflict. Length is only a problem when there's too much there to keep in your head how it fits together.

Sticking strings together one bit at a time with + is an expensive thing to do. It's worth getting into the habit of using something like join As shown in jstudenski's code.


I'm going to preface this with "I didn't actually try this, and the code may not even compile.", but I think you can greatly simplify your code by utilizing the DataReader class instead of parsing everything "by hand".

I'm imagining your routine looking something like this.

using (var dataReader = new Windows.Storage.Streams.DataReader(input.InputStream))
{
    // use network order to read the packet
    dataReader.ByteOrder = Windows.Storage.Streams.ByteOrder.BigEndian;

    //load the 2 byte command and 2 byte payload size into the buffer
    await dataReader.LoadAsync(4);

    short command = dataReader.ReadUint16();
    short payloadSize = dataReader.ReadUint16();

    // now we know how big the payload is, and can load it in full into the buffer.
    await dataReader.LoadAsync(payloadSize);

    byte[] data;
    dataReader.ReadBytes(out data);

    // package the whole shebang into a struct
    var myStruct = new MyStruct(command, payloadSize, data);

    // raise packet received event.
    Invoke?.PacketReceived(this, new PacketReceivedEventArgs(myStruct);

}

There are a couple of benefits to this approach.

Relies on existing abstractions and framework code instead of rolling your own.
We've defined an actual data structure for your packets. Client code can use this higher level abstraction without knowing all the knitty gritty details of how the packet was passed over the network.
Removes the need for the "other" infinite loop on a separate thread that's reading your data. It can listen for the PacketReceived event and react to it and the explicitly passed packet instead. This should lower the risk of race conditions.

One last note, don't use an infinite loop to receive the packets either.
It's much nicer (and user less CPU) to use a System.Threading.Timer to do this kind of work. It has a 15ms resolution but, then again, so does Task.Delay. You're waiting longer than that resolution anyway.


Whenever you're splitting a list up into a number of chunks, it's worth looking into the partition function (and related functions).

A string is just a list of characters, and you just want to split it when the character changes, so (partition-by identity characters) should be much simpler than what you have above.  You can pair that with another partition to make sure you have no chunks of > 9 characters:

(defn rle-chunks [string]
  (->> string
       (partition-by identity)
       (mapcat #(partition-all 9 %))))

Actually performing the compression is then just a case of calling first & count on each of these chunks, then converting back to a string:

(defn rle [input]
  (->> input
       rle-chunks
       (map (juxt first count))
       (apply concat)
       (apply str)))


Function to check if a numbers sequence is increasing

Implementation

The current return statement has the form if(condition) return !condition; else return condition;. This can be simplified to return !condition, i.e. return !truthArray.includes(false);.
The current implementation uses \$O(n^2)\$ runtime and memory, even though it is possible with \$O(n)\$ runtime and \$O(1)\$ memory:

The while loop can be exchanged for an if condition, or dropped entirely if there are no expected undefined entries in the input array (in that case, also remove the superfluous num++) by changing the for loops condition to num < numArr.length - 1.
There is no need to push every partial result into an array: If there is a mismatch, just return false. If there is no mismatch (i.e. you reach the end of the function), simply return true.

The current implementation returns false for input 1, 2, 2, 3. Is this intended?

Cleaned up code

/**Check if numbers sequence is increasing
* @param {number} numbers - a sequence of input numbers, must be valid floating point values;
* @return {boolean} - true if given sequence is increasing, false otherwise
*/
function isIncreasingSequence(numbers) {
  let numArr = Array.prototype.slice.call(arguments);

  for (var num = 0; num < numArr.length - 1; num++) {
      if (numArr[num] >= numArr[num + 1] || Number.isNaN(numArr[num]) || Number.isNaN(numArr[num + 1])) {
          return false;
      }
  }

  return true;
}

  The condition numArr[num] >= numArr[num + 1] || Number.isNaN(numArr[num]) || Number.isNaN(numArr[num + 1]) could be reduced to !(numArr[num] < numArr[num + 1]), but I chose the current condition because it makes the handling of NaN values more visible.

  NOTE: Arguments are not validated, call this function with non-Number arguments at your own risk!


Working Demo http://jsfiddle.net/jEjYp/2/

Rest feel free to play around with the code or demo.

Hope it fits your cause. :)

code

$(document).ready(function() {
    $('#qc1,#qc2,#qc3').hover(
        function () {
            $(this).find('.answer').slideDown('fast');
        },
        function () {
            $(this).find('.answer').slideUp('fast');
        }
    );

});


Producer - multiple consumer implementation using futures

I notice several things.

You have a data race on the shared queue. The consumer has an unsynchronized access to the nonEmpty property.

The notifyAll after you removed an element from the queue is unnecessary. Consumers shouldn't care about other consumers removing items.

But the main problem, which is suspect is the source of your deadlocks, is the race condition between the producer and the consumers. Here's what I think happens:

The producer produces the last item. It notifies all threads, releases the lock, but is preempted before setting the promise.
Consumer C1 wakes up, sees the queue is non-empty and grabs the element. It notifies all threads, releases the lock, and goes out to add the element to its list.
The other consumers wake up, see that the queue is empty but the promise is not set, and go back to sleep.
The producer sets the promise.
Consumer C1 sees that the promise is set and terminates.
The other consumers continue sleeping for all eternity.

To solve this, you need to notifyAll after you've set the promise. You can also probably optimize the whole thing by only calling notifyOne after adding an element.