Since @Imus has already pointed out the technical problems with your code, and how a depth-first approach is more reasonable, I'll just note on code style and give a few bits of advice.
Advice
If you expect balanced BSTs of height > 11 (more than 6500 nodes), to avoid stack overflow errors you can still use a DFS with an explicit Stack and while loop, like you do for your BFS - it'll even be less code.
Style
Note that here all my points can be seen in example in @Imus' answer.

Spaces around operators make expressions easier to read.

Consistent bracing style and indentation. I prefer the opening brace to be on the same line as the statement, with a space between the closing parenthesis and the opening brace. The closing brace should be on its own line.

Horrible variable names - one-letter names are reserved for loop indices, and then too not always. Variable names should be meaningful and convey the purpose of the variable. Use visitedNodes instead of q, processedContents instead of s, and currentNode instead of t. Doesn't it make it that much more understandable at first glance?

!visitedNodes.isEmpty() looks a bit better than q.size()>0 in your while loop.

My recommendation is to always use the block form instead of the statement form for if/else statements or for loops (use braces around even single-line bodies). This makes code addition later easier, and also contributes to readability.

Everything in points 1 to 3 can be done automatically by a proper IDE (you'll have to choose the good names, the IDE will suggest them to you after that so you don't need to type as much).


Structuring code logic for events on laravel controller

I'm mostly a back-end guy who fusses his way through front end code. Here's my advice:

Keep the controller code as close as possible to handling the response only. Delegate the creation of objects to their own classes. Think of the S in SOLID - Single Responsibility.
public function store(Request $request)
{
    $image = new ImageMeta($base64);
    $archiver = new ImageArchiver($image);
    $response = $archiver->post();

    if($response->getStatusCode() >= 500){
        return response($response->getBody(), $response->getStatusCode());
    }else{
        $drawing = Drawing::create([
            'user_id'=>Auth::id(),
            'file_name'=>$imageName,
        ]);
        //There's a few different ways to look at this which might be part of a larger conversation,
        // so I won't touch this part yet. But is this something specific to drawings? Or is the broadcast
        // of model creation something that will happen for lots of different models? Regardless, I would
        // change the name from NewDrawing to something like DrawingCreationBroadcast, or something like that
        // NewDrawing gets confusing since its too close to new Drawing();
        event(new NewDrawing($drawing));
        return response('Drawing created!',200);
    }
 }

ImageMeta class
    /** For all classes assume property declarations, and getters are included.
    * Lean toward immutable classes where possible, so don't include setters
    * unless it becomes necessary. Code re-use != object instance re-use.
    **/

    class ImageMeta {
        public function __construct($base64) {
            $this->image = str_replace('data:image/png;base64,', '', $base64);
            $this->imageName = 'draw'.time().'.png';
        }
    }

ImageArchiver class
    class ImageArchiver {
        private $config;

        public function __construct(ImageMeta $image) {
            $this->image = $image;
            $this->makeConfig();
        }

        private function makeConfig() {
            $this->config = [
                'multipart' => [
                    [
                        'name' => 'file',
                        'contents' => $image->getImage()
                    ],
                    [
                        'name' => 'file_name',
                        'contents' => $imageName->getName()
                    ],
                    [
                        'name' => 'file_folder',
                        'contents' => 'drawings'
                    ],
                ],
            ]
        }

        //use type hinting here. Off the top of my head I don't know the parent class of guzzleClient
        public function archive($guzzleClient) {
            return $guzzleClient->post($this->config);
        }

    }


Timestamp function with millisecond precision

You state that operating specific functions are out, which I assume means that you don't want to use operating system specific system functions. However in this particular case that is actually hindering you from actually solving your task, as POSIX-based systems and Windows-based systems has two different ways of handling this.

Although the ftime is present in various operating system, it has been marked as obsolete as of POSIX.1-2008:

  4.2BSD, POSIX.1-2001.  POSIX.1-2008 removes the specification of ftime().

  This function is obsolete.  Don't use it.  If the time in seconds
  suffices, time(2) can be used; gettimeofday(2) gives microseconds;
  clock_gettime(2) gives nanoseconds but is not as widely available.

Further is the gettimeofday() also obsolete as of POSIX.1-2008, leaving only the clock_gettime() alternative, which is not as widely available. Most notably not present in Windows, as indicated in "Porting clock_gettime to windows".

On Windows there are some other options, but seems that most fall back to using QueryPerformanceCounter & co (referred to as QPCs) as indicated in "Acquiring high-resolution time stamps". Some of my search findings also indicate that the QPCs are not be trusted in SMP (Symmetric MultiProcessing environments).

In other words, if you want to do this correctly for use in various operating systems, you do need to make it operating system dependent. If you choose to carry on with your solution using the obsolete ftime() more could surely be said, but here are some comments on your actual code:

Loose the append variable – You already have room in buf for the result, and know how much you've already used. I.e. replace it with something like either sprintf(&buf[8], ":%03u", start.millitm); or sprintf(buf + 8, ":%03u", start.millitm);1, and you can return without doing the strcat at the end.
Avoid busy loops – Your while loop is called a busy loop as it does nothing excepting counting. It is usually better to trigger a sleep function or similar, allowing the processor to do other work in between.
Strange reset of countdown – Instead of resetting the countdown in the for loop, it would be clearer code to reset it just before the while loop, or even better (if persisting to use the busy loop) to make it into a locally scoped for loop, i.e for (int countdown = 0; countdown < 1000000; countdown++) ;
Decide on one style of bracing – Decide whether you want to have opening braces on the start of the line, or end of preceding line, and stick to it. Mixing like you've done here make your code somewhat harder to read, and when mixing with empty block (aka the busy loop) with missing braces, it is not good.

Some guys advocate a different opening brace style for functions versus other blocks, but I would suggest using the same style for everything making it more consistent.

Addendum: C11 and xtime_get or rather timespec_get

Jerry Coffin refers to a xtime_get() with potential nanoseconds precision (albeit still dependent on operating system precision). This is part of the C++ boost library. It was proposed to be included in C11 (see N1548.pdf, 7.25.7, p 383. This was revised in N1570, 7.27.2.7, into a timespec_get() function. N1570 is the latest draft available, before the standard was defined (and made commercially available). From this I quote:

  3 If base is TIME_UTC, the tv_sec member is set to the number of seconds since an implementation defined epoch, truncated to a whole value and the tv_nsec member is set to the integral number of nanoseconds, rounded to the resolution of the system clock.321)
  ...
  321) Although a struct timespec object describes times with nanosecond resolution, the available resolution is system dependent and may even be greater than 1 second.

This does however seem to have made it into C11 (also known as ISO/IEC 9899:2011), according to the table of contents listed here, see section 7.27.2.5. So if your compiler and libraries is compliant to C112, you might use timespec_get() and possibly get a system dependent precision up to nanoseconds (or even greater than 1 second).

1 Thanks to 200_success for pointing out error in code related to buf[8] not being an acceptable target for sprintf()
2 For the gcc family this seems to be gcc ver 4.6 and glibc ver 2.16, or newer


Why is my Bubblesort implementation faster than my Quicksort code?

It is normal in production quality qsort code to switch to another sorting method (maybe a unrolled bubble sort) when the size of the input is small (often 8 is used).    QSort has very high overheads, but scales well, for a small input size the overheads are much more important than the scaling.

If you run your code on an input that is 1000 items long, then I expect that your qsort would be faster than your bubble sort.

Try writing a test problem that increases your input size in steps of 100 and then graph the results with both sorting methods.

The other way to look at it, is to find the largest input that each sort method can sort in say 5 seconds.

Also your qSort could be written to be a lot faster by not creating 3 new Lists, it is also very important to quickly choose a good item to privet on.   You do not even set the size of the list when you create them, hence each list will have to be reallocated and copied many times as you add items to it.

You have a qSort that is implemented is an inefficient way compared to a boubleSort that is close to the best implementation for boubleSort.

Yet as you confirmed in your comment the qSort does better when you have over 10000 items, slowing just how much better qSort scales.


Convert list/tuple of arguments into just arguments

You could use itertools.compress in combination with the tuple

def get_all_users(times=False, groups=False, ips=False):
    """Get a list of all users online"""
    arguments = ("clientlist", "times", "groups", "ips")
    selectors = (True, times, groups, ips)

    return ts3conn.exec_(*itertools.compress(arguments , selectors))

or in python 3.6+, using the retained insertion order of dicts (earlier versions can use an collections.ordereddict

def get_all_users(times=False, groups=False, ips=False):
    """Get a list of all users online"""
    arguments = {
        "clientlist": True,
        "times": times,
        "groups" : groups,
        "ips": ips,
    }
    return ts3conn.exec_(*(key for key, value in arguments.items() if value))


I'm bringing your code in line with C#3, which is about 8 years old, so hopefully can be used by your audience. By and large, it's making the class Listener static because it contains no state, using EventHandler<T> to create an event handler rather than using a custom delegate and using var to declare local variables with. I also added some vertical spacing so the code could breathe. The class 'RaiseArgs' is now immutable since the state should remain the same after creation. I like having classes sealed unless my design requires them not to be (it prevents them from being inherited). And lastly, I used a thread-safe access to the event by copying it to a local variable and comparing to null. And now the code:

using System;

// program that managers publisher and listener
public static class Program
{
    // subscribe to event, raise event
    public static void Main()
    {
        // new publisher
        var publisher = new Publisher();

        // subscribe to event
        Listener.Subscribe(publisher);

        // raise event
        publisher.RaiseEvent();
    }
}

// object with the event
public sealed class Publisher
{
    // declare event
    public event EventHandler<RaiseArgs> Event;

    // raise event, result: "hello"
    public void RaiseEvent()
    {
        var handler = Event;

        if (handler != null)
        {
            var args = new RaiseArgs("hello");

            handler(this, args);
        }
    }
}

// object that listens for the event
public static class Listener
{
    // subscribe to event
    public static void Subscribe(Publisher publisher)
    {
        publisher.Event += HeardEvent;
    }

    private static void HeardEvent(object sender, RaiseArgs e)
    {
        Console.WriteLine(e.Message);
    }
}

// the arguments to use with an event
public sealed class RaiseArgs : EventArgs
{
    private readonly string _Message;

    public RaiseArgs(string message)
    {
        _Message = message;
    }

    public string Message
    {
        get
        {
            return _Message;
        }
    }
}


Loads two columns from excel - cleans up the data - and makes a new list of unmatched values

Your code is actually pretty good!

But there are some small things I would change:

Don't use ws and ws2, instead just index them in the for loop. E.g. for col in wb['dirtyfile']['A'].
Rather than initalizeing j and incrementing it each loop you can instead use enumerate.
It's part of Python so it's well known, and improves clarity in your code.
This can change your cleansource loop to:

for j, i in enumerate(cleansource):
    cleansource[j] = str(i)

Rather than checking if an item is in another list, if it is do nothing otherwise add to another list.
Just check if the value is not in the list. E.g.

for i in dirtysource:
    if i not in cleansource:
        delta.append(i)

You also tagged this performance. And so there is one way you can improve the performance of this program.
Since cleansource is a list, if i in cleansource is a performance killer.
Instead you can use a set, this can allow you to perform if i in cleansource faster, as it's optimised to do so.
However I'd still keep your original cleansource, as sets are an unique unorganised collection of data.
Say you have the list ['a', 'b', 'c', 'd', 'a', 'b'] and you change it to a set you could get {'b', 'd', 'c', 'a'} back.
Either way you can change your code to the following for a performance increase:

clean_set = set(cleansource)
for i in dirtysource:
    if i not in clean_set:
        delta.append(i)


Some comments on naming and coding style.

First, it is a bit unusual for member function names to be in PascalCase in C++. camelCase or snake_case are more usual, reserving identifiers that start with an uppercase letter for type names.

char sign;
char Sign(char x) {sign=x;};
field.Sign(sign);

This isn't clear to me at all (could be a language issue though). What is this "sign" thing? Positive/negative? Does the Sign method do a cryptographic signature? What does Sign do to a sign?

I'd go with player, and rename TicTacToe::Sign to SetPlayer/SetCurrentPlayer to make it clear it's setting something.

Or get rid of that entirely and pass the current player's symbol to the methods that need it: there's only one. This lets the TicTacToe class to only manage the board, and leaves managing players to your future gameplay controller class ('cos stuffing all that in main isn't the best idea).

void MakeField();

The field is already "made", but not initialized. Something like InitializeField or ClearBoard would be sound more appropriate to me (though that's really minor).

void DrawField();           // good
bool IsFree(int y, int x);  // great

bool FindAndReplace(int x,int y);

This method doesn't find anything. It sets a cell to a value if it's free. And wait a sec, didn't we just see another method that takes coordinates?

bool IsFree        (int y, int x);  // oh?
bool FindAndReplace(int x, int y);  // what?

Why do you pass in the coordinates in different order? Please don't do that, it is very, very error prone. Stick to one order, and make that x, y consistently.

bool Row();
bool Column();
bool Diagonal();

These names don't tell me anything about what the functions do. I'd expect them to somehow return are row, column or diagonal, but bool doesn't work for any of this. Plus they operate on all rows, columns and diagonals (plural).

I'd rename all that to CheckRows() etc., and make them private - users aren't supposed to call these directly. Then fix the indentation, especially since you're not using {} in your ifs - your current layout is misleading.

bool Win();

IsGameWon()?

bool IsFull();

IsGameTied()?

TicTacToe(){MakeField();DrawField();}

The constructor initializes the field - that's good, but then it prints it immediately. This might not be what the caller wants, and the caller doesn't have a choice. I'd remove the DrawField() call, and add some whitespace.

TicTacToe() { MakeField(); }

Now in main, this should be in a separate function that does just that, i.e. get valid input from the player.

    std::cout << "Turn " << sign << ": Get x cordinate:";
    std::cin >> x;
    std::cout << "Get y cordinate:";
    std::cin >> y;
    if(x>2||y>2)
    {
        std::cout << "this coordinates does not exist! Try again\n";
        i--;
        continue;
    }

The i--; continue; is not very intuitive, and you're likely to get something wrong if you ever update the code and add something in between the top of the loop and the continue statement.

I personally don't like this form:

    if(field.FindAndReplace(x,y))
        field.DrawField();
    else
    {
        std::cout << "is full!";
        i--;
    }

I'd {} both sides, and only omit the braces only if both sides are single, simple statements. Most importantly be consistent - your Row, Col and Diagonal methods aren't (for the for).

As for spacing:

    sign=i%2==0?'o':'x';

This is unreadable for me (slightly better if I put my glasses on, but still hard to parse). More spaces, at least:

    sign = i%2==0 ? 'o' : 'x';

And I'd personally add a pair of parens and even more spaces, but I tend to like parens more than most I think.

    sign = (i % 2 == 0) ? 'o' : 'x';

Same applies for most of your assignments and comparisons, they could do with more spaces (and perhaps more parens), e.g.

if (!IsFree(0, i) && !IsFree(1, i) && !IsFree(2, i))
if ((m_field[0][i] == m_field[1][i]) && (m_field[0][i] == m_field[2][i]))
m_field[y][x] = sign;

Finally:

bool TicTacToe::Something()
    {
    }

but:

int main()
{
}

That's unusual. I'd stick to one style only - the class/struct name already informs the reader that it's a member function, so I see no reason for a different style between toplevel and member functions. (I'd pick the style you chose for main, less wasted horizontal space.)

A couple suggestions for the code itself.

This one is (I believe) non controversial:

bool TicTacToe::IsFree(int y, int x)
{
  // no need for an 'if', you have a boolean result already
  return m_field[y][x] == ' ';
}

This is a bit trickier but makes your row and column check a bit easier to read:

bool TicTacToe::CheckRows()
{
  for (int i = 0; i < 3; i++) {
    if (IsFree(i, 0)) // if the first cell is free, no need to look further
      continue;
    if ((m_field[i][0] == m_field[i][1]) && (m_field[i][0] == m_field[i][2]))
      return true; // and if it isn't the other two must match to win
  }
  return false;
}

This is a matter of taste - getting the "easy" cases out of the way as soon as possible generally results in less nesting depths for the main part of the function. (Here, not much gained.)

bool TicTacToe::SetIfFree(int x, int y)
{
  if (!IsFree(y, x))
    return false;

  m_field[y][x] = sign;
  return true;
}


Generating prime numbers within a range in C++

Stylistic notes:

Use more spaces around punctuation (for(int i=0;i<b;i++) wants to breeze), don't sprinkle your code with blank lines in random places, and use consistent indentation.
Declare your variables on separate lines; use the blank space on the right to write a comment explaining what the variable is for.
Use meaningful variable names. Come on, array? The reader can see that it's an array, but what does it contain?

Also, make up your mind: you're writing C++, not C. Some parts (such as the use of C arrays) are not idiomatic C++ though; you should pick one, either C (and use stdio, not iostream) or C++ (and use new and the STL). Since I'm a C programmer but don't know much C++, I'm going to comment on the C-ish parts and not say anything about idiomatic C++.

The array variable isn't useful here. The small primes will appear in the holder array anyway, so put them in directly. Even if you were handling small primes specially, your count variable is useless: you don't need to count how many small primes divide i, you only need to know whether some small prime divides i.

Also, you might as well use unsigned integers for your variables, since they're not going to contain negative numbers.

unsigned holders[1000000]; /* list of prime numbers */
unsigned length = 0;
holders[length++] = 2;
holders[length++] = 3;
holders[length++] = 5;
holders[length++] = 7;

You do not need to fully initialize holders, since you'll be only looking at the first length elements. While you could write unsigned holders[1000000] = {3, 5, 7}; and the compiler would fill the rest with zeroes, with typical implementations, this would result in the full array (zeroes included) being written into your executable, which is a huge waste.

You should be allocating the holders dynamically anyway, and checking its size. If someone passes such a large value for b that the holders array overflows, your code will overwrite some arbitrary memory. Either compute the size of the holders array so that it's large enough given b, or keep track of its size and extend it if length becomes too large.

Even numbers are never prime. So instead of looping over all integers, loop over all odd integers.

There's no reason to fill holders with non-prime numbers. Your whole first loop can be eliminated.

for (x = 11; x < b; x += 2) {
    bool is_prime = true;
    // start j at 1.
    // As holders[0] is 2 and no value of x is divisible by 2.
    for (j = 1; j < length && holders[j] <= sqrt(x); j++) {
        if (x % holders[j] == 0) {
            is_prime = false;
            break;
        }
    }
    if (is_prime) {
        holders[length++] = x;
    }
}

Now, to find the number of primes between a and b, traverse the holders array from the first value that's larger or equal to a. When you write a complete program, take care of the boundary conditions; in particular, make sure to count 2 if a ≤ 2.

for (j = 0; j < length; j++) {
     if (holders[j] >= a) break;
}
return length - j;


Find SuburbName from latlong or location

There are lots of nice things in your code for a beginner, congratulations.
Configuration file
Right now, you obfuscated your API key so that we don't have it, that's logical.
But it shouldn't be hardcoded in your code either. This is a bad practice for multiple reasons

What if I want to use your code? I'd be using you API key, this is danngerous. I should be able to set mine without having to recompile
Your API key would be stored in your source control (if you have one) and could be accessible to anyone decompiling your code. If there are costs related to Maps API, things could go wrong very quickly.

An API key should always be in some sort of configuration file. Either an app.config, web.config or some other external configuration manager.
Code repetition
Between the two overrides of GetSuburbName, there are parts of code that are duplicated. You did a good job of extracting FindSuburbName(GeoCodeResponse result) as a private method though.
I would go a little further. The only difference between the two methods is the parameters list so, as an example, I'd change :
if (!string.IsNullOrEmpty(location))
{
    using (var clientService = new HttpClientService<GeoCodeResponse>("https://maps.googleapis.com"))
    {
        var param = new Dictionary<string, string>();
        param.Add("address", location);
        param.Add("components", "country:AU");
        param.Add("result_type", "locality");
        param.Add("key", GoogleApiKey);
        var apiResult = clientService.GetAPI("maps/api/geocode/json", param);
        return FindSuburbName(apiResult);
    }
}
return string.Empty;

To :
if (!string.IsNullOrEmpty(location))
{
    var param = new Dictionary<string, string>();
    param.Add("address", location);
    param.Add("components", "country:AU");
    param.Add("result_type", "locality");
    param.Add("key", GoogleApiKey);

    return FindSuburbName(param);
}
return string.Empty;

Then, you could have your API call in the common method.
C# tips
You can use the Dictionary Initializer if you have a recent version of C#.
As an example :
var param = new Dictionary<string, string>();
param.Add("address", location);

becomes :
var param = new Dictionary<string, string>
{
    {"address", location},
    //etc
}

Regarding this line :
var component = addressObj.AddressComponents.Where(x => x.Types.Contains("locality")).FirstOrDefault();

There is an override for FirstOrDefaut that takes a Predicate (a condition), which means your code could be :
var component = addressObj.AddressComponents.FirstOrDefault(x => x.Types.Contains("locality"));

@FabienH. @FabianH. already pointed out the other points I wanted to cover regarding C#.


Reduce JavaScript code. Double event, selector into one

Give those #vtabs a class and it should be simple:

$(function() {
    $('.vtab > ul > li').mouseover(function() {
        var $this = $(this);

        $this.addClass('selected').siblings().removeClass('selected');
        $this.closest('.vtab').find('div').eq($this.index()).hide().siblings().show();
    }).each(function() {
        $(this).find('> ul > li').eq(1).mouseover();
    });
});

Although I'd try turning it into a plugin at this point.


PHP Class code that allow developers to register taxonomies in a CMS

I think you're mixing too many ideas here and as a consequence your class ends up having too many responsibilities, which than need extensive documentation because their behaviour may not be obvious and self explanatory.

Try to keep things just as simple as possible. In your case a simple plain old PHP object would potentially do the job.

Take for example the following entity class, which is basically the core of your code, all the rest of your functions are just creational util function.

class Taxonomy
{
    private $name;
    private $isHierarchical;

    public function __construct($name, $isHierarchical = false)
    {
        $this->name           = $name;
        $this->isHierarchical = $isHierarchical;
    }

    public function getName()
    {
        return $this->name;
    }

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

Because the code is that simple and self explanatory I don't even need to add any comment. Generally it's preferable to have clear and readable code over extensive documentation ...

That little extra bit of logic to have unique taxonomy names within an array of taxonomies could be archived by using for example a TaxonomyCollection object which takes care of that.

E.g.

class TaxonomyCollection
{
    private $taxonomies = [];

    public function __construct(array $taxonomies)
    {
        array_walk($taxonomies, function($taxonomy) {
            $this->addTaxonomy($taxonomy);
        });
    }

    public function addTaxonomy(Taxonomy $taxonomy)
    {
        if ($this->getTaxonomyByName($taxonomy->getName())) {
            throw new \RuntimeException(
                sprintf(
                    'Taxonomy name "%s" not unique within the collection.',
                    $taxonomy->getName()
                )
            );
        }

        array_push($this->taxonomies, $taxonomy);
    }

    public function getTaxonomies()
    {
        return $this->taxonomies;
    }

    public function getTaxonomyByName($taxonomyName)
    {
        foreach($this->taxonomies as $taxonomy) {
            if ($taxonomyName === $taxonomy->getName()) {
                return $taxonomy;
            }
        }
        return null;
    }
}

Example usage:

new TaxonomyCollection([
    new Taxonomy('foo', true),
    new Taxonomy('bar'),
]);

Now if you like to have a more convenient way for creating objects have a look on the factory pattern for example, but don't pollute your entities with endless boilerplate.


Well this is a fascinating question!

I don't see much you could do in createQueryString besides potentially using Object.entries instead of Object.keys and a slight rearrangement to get rid of the outer template string.

const createQueryString = input =>
  '?' + encodeURI(Object.entries(input)
    .map(([name, value]) => `${name}=${value}`).join('&'));

Do note that there is a problem here if your name or value contains &. To fix this you would need to call encodeURIComponent on each part and then drop the outer enocdeURI call.

const createQueryString = input =>
  '?' + Object.entries(input)
    .map(([name, value]) =>
      `${encodeURIComponent(name)}=${encodeURIComponent(value)}`
    ).join('&');

parseQueryString can be improved in several ways.

You don't use obj = Object.create(null), so get rid of it.
There is a (mostly) a built in way to do this which I will pretend doesn't exist for the rest of this post. (One disadvantage with this method is that it requires a full URI, not just the query string)

[...new URL(uri).searchParams.entries()]
    .reduce((obj, entry) => Object.assign(obj, { [entry[0]]: entry[1] }), {})

You can use regular expressions to simplify the code slightly.

const parseQueryString = (input) =>
  input.slice(input.indexOf('?') + 1)
  .match(/[\w\d%\-!.~'()\*]+=[\w\d%\-!.~'()\*]+/g)
  .map(s => s.split('=').map(decodeURIComponent))
  .reduce((obj, [key, value]) => Object.assign(obj, { [key]: value }), {})

Full demo:

const createQueryString = input =>
  '?' + Object.entries(input)
    .map(([name, value]) =>
      `${encodeURIComponent(name)}=${encodeURIComponent(value)}`
    ).join('&');

const queryString = createQueryString({
  name: 'Darrell',
  age: '3     2',
  nationality: 'Swedish',
  messy: '&hi=bye'
});

const parseQueryString = input =>
  input.slice(input.indexOf('?') + 1)
  .match(/[\w\d%\-!.~'()\*]+=[\w\d%\-!.~'()\*]+/g)
  .map(s => s.split('=').map(decodeURIComponent))
  .reduce((obj, [key, value]) => Object.assign(obj, { [key]: value }), {})

const parsedQueryString = parseQueryString(queryString);

console.log(parsedQueryString)


Application of higher-order function in Python

Nice docstring.

Your loop is too complicated, and not idiomatic Python.  Use range(n) to repeat n times:

def repeated(f, n):
    """Docstring here"""
    def g(x):
        for _ in range(n):
            x = f(x)
        return x
    return g

Your repeated() function works fine for functions that accept a single argument, like square(x) (which could just be written x * x, by the way).  However, it fails for higher-arity functions, such as

def fib_iter(a, b):
    return b, a + b

To handle multi-argument functions…

def repeated(f, n):
    """Docstring here"""
    def g(*x):
        for _ in range(n):
            x = f(*x) if isinstance(x, tuple) else f(x)
        return x
    return g

However, there is a bug in that: repeated(square, 0)(2) would return a tuple (2,) rather than an int 2.  To work around that special case…

def repeated(f, n):
    """Docstring here"""
    def g(*x):
        for _ in range(n):
            x = f(*x) if isinstance(x, tuple) else f(x)
        return x

    def unpack(*x):
        result = g(*x)
        if isinstance(result, tuple) and len(result) == 1:
            return result[0]
        else:
            return result

    return unpack


Function measuring time of another function

The big thing you're missing here is perfect forwarding. When you receive the argument pack, it may contain one or more rvalue references. But when you pass args... to the function you're timing, you've given a name to the pack, so even though what you received were rvalue references, what you end up passing to the timed function won't be an rvalue reference any more.
To fix this, you'd use std::forward:
function(std::forward<ArgsT>(args)...);

The other obvious addition I'd consider would be gathering and returning the return values from the calls you make. One possibility would be to return something like a pair<double, std::vector<output>>, to hold the time and the return values.


Concatenate two containers, e.g. vector or strings

Your current strategy will cause more reallocations than you need to, which is not efficient. You already have all of your vector parameters, so you simply need to get their size, and reserve that amount for the output vector.

template<typename V1, typename V2, typename... Rest>
std::size_t get_reserve_amount( V1 const& v1, V2 const& v2, Rest const&... rest ) noexcept
{
    using exp = int[];

    std::size_t size_sum{ v1.size() + v2.size() };
    (void)exp{ 0, ( ( size_sum += rest.size() ), void(), 0 )... };

    return size_sum;
}

Create an output vector, call reserve with the result from get_reserve_amount().
Use the same technique from above to insert elements into the vector.
We also remove the single element concatenate() overload.

Using those suggestions, we get rid of recursion completely in the concatenate function.

template<typename V1, typename V2, typename... Rest>
std::decay_t<V1> concatenate( V1&& v1, V2&& v2, Rest&&... rest )
{
    using exp = int[];

    std::decay_t<V1> v;
    v.reserve( get_reserve_amount( v1, v2, rest... ) );

    v.insert( v.cend(), v1.cbegin(), v1.cend() );
    v.insert( v.cend(), v2.cbegin(), v2.cend() );

    (void) exp
    { 0, ( ( v.insert( v.cend(), rest.cbegin(), rest.cend() ) ), void(), 0 )... };

    return v;
}

Usage remains the same.

Here's a couple of timing (in milliseconds) tests to show you how big of a difference this makes.

Before reserve: 1061, 1062, 1058

After reserve: 332, 331, 330

Here is my timing test code:

#include <iostream>
#include <vector>
#include <chrono>

template <class TimeUnit, class Clock, class F, class... FArgs>
TimeUnit measure( F&& f, FArgs&&... f_args )
{
    auto t0{ Clock::now() };
    std::forward<F>( f )( std::forward<FArgs>( f_args )... );
    return std::chrono::duration_cast<TimeUnit>( Clock::now() - t0 );
}

int main()
{
    std::vector<int> v0( 11'000, 1 );
    std::vector<int> v1( 33'000, 3 );
    std::vector<int> v2( 55'000, 5 );
    std::vector<int> v3( 77'000, 7 );
    std::vector<int> v4( 99'000, 9 );

    std::size_t loop_count{ 1'000 };

    auto test = [ &, lc = loop_count ]
    {
        std::vector<int> v;
        for ( std::size_t i{ 0 }; i != lc; ++i )
        {
            v = concatenate( v0, v1, v2, v3, v4 );
        }
    };

    using ms = std::chrono::milliseconds;
    using hrc = std::chrono::high_resolution_clock;

    std::cout << measure<ms, hrc>( test ).count() << '\n';
}

You can most likely optimize this further by using move operations when concatenating.

The expanding pattern is explained very well here:

https://stackoverflow.com/a/25683817/2296177


Accessing value from either os.environ or argparse

Using get on the os.getenv dictionary and specifying args.verbose as the default value (2nd param of the .get call) will have your desired outcome:

import os
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose",  action="store_true", dest="verbose")
    args = parser.parse_args()

    verbose = bool(os.environ.get('VERBOSE', args.verbose))

    print("Verbose:", verbose)

Test runs:

$ ./test.py -v; VERBOSE=1 ./test.py ; ./test.py
Verbose: True
Verbose: True
Verbose: False

Same output as your original.

Other notes:

The comment # Parse arguments. was pointless
Imports should appear on separate lines as per PEP8


I would write it as a mix of your two solutions. Checking if the set of the string has the same length as the string is probably the best way to check for an isogram.

On the other hand, the control structures in your first code are nicer, because there is less nesting and it does the same thing.

You should make sure you use a consistent number of spaces for indentation. You seem to be using 2, 4 and 6. PEP8, Python's official style-guide, recommends 4.

def is_isogram(word):
    if not isinstance(word, str):
        raise TypeError('Argument should be a string')
    if not word:
        isogram = False
    else:
        isogram = len(word) == len(set(word.lower()))
    return word, isogram

Does the specification say anything about if A and a should count as the same letter?


I agree with almaz - a blanket catch is bad juju in just about every case. Need to know what exception(s) wind up being there. If the column doesn't exist, there should be a better, non-exceptional way of doing that:

    private void HideExcludedColumns(UltraGridBase grid)
    {
        if (_scExclusions == null) return;
        foreach (var strKey in _scExclusions)
        {
            //Set the appropriate column of the grid to hidden.
            foreach (var band in grid.DisplayLayout.Bands)
            {
                var columnIndex = band.Columns.IndexOf(strKey);
                if (columnIndex > -1)
                {
                    band.Columns[columnIndex].Hidden = true;
                    break;
                }
            }
        }
    }


Raising error if method not overridden by sub-class

With multi-inheritance and super, raising NotImplementedError is an anti-pattern.

Breaking the DRY principle

When __init__ raise a exception all subclass must repeat the initialization instead of using the default.

class BadBaseMatrix():
    """Init raise NotImplementedError"""
    def __init__(self, text_version_of_matrix):
         """text_version_of_matrix represent some argument to initialize all matrix"""
         # ...
         raise NotImplementedError

class ComplexMatrix(BadBaseMatrix):
    def __init__(self, text_version_of_matrix):
        self.text_version_of_matrix = text_version_of_matrix
        # ...

class OtherMatrix(BadBaseMatrix):
    def __init__(self, text_version_of_matrix):
        # Must redo the initialization here
        self.text_version_of_matrix = text_version_of_matrix
        # ...

instead of something like this

class BetterBaseMatrix():
    def __init__(self, text_version_of_matrix):
         """text_version_of_matrix represent some argument to initialize all matrix"""
         self.text_version_of_matrix = text_version_of_matrix

class ComplexMatrix(BetterBaseMatrix):
    # ...

class PrintMatrix(BetterBaseMatrix):
    def __init__(self, text_version_of_matrix):
        super().__init__(text_version_of_matrix)
        # in python 2, this would be super(MyMatrix, self)
        print("PrintMatrix initialized")

Breaking inheritance

class MyMatrix(BadBaseMatrix):
     def__init__(self, text_version_of_matrix):
        # I will use his implementation because it must do some important initialization there.
        super().__init__(text_version_of_matrix)

>>> matrix = MyMatrix("")
# NotImplementedError

Do you really need a abstract base class

I feel that in Python, you do not need to prevent consumers of using your class a certain way. Maybe the base class could be used as a valid container. If so, returning a correct default (possibly None) would be enough for methods.

Here a similar version as your original of a plain matrix usable as a base class. But you should define each method to be able to add it's docstring.

class PlainMatrix():
    def _do_nothing(*args, **kwargs):
        """This docstring is used for all methods ..."""
        pass  #
    rotate = flip = _do_nothing

You really need a a abstract class

Use abc.ABCMeta.

import abc

class BaseMatrix(metaclass=abc.ABCMeta):
    # In python 2,
    # __metaclass__ = abc.ABCMeta

    def __init__(self, text_version_of_matrix):
         """text_version_of_matrix represent some argument to initialize all matrix"""
         self.text_version_of_matrix = text_version_of_matrix

    @abc.abstractmethod
    def rotate(self, degree):
         """ Abstract rotate that must be implemented in subclass"""
         pass

 class SubMatrix(BaseMatrix):

    def rotate(self, degree):
        """ True implementation of rotate"""
        # ...

 class StillAbstractMatrix(BaseMatrix):
     """ StillAbstractMatrix has not implemented rotate """
     pass

 >>> sub_matrix = SubMatrix("1 2 3")
 >>> bad = StillAbstractMatrix("1 2 3")
 # Traceback (most recent call last):
 #    File "<stdin>", line 1, in <module>
 # TypeError: Can't instantiate abstract class StillAbstractMatrix with abstract methods rotate


There's no particular ordering of characters' code-points in C (other than the digits 0..9).  This code assumes (for example) that '[' is less than '`', but that's not the case in EBCDIC at least.

I think you might be better off creating a table of boolean values, and indexing into that with the (unsigned value of) ch, in the way that standard <ctype.h> functions are normally implemented.  This will probably improve performance (one lookup, rather than up to 11 comparisons, per call).

Alternatively, and depending on what characters are considered "delimiters", you may be able to use standard library functions (e.g. isalnum()) in combination.


One can use Math.Round() to truncate a number by removing 0.5 / 10 ^ places and then rounding

e.g
     11.685 to 2 places

Math.Round(11.685 - 0.005, 2)

The following seems to do the job

public static class NumberExtensions {
    public static decimal TruncateDecimalPlaces(this decimal val, int places) {
        if (places < 0) {
            throw new ArgumentException("places");
        }
        return Math.Round(val - Convert.ToDecimal((0.5 / Math.Pow(10, places))), places);
    }
}

[TestMethod]
public void TruncateToPlaces() {

    Assert.AreEqual(10.665m, 10.6651M.TruncateDecimalPlaces( 3));
    Assert.AreEqual(10.665m, 10.6653M.TruncateDecimalPlaces( 3));
    Assert.AreEqual(10.665m, 10.6655M.TruncateDecimalPlaces( 3));
    Assert.AreEqual(10.665m, 10.6657M.TruncateDecimalPlaces( 3));
    Assert.AreEqual(10.665m, 10.665789M.TruncateDecimalPlaces( 3));
    Assert.AreEqual(10.665m, 10.66599999M.TruncateDecimalPlaces( 3));

    Assert.AreEqual(10m, 10.66599999M.TruncateDecimalPlaces( 0));
    Assert.AreEqual(10.6m, 10.66599999M.TruncateDecimalPlaces( 1));
    Assert.AreEqual(10.66m, 10.66599999M.TruncateDecimalPlaces( 2));
    Assert.AreEqual(10.665m, 10.66599999M.TruncateDecimalPlaces( 3));
    Assert.AreEqual(10.6659m, 10.66599999M.TruncateDecimalPlaces( 4));

}


First, there are some problems with your code:

You allocate memory for bool *visited but never free it again. Use delete[] visited when you don't need it anymore.
The condition in if(f<=rhs.f && f>=rhs.f) is true if and only if f == rhs.f. If that was what you wanted to check, then code it that way.
In line 26 you define the global variable i which is never used because it is hidden by the definition of a local i in main(), line 66.

These aside your code could be improved in the following ways:

Avoid mixing C and C++ programming styles

When choosing C++ and STL, go all the way. You already use std::vector for storing edges and nodes, so use one for visited. A vector does memory allocation and deallocation for you which is less error prone.
Use C++'s std::cout and std::cin instead of C's printf and scanf functions. See this answer for reasons why.
Stick to a set of rules for formatting your code. For example, you're inconsistent when it comes to spaces in variable definitions (see lines 26 and 27) and for statements (see lines 32 and 70) and when using {} brackets with single statement if and for scopes (see loops in lines 32 and 47).
Don't use global variables unless you have to. The definitions of node1 and node2 for example can be moved where they are needed, and myTime could be changed into a static variable of your dfsVisit function. To eleminate the other global definitions you can for example define them in main and pass them as needed by reference to dfs.
Move the definition of i inside the for statement where it is used. There is no need for it outside the fors scope.
Do bounds checking as early as possible. You know that M and N have to be between 0 and 100, so check them once you read them. Also do something when you detect an error, don't just silently ignore invalid node values.
Use node values starting by 1. Currently you read the value, decrease it by 1 and add 1 again to print it. Your program never relies on zero based node values.
Set node1.value once per rule by moving the statement one scope up because if never changes in the while loop at line 78.
When swapping the order of your dfsVisit and dfs functions you don't need the forward declaration of dfsVisit anymore.
Your nodes get copied alot. Each edge gets a copy of two nodes. You could instead use a std::map<int, node> for storing your nodes by value. An edge is then simply a pair of node values.
Consider an extra struct edge instead of using std::pair. Yes, it is extra code you don't necessarily need, but using edge.source and edge.target is more expressive than edge.first and edge.second which could be anything.
visited is a property of a node, so add bool node::visited and use this value instead of an external variable. Doesn't work unless you also implement #10, because the other edges' copies of the node don't get automagically updated when you set node.visited to true.

Consider an object oriented style instead of functional programming

If you encapsulate your algorithm in a class you can easily get rid of the global variables. Implement class methods for data input and validation and for the actual DFS. You could even split data management and DFS implementation into separate classes.


isspace

There are other characters besides for spaces. What happens if I do:

Hello<tab><tab>world!

Your code will report that there is one word. I would rewrite these:

if(*string==' '){
  //get previous character
  string--;
  // If previous character is not a space we increase the count
  // Otherwise we dont since we already counted a word
  if(*string!=' '){
    count++;
  }

You should instead use isspace for these kind of things. ' ' is for explicitly a space.

Indentation

Fix your indentation. Your main uses 4 spaces, your word_counter uses (maybe?) 2. Be sure that it is consistent. Choose one or the other.

Empty case rework

(Actually, as @200_success points out you don't need this corner case. I'm going to leave this up here though, because sometimes you will get cases like this and you should consider reworking them if they appear awkward)

Your empty corner case can be reworked:

  int count;
  if(*string!='\0'){
    count=1;
}
  else{
    count=0;
    return 0;
  }

First you don't need to set count = 0 if you just return immediately. I would restructure you if statement to be:

if (*string == '\0') {
    return 0;
}

And from there continue with:

int count = 1;

This means we don't leave count uninitialized either.


Selecting the number of working days minus weekend days and UK bank holidays

ISNULL, which you use a few times, is valid T-SQL, but there is an argument for using the more portable COALESCE instead. They're not straight aliases, though, so consider whether this is appropriate.
Comparing the two lines

,CONVERT(VARCHAR(10),singleended2.dbo.fn_WorkDays(cir.[Install Date], GETDATE()),103) AS NumberOfDaysSinceOrderDate
,CONVERT(VARCHAR(10), ISNULL(cir.[Install Date],'01/01/1900'),103) AS  OrderDate--Get the order dates

you assume in the second line that cir.[Install Date] might be null, but the first line passes it directly to a function which has no special-casing for that situation. Is this intentional?
I think you're overdoing things in

CONVERT(VARCHAR(10), ISNULL(cir.[Install Date],'01/01/1900'),103)

You're trying to convert the date to a dd/mm/yyyy string, but if it's NULL you take a string in that format, convert it with whatever the default date format happens to be (although since the day and month are the same you have good odds of getting the right result), and then convert it back. Why not push in the CONVERT and handle the fallback outside?
You're making assumptions about locale-related settings inside the function. It's understandable that you hard-code an assumption about which days are the weekends: you're only interested in one culture, so that's a business-level setting. But the localisation of the values returned by DATENAME is a per-connection setting. You might think that your function will always be executed in an English locale, and you might even be right, but it's a small change to replace DATENAME with DATEPART, and it makes the code slightly more robust.

(I've had experience of maintaining a system built for a British organisation but which relied implicitly on using a US locale; since my dev machine has a UK locale, lots of things broke. Don't discount the possibility that in future your code will be maintained by someone from another country who configures their dev machine differently - or even that the production machine might be moved to a server with a different locale).
For the benefit of future maintenance programmers, who may not be SQL-Server experts or domain experts on UK bank holidays, it would be nice to add some comments pointing out that DATEDIFF ignores @@DATEFIRST in order to be deterministic, and that a bank holiday will never be on a weekend.


Shorten code to perform search based on four slash-delimited parameters

Code Structure

It is quite tedious what you trying to do in the first piece of code. You might as well just pass the string array directly. As accessing an indexed element is not much different than variable named like paramx.
The second piece of code is mirrored from the middle. The lower section and upper section are essentially doing the same job with only 1 offset in parameter, and ViewType being different.
Never repeatedly make the same test, if possibly. Try to process by reduction and elimination, or change the flow of code.

Logic Flaws

When only one argument or two arguments (that begins with "Map" or  "Kort") are passed, then Area is being assigned instead of Country.

else if (!string.IsNullOrWhiteSpace(param1))
{
    SearchType = SearchStateType.Address;
    Area = param1.ToUnfriendlyUrl();
}

When 3 or 4(with Map/Kort) arguments are passed, SubArea is assigned before Area.

if (!string.IsNullOrWhiteSpace(param1) && !string.IsNullOrWhiteSpace(param2) && !string.IsNullOrWhiteSpace(param3))
{
    Country = param1.ToUnfriendlyUrl();
    Area = param3.ToUnfriendlyUrl();
    SearchType = SearchStateType.Address;
    SubArea = param2.ToUnfriendlyUrl();
}

Polished Code

SearchState = new RoomSearchState(parameters.Split('/'))

public RoomSearchState()
{
    SearchType = SearchStateType.Empty;
    ViewType = "Default";
}

public RoomSearchState(string[] args) : this()
{
    if (!args.Any()) return;

    if (args[0] == "Kort" || args[0] == "Map")
    {
        ViewType = "Map";
        args = args.Skip(1).ToArray();
    }

    switch(args.Length)
    {
        case 1:
            if (args[0].StartsWith("@"))
            {
                Country = args[0];
                SearchType = SearchStateType.Coordinates;
            }
            else
            {
                Country = args[0].ToUnfriendlyUrl();
                SearchType = SearchStateType.Address;
            }
            break;
        case 2:
            Country = args[0].ToUnfriendlyUrl();
            Area = args[1].ToUnfriendlyUrl();
            SearchType = SearchStateType.Address;
            break;
        case 3:
            Country = args[0].ToUnfriendlyUrl();
            Area = args[1].ToUnfriendlyUrl();
            SubArea = args[2].ToUnfriendlyUrl();
            SearchType = SearchStateType.Address;
            break;
        default: throw new ArgumentException("args");
    }
}


Dictionary<Y> is only efficient if you access the entries through the key. You are enumerating the dictionary with linq. This is very slow. Try to access it like this:

int count;
if (dic.TryGetValue(am, out count)) {
    // found
} else {
    // not found
}

You cannot search for keys that start with a text. If you want to do this then look for a more appropriate data structure. A binary tree inserts and looks up fast and sorting happens automatically. However, keep in mind that simple binary trees (not AVL trees) perform badly if items are added in a presorted order. A binary tree would also allow you to search for beginning of words.

EDIT:

I have thought things over. It would be possible to work with two collections at the same time. It is a bit complicated to handle, but should be faster.

Let me explain. We are using binary trees, because, unless dictionaries, they are ordered by the key. Let us store the information with the words as key and the frequencies as value in the first binary tree. In the second binary tree, we use the frequency as key. Because several words can have the same frequency, we use a list of words as value. With this approach, we have our information ordered by words and by frequencies at the same time.

Now let us update the frequency of a word, which is already contained in our collections. As an example, let us add 50 to the frequency of the word “TEDDY”:

We look up the word in collection 1. We see that the frequency of the word is 100.
We look up the words with frequency 100 in collection 2. We find two corresponding words, “TEDDY” and “HOUSE”.
We ignore “HOUSE” and remove “TEDDY” from collection 2.
We re-insert “TEDDY” in collection 2 with a frequency of 100 + 50 = 150. Because the frequency is used as key, it will probably be inserted at a different place in the tree structure.
We update the frequency in collection 1 to 150. Since the key does not change, we can just replace the value “in place”.

After these operations, both collections are still ordered by words and by frequencies respectively. Moreover, both look up operations, the remove and the insert operation were fast.


If I understood you correctly, you have a lot of methods which are identical to the one you've shown except for the parameters they take and the contents of the try-block. The rest is repeated code, which is bad.

To fix this I'd recommend to abstract the "repeat this action as long as Excel is busy" logic into its own method, which takes the action to be repeated as a parameter.

On a style note, I would argue against using Hungarian Notation. It's not really commonly used in .net and basically every style guide written in this century argues against it.

I'd also recommend making the bool variable positive (i.e. success instead of notSuccess). This way people don't have to perform double negation in their head when reading things like notSuccess = false (which would be changed to success = true).

With these suggestions the code could look like this:

private void TryUntilSuccess(Action action)
{
    bool success = false;
    while (!success)
    {
        try
        {
            action();
            success = true;
        }

        catch (System.Runtime.InteropServices.COMException e)
        {
            if ((e.ErrorCode & 0xFFFF) == 0xC472)
            {   // Excel is busy
                Thread.Sleep(500); // Wait, and...
                success = false;  // ...try again
            }
            else
            {   // Re-throw!
                throw e;
            }
        }
    }
}

You could then implement WriteDoubleValue and all the methods like it with a call to TryUntilSuccess like this:

TryUntilSuccess( () =>
{
    ((Excel.Range)sh.Cells[y,x]).set_Value(Missing.Value, lfval);
    ((Excel.Range)sh.Cells[y, x]).Font.Bold = bBold;
});


if($_GET['follow']){fun1();}

A more typical way to write this would be

if ( $_GET['follow'] ) {
  fun1();
}

As a general rule, do not put statements on the same line as the curly brace that opens the block.

$key = 'following';
$themeta = get_user_meta($user_id , $key, TRUE);

Since you never use $key again, you don't need it.

$following = get_user_meta($user_id, 'following', true);

If you're only getting the meta data for 'following', $following is probably a better name than $themeta.

if($themeta != '') {
$user_id= get_current_user_id;
update_user_meta($user_id, 'following', $fauid); }

else {

$user_id= get_current_user_id;
add_user_meta($user_id , 'following' , $fauid , true );
update_user_meta($user_id, 'following', $fauid);
}

Two of the three statements are in both branches of the if.  Therefore, you could pull them out:

$user_id= get_current_user_id;
if($themeta != '') {
} else {
  add_user_meta($user_id , 'following' , $fauid , true );
}
update_user_meta($user_id, 'following', $fauid);

Note that the order of the statements will stay the same with the add_user_meta in the middle.

But if you do that, one of the branches is empty.  You might as well remove it.

$user_id = get_current_user_id;
if ( '' == $themeta ) {
  add_user_meta($user_id , 'following' , $fauid , true );
}
update_user_meta($user_id, 'following', $fauid);

You also call

$user_id= get_current_user_id;

multiple times.  You should be able to do this just once.

The update_user_meta function will overwrite the value that you just added, so you might be better off with

if ( '' == $themeta ) {
  add_user_meta($user_id , 'following' , $fauid , true );
} else {
  update_user_meta($user_id, 'following', $fauid);
}

Now you add or update, not both.

This model only allows you to follow one author at a time.  A second author will replace the first.  It's more common to be able to follow as many as you want.  You might be able to manage with a serialized array, but a more robust solution would be a table that matched readers to authors.

$following = get_user_meta($user_id, 'following', true);
if ( ! is_array($following) || empty($following) ) {
  add_user_meta($user_id , 'following' , array($fauid) , true );
} else if ( ! in_array($fauid, $following) ) {
  $following[] = $fauid;
  update_user_meta($user_id, 'following', $following);
}

If there's no following array, it creates one.  If one already exists and doesn't already have this user ID in it, add to the existing array and update.

It's also worth noting that this is not the normal way to write for WordPress.  WordPress usually makes additions by adding plugins, and this doesn't look like a plugin to me.  For one thing, it doesn't register any hooks.  Nor does it define an install/activate procedure.


Your two print methods are odd in the sense that they are inconsistent with how you present them. A 'classic' matrix consists of primitive arrays (like int[][]), and not nested containers (like ArrayList<ArrayList<T>>). I can understand why you have one and also the other, but the mix of them is bizarre, ArrayList<T[]>. Remove the second print method.

Let's go through some other items first though. Let's narrow the ArrayList down to the interface level, just List. There is no reason to constrain the method to the concrete implementation because that severely restricts the applicability. I would actually go further and constrain it to Iterable. This produces the signature:

public static <T, R extends Iterable<T>, M extends Iterable<R>> void printMatrix(M matrix) {
    ....
}

What am I saying there? I am saying that the Matrix can consist of any combination of values that may have an Iterator. The mnemonics I use there are that:

T is the type of the cell data
R is the type of each row (which can be anything that is of type Iterable<T>)
M is the combined Matrix, which can be any Iterable of <R> (i.e. it's a collection of rows)

This is a generic method. You can throw pretty much anything at it from any collection structure.

An implementation of the method would look something like:

public static <T, R extends Iterable<T>, M extends Iterable<R>> void printMatrix(M matrix) {
    int size = -1;
    for (R row : matrix) {
        int s = 0;
        for (@SuppressWarnings("unused") T value : row) {
            s++;
        }
        if (size < 0) {
            size = s;
        } else if (size != s) {
            System.err.println("This is not a matrix.");
            return;
        }
    }

    StringBuilder sb = new StringBuilder();
    for (R row : matrix) {
        sb.setLength(0);
        for (T value : row) {
            sb.append(value).append('\t');
        }
        if (sb.length() > 0) {
            sb.setLength(sb.length()-1);
        }
        System.out.println(sb);
    }
}

and this could be used, for example, like:

public static void main(String[] args) {
    List<Collection<Object>> data = new ArrayList<>();
    data.add(System.getProperties().keySet());
    data.add(System.getProperties().values());
    printMatrix(data);
}

You should note a few things here:

The only reference to any concrete class here is the new ArrayList<>() in the main method. Everything else is treated at the lowest usable interface level (Collections, Lists, Iterables).
I use StringBuilder to build things 1 line at a time. This improves performance because each print is expensive, so you do fewer prints.
Java8 has a better way of counting the members, and also joining the Strings with the \t character:

for (R row : matrix) {
    long s = StreamSupport.stream(row.spliterator(), false).count();
    if (size < 0) {
        size = s;
    } else if (size != s) {
        System.err.println("This is not a matrix.");
        return;
    }
}

for (R row : matrix) {
    StringJoiner sj = new StringJoiner("\t");
    row.forEach(v -> sj.add(String.valueOf(v)));
    System.out.println(sj);
}

There is no need for the array-of-Integer to count the number of values in each line.
By putting the complexity of the generic types in the static method generics declaration area, the actual parameter has the simple type M.


Retrieve and cache web SPI results, then display on page

Closures in JavaScript

  I'd like some general JavaScript feedback but more specifically how to avoid globals. I understand they're evil in every language but do they seem to be unavoidable here?

You can easily avoid globals in JavaScript using closures.
I suggest to read more about the subject,
for example in this article by Douglas Crockford.

In fact you have already used the concept here:

function retrieveFromStore() {
    var data;
    window.store.get('data', function (d) { data = d.value; });
    return data;
}

The anonymous function in the call to store.get uses the data variable defined outside of the function, but within its closure.

As another example, and a simple solution to avoid window.store,
you could define all your functions within the outer $(function () { ... });, and then store will be visible to them, for example:

$(function () {
    var store = new Lawnchair(function () { });

    function storeData(data) {
        store.save({ key: 'data', value: data });
    }

    // ... other functions
});

Append directly instead of accumulating text

This function accumulates text in a variable before appending to the dom:

function drawData() {
    var data = retrieveFromStore();
    var text = '';
    for (var i = 0; i < data.length; i++) {
        text += '
' + data[i].Name + '
';
    }
    $('#results').append(text);
}

This is unnecessary,
you could append directly:

function drawData() {
    var data = retrieveFromStore();
    var results = $('#results');
    for (var i = 0; i < data.length; i++) {
        results.append('
' + data[i].Name + '
');
    }
}

Note that the reason for var results = $('#results'); is to avoid repeated dom lookups, which can be expensive.
It's a good practice to save repeatedly used dom lookups in variables.


Try not to repeat yourself and refactor common code to functions. Also you might want to create types (classes, structs, enums) to make things more expressive. Quick example with not so nice new data type (untested):

import UIKit

class ViewController: UIViewController {

    struct Operator {
        var stringRepresentation: String
        var `operator`: (Int, Int) -> Int //quotes required  as operator is a keyword
    }

    var operators = ["+":Operator(stringRepresentation:"+", operator:+),
                 "-":Operator(stringRepresentation:"-", operator:-),
                 "*":Operator(stringRepresentation:"*", operator:*),
                 "/":Operator(stringRepresentation:"/", operator:/)]
    @IBOutlet var buttonResponseLabel: UILabel!
    var userIsCurrentlyTyping: Bool = false
    var storedValue: Int = 0;
    var currentOperation: Operator?
    var currentNumberInLabel = ""
    var buttonTitle = ""

    @IBAction func buttonAppend(_ sender: UIButton) {
        buttonTitle = sender.currentTitle!

        if let chosenOperator = operators[buttonTitle] {
            currentOperation = chosenOperator
            storedValue = Int(currentNumberInLabel)!
            buttonResponseLabel.text = ""
        } else if buttonTitle == "=" {
            showResult()
        } else if userIsCurrentlyTyping {
            currentNumberInLabel = buttonResponseLabel.text! + buttonTitle
            buttonResponseLabel.text = currentNumberInLabel
        } else {
            userIsCurrentlyTyping = true
            buttonResponseLabel.text = buttonTitle
        }

        print("\(currentOperation) \(buttonTitle)")
    }

    func showResult() {
        print(currentNumberInLabel)
        guard let currentOperator = currentOperation else {
            print("This should never happen. Fail silently")
            return
        }
        operate(withOperator: currentOperator.operator)
    }

    func operate(withOperator op: (Int, Int) -> Int){
        let secondStoredValue = Int(currentNumberInLabel)!
        let finalValue = op(storedValue, secondStoredValue)
        buttonResponseLabel.text = String(finalValue)
    }
}

A very good walk-through Swift by implementing a calculator can be found here btw. It's from late 2015, so no Swift3. Maybe you find an update.


In general, the file input takes the most amount of processing time.

Your CRC algorithm may also be consuming a lot of the processing time.

Here are some suggested optimizations:

Don't clear the checksum.  The CRC will write to it anyway.  This is
a wasted function call.
The strlen function searches the string to determine length.  Use
std::string instead, because it maintains the length of the string
and can return the string length faster.
Don't read the entire file into memory.  Pick a chunk size and use
that.  A seek to the end of file may consume a lot of time.  If you
must get the file size, use an OS API that will return the size of
the file; hopefully it will be faster than seeking to the end of the
file.
If your OS supports memory mapped files, you may want want to use
this.  The memory mapped files allows the OS to handle reading the
file into memory.
Don't keep allocating from the heap.  Create a large array once and
use that.  Memory allocation may become a bottleneck when the memory
becomes fragmented.
Turn on compiler optimizations to highest level.
Try creating multiple threads for processing.  For example, you could
spawn two threads, the main program would pass different filenames to
the threads as they complete their processing.
Reduce the number of branches; branches may force instruction
pipeline reloading, which wastes time that could be spent processing
data.  Research "loop unrolling".
Optimize data to fit into the cache.  Reloading of the cache for
items outside the cache wastes time.
If you can, do whatever it takes to keep the hard drive spinning.
There is an overhead associated with starting up the hard drive
motors.  Keeping the drive spinning reduces the need to restart the
motors.  See also "double buffering".
Optimize the CRC by performing it in parallel, if possible.


Detecting when the contents of a web page changes

I can't really verify what the code does since when I checked, the filler is always 0px. But I assume your code checks for the surrounding elements in an interval and updates the filler height accordingly.

I have some tips for your code:

//shorthand .ready using the jQuery namespace
//and using the $ as the inner namespace
jQuery(function ($) {

    //cache repeatedly used references
    var content = $("#content"),
        footer = $("#footer"),
        $window = $(window),
        filler = $("#filler");

    // - place functions inside the ready handler to avoid globals
    // - always hand over a function reference to a timer and never an eval-able string
    // - since 500ms is fast enough, resize and an init wouldn't be needed
    //   a human sees 200ms as "instant" and at least 700ms a significant lag
    //   somewhere in between is the "sweet spot"
    setInterval(function () {
        var startPos = content.position(),
            topHeight = startPos.top,
            contentHeight = content.outerHeight(true),
            footerHeight = footer.outerHeight(true),
            viewportHeight = $window.height(),
            spaceForContent = viewportHeight - footerHeight - topHeight,
            //JS has a function scope. Any variable declared anywhere is visible
            //everywhere in the containing function. Therefore, it's better to
            //declare them outside operations
            newHeight = 0; //default to 0

        //overwrite 0 if conditions state otherwise
        if (spaceForContent > contentHeight) {
            newHeight = spaceForContent - contentHeight
        }

        //so it's 0 or some other value
        filler.css('height', newHeight);

    }, 500);
});

Packed version:

jQuery(function ($) {
    var content = $("#content"),
        footer = $("#footer"),
        $window = $(window),
        filler = $("#filler");
    setInterval(function () {
        var startPos = content.position(),
            topHeight = startPos.top,
            contentHeight = content.outerHeight(true),
            footerHeight = footer.outerHeight(true),
            viewportHeight = $window.height(),
            spaceForContent = viewportHeight - footerHeight - topHeight,
            newHeight = 0;
        if (spaceForContent > contentHeight) {
            newHeight = spaceForContent - contentHeight
        }
        filler.css('height', newHeight)
    }, 500)
});

You might want to check out Mutation Observers API which gives you the ability to listen to changes in the DOM. It's not yet supported across browsers but just included it if ever you are interested.

Also, I think it's better that you rethink your layout - one which only relies on plain HTML and CSS.


Kudos for figuring out the correct algorithm.

However you can streamline it by not using a v vector:

You correctly treated an operation a, b, k as a pair of operations: add k from a to the end, and subtract k from b+1 to the end. Now, instead of storing them in v, collect decoupled operations in a vector of their own. Sort it by index. std::partial_sum it, and find the maximum in the resulting array.

This will drive the space complexity down from \$O(n)\$ to \$O(m)\$, and change the time complexity from \$O(n+m)\$ to \$O(m\log m)\$. According to constraints, the time complexity seems to be better. One should also keep in mind that accesses to v could be all over the place with no particular order, and a well crafted sequence of operations may incur too many cache misses. I didn't profile though.
It is possible that spelling the loop out (rather than using for_each and lambda) would improve readability.
The algorithm would fail if k was allowed to be negative. Even it is not the case, it still is a good habit to initialize max and x to v[0], and start the loop at v.begin() + 1.


The standard indentation in Python is 4 spaces, as specified in PEP 8.  This is a pretty strong convention, since Python is very sensitive to indentation.

To process a file specified on the command line, use the fileinput module.  It supports multiple filenames, and it also falls back to reading standard input if there is no filename given.

Instead of for iplist in ipfile, I would say for line in ipfile — because it's not a list until you have split it.  It's also odd that you wrote the code to expect a "list", when in your question, you specified one IP address per line.

str.split(), with no separator specified, splits on whitespace and automatically discards whitespace from the results for you.

Calling check_ip() with the ip as a global variable is bad practice.  You should pass it as a parameter.  However, I wouldn't bother defining a function for it, especially since that function has a side-effect of printing its output.

The except Exception, e syntax is obsolescent.  Prefer writing except Exception as e.  (In this case, you don't need to name the exception at all.)

Since all of the color-changing codes should reset the color back to normal, I would define a function for that.

import fileinput
import socket

RED = '31'
BLUE = '34'

def color(color_code, text):
    return '\033[{}m{}\033[0m'.format(color_code, text)

for line in fileinput.input():
    for ip in line.split():
        try:
            socket.inet_aton(ip)
        except Exception as invalid_ip:
            print color(RED, 'Invalid IP address = ') + ip
        else:
            hostname = socket.getfqdn(ip)
            print color(BLUE, ip) + ' hostname is ' + color(BLUE, hostname)


Stack Exchange userscript for showing spoilers on questions with particular tags

For Loop

The style of the for loop you're using could be improved.

for (var jj = 0; jj < tags.length; jj++) {
    // If we don't find the tag in the array of spoiler-able tags,
    // then we have to reject the question.
    if (SHOW_ME_SPOILERS_IF_TAGGED.indexOf(tags[jj]) == -1) {
        return false;
    }
}

should probably be changed to a for of loop

for (tag of tags) {
    // If we don't find the tag in the array of spoiler-able tags,
    // then we have to reject the question.
    if (SHOW_ME_SPOILERS_IF_TAGGED.indexOf(tag) == -1) {
        return false;
    }
}

map

This code is essentially doing the same thing as a map function:

var tags = [];
for (var ii = 0; ii < hrefs.length; ii++) {
    tags.push(hrefs[ii].innerText);
}

You could rewrite it to this (which uses an arrow function as well):

var tags = hrefs.map(href => href.innerText);


Simplified encryption API wrapper for RSA and AES

I don't think you are over-thinking it, casting is always a code-smell. The fundamental problem is that you separate logic from data, the key (data) and the actual usage of that key (data). This is a problem in object-orientation.

Here is an alternative possible design, which does not do that:

public interface SecretKey {
    PublicKey generatePublicKey();

    CipherText encrypt(byte[] plaintext); // Symmetric encrypt
}

public interface PublicKey {
    CipherText encrypt(byte[] plaintext); // Asymmetric encrypt
}

public interface CipherText {
    byte[] decrypt();
}

It all depends of course on your requirements, this may not exactly match what you are looking for, but the key idea here is that the data and function are not separated.


Method naming and violating single responsibility

It looks like you're building a small DSL, in which event message "Hello" is analogous to, say, Rails' belongs_to :user. The difference is that while belongs_to is only, in a sense, a setter (it can't be called without an argument, and doesn't return any useful value), you've built message as a getter and a setter.

I think this is about context. In your example:

Queue.new :test_queue do
  message "This is a test"
end

..the use of message feels "right." But in this example, it doesn't:

q = Queue.new :test_queue

q.message "This is a test"

..at least not as much. q.message = "..." makes more sense here.

You could just leave it as-is, i.e. allow assignment both ways, using whichever you prefer and letting others use whichever they prefer. The other option would be to make it work one way inside the constructor block and another way on an instance object. Here's an article that's relevant to this approach, with an apropos shout-out to Factory Girl, which itself contains a great DSL.

Hope that helps!


You forgot to include <string>, and misspelt std::size_t (twice).
Since this doesn't create a RFC-4122-compliant UUID, I would change the name so it doesn't get used where it shouldn't.  Perhaps create_random_id() or similar?
I don't like the name x for the digit string - I'd prefer something more descriptive like hex_chars or even just hex.

We could consider constructing a string that's already long enough, then setting all its characters:
std::string uuid(len, '\0');
for (auto& c: uuid) {
    c = x[dis(gen)];
}

Or perhaps replace the loop with a standard algorithm:
std::string uuid;
uuid.reserve(len);
std::generate_n(std::back_inserter(uuid), len,
                [&]{ return x[dis(gen)]; });

Though I don't think that's necessarily clearer.

Going a little over the top, we could make a general select-from-collection function and use that:
template<std::ranges::sized_range C, class G>
auto sample_from(C const& collection, G&& generator)
{
    std::uniform_int_distribution<typename C::size_type> dis{0, std::ranges::size(collection) - 1};
    return collection[dis(generator)];
}

⋮
    static const std::string_view hex_chars = "0123456789abcdef";
    std::generate_n(std::back_inserter(uuid), len,
                    [&]{ return sample_from(hex_chars, gen); });

We might even make a custom input-iterator for selecting random characters:
class random_char_source
{
    const std::string chars;
    std::mt19937 generator;
    std::uniform_int_distribution<std::size_t> distribution;

public:
    using iterator_category = std::input_iterator_tag;
    using value_type = char;
    using difference_type = int;
    using pointer = const char*;
    using reference = const char&;

    explicit random_char_source(std::string chars, std::random_device::result_type seed = std::random_device{}())
        : chars{std::move(chars)},
          generator{seed},
          distribution{0, this->chars.size() - 1}
    {}

    // it's an input iterator
    char operator*() { return chars[distribution(generator)]; }
    random_char_source& operator++() { return *this; }
};

That makes our ID generator very simple:
static std::string generate_random_id(std::size_t len)
{
    auto hex_chars = random_char_source{"0123456789abcdef"};

    std::string uuid;
    uuid.reserve(len);
    std::copy_n(hex_chars, len, std::back_inserter(uuid));
    return uuid;
}

However, for generating power-of-two numbers, and since we have a UniformRandomBitGenerator (the std::mt19937 object), we can extract bits directly:
static std::string random_id(std::size_t len)
{
    static const std::string_view hex_chars = "0123456789abcdef";
    using Generator = std::mt19937;

    Generator gen{std::random_device{}()};

    std::string uuid;
    uuid.reserve(len);

    while (uuid.size() < len) {
        auto n = gen();
        for (auto i = Generator::max();  i & 0x8 && uuid.size() < len;  i >>= 4) {
            uuid += hex_chars[n & 0xf];
            n >>= 4;
        }
    }

    return uuid;
}

You could probably make a simpler and more readable version of that.


Time Converter - Python Tkinter - General comments on code

One issue I can see on first glance is the *. It's considered bad practice to import everything like that, and here is why from this Stack Overflow post:

Because it puts a lot of stuff into your namespace (might shadow some other object from previous import and you won't know about it).
Because you don't know exactly what is imported and can't easily find from which module a certain thing was imported (readability).
Because you can't use cool tools like pyflakes to statically detect errors in your code.


#include <stdexcept>

And either <utility> or <algorithm>, for std::swap.

stack(int max) {

I very strongly recommend you make this constructor explicit. Right now it's a non-explicit (implicit) conversion, which means you're permitting your users to convert integers to stacks implicitly:

void foo(stack<int> s);
void bar() {
    foo(42);  // compiles and calls foo with stack<int>(42)
}

The general rule (at least for user codebases) is "make everything explicit unless you have some specific reason that it needs to be implicit." So you should make your node constructor explicit as well.

(I say "at least for user codebases" because the STL itself doesn't follow that principle — partly because the principle wasn't understood in 1998, and partly due to differences of opinion among the authors. "STL style" would be to make stack(int) explicit because it's a one-argument constructor, but leave all zero- and two-argument constructors implicit. I recommend against doing that.)

int max = -1; // -1 so isFull() == false when default constructor used

This comment doesn't help me understand. I would understand INT_MAX, but -1 just looks like it's breaking the class invariant enforced by the one-argument constructor:

if (max <= 0) throw std::out_of_range("stack size must be > 0");

Looking at these two lines in isolation, actually, I briefly wondered "wait, doesn't that always throw? You don't initialize max before that if, so it would have its default value, which is less than zero..." But then I realized that the name max here is overloaded: the max in the if statement is testing the function parameter, not the data member.

To eliminate confusion about name overloading, I strongly recommend that you sigil each of your data members with a trailing underscore: max_, size_, head_.
Then you don't have to write this-> when you access a member:

this->max = max;

can become just

max_ = max;

You don't need the disambiguating this->, because there's no confusion anymore about which max/max_ you mean.

stack(stack const& rhs) :
    head(copyList(rhs.head)),
    size(rhs.size),
    max(rhs.size) {}

Do you see the typo?

Write some unit tests for your code! In particular, now that you've spotted a bug, write a unit test that would have caught this bug and commit it as part of the bugfix. That's called a "regression test."

stack& operator = (stack const& rhs)
{
    stack tmp(rhs);
    swap(tmp);

    return *this;
}

FYI, the copy-and-swap idiom can be written more concisely if you want to:

stack& operator=(stack const& rhs)
{
    stack(rhs).swap(*this);
    return *this;
}

const void pop() {

The const here is useless; remove it. (I wonder if it was a mistake for something similar — void pop() const? constexpr void pop()? but neither of those makes sense either.)

T peek() {

OTOH, this method should be const:

T peek() const {
    if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");
    return std::as_const(head->data);
}

I threw in an as_const just to illustrate complete paranoia. We don't know what type T is, right? So when you construct the return value T, which constructor do you want to call — T(T&) or T(const T&)? Write a unit test for a type T where it makes a difference, and see what happens.

getSize(), isFull(), and isEmpty() should all be const methods as well.

void swap(stack& other) noexcept

Good! You also do the using std::swap; dance correctly — although, since you're not swapping anything but ints and pointers, the dance is unnecessary in this case, but hey it's good practice.

You did forget, though, that if you want the using std::swap; dance to work for anyone else who uses your stack class, you'll need to provide that free ADL function swap. So we add an inline friend:

friend void swap(stack& a, stack& b) noexcept {
    a.swap(b);
}

Now

using std::swap;
swap(redstack, bluestack);

will be as efficient as possible.

Consider adding move semantics to your class — stack(stack&&) noexcept, stack& operator=(stack&&) noexcept, void push(T&&) (or just void push(T) at that point). I assume you left them out on purpose for this simple example.

Your copyList is recursive. This could blow your stack if you're copying a very long list. You successfully eliminated the recursion from your destructor — why not eliminate it here too?

node* copyList(node* l)

Since this member function doesn't need the this pointer for anything, it should be marked static. And it wouldn't hurt to add const to the node you don't intend to modify, just for a tiny bit of self-documentation:

static node *copyList(const node *l)


Here a few suggestions (in no particular order) for improvements on your code:

Make variables have locality

The line:

items = 1

is at the top of the method, but is only used by the loop at the bottom of the method.  It is likely better located just in front of the loop that increments it.

Same applies to:

tickerdict = {}

You can break strings across multiple lines:

This:

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}

Can be:

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) '
    'AppleWebKit/537.36 (KHTML, like Gecko) '
    'Chrome/56.0.2924.87 Safari/537.36'
}

You often don't need loops:

for tags in maxpage_td[0].findAll('a'):
    maxpage_a_tag.append(tags)

likely works just fine as:

maxpage_a_tag.extend(maxpage_td[0].findAll('a'))

And then this:

maxpage_a_tag = []
maxpage_a_tag.extend(maxpage_td[0].findAll('a'))

is really just:

maxpage_a_tag = list(maxpage_td[0].findAll('a'))

Don't use python names

The name type is used by Python.  Suggest instead changing to type_ or better yet, as suggested from comments, something more descriptive, like request_type.

Reworked code:

Here is the reworked code with the above suggestions, and maybe a few others that snuck in.

class finviz_crawler():

    def requesting(self, type_):
        baseurl = 'https://finviz.com/screener.ashx?v=111'
        if type_ == 'sp500':
            firstpage = baseurl + '&f=idx_sp500&o=ticker'
        elif type_ == "China":
            firstpage = baseurl + '&f=cap_largeover,geo_china'
        else:
            raise ValueError("Unknown type {}".format(type_))
        finalurl = firstpage
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) '
                          'AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/56.0.2924.87 Safari/537.36'}
        resp = requests.get(finalurl, headers=headers)
        soup = bs.BeautifulSoup(resp.text, "lxml")
        maxpage_td = soup.findAll('td', {'class': 'body-table'},
                                  bgcolor="#ffffff", valign="top",
                                  width="100%")
        maxpage_a_tag = list(maxpage_td[0].findAll('a'))
        if not maxpage_a_tag:
            maxpage = 1
        elif (maxpage_a_tag[-1].text == "next"):
            maxpage = maxpage_a_tag[-2].text
        else:
            maxpage = maxpage_a_tag[-1].text

        items = 1
        tickerdict = {}
        for page in range(int(maxpage)):
            resp = requests.get(finalurl, headers=headers)
            soup = bs.BeautifulSoup(resp.text, "lxml")
            table = soup.findAll('td', {'class': 'screener-body-table-nw'})
            find_all_args = 'a', {'class': 'screener-link-primary'}
            for row in table:
                tickerdict.update(
                    {tickers.text: tickers['href']
                     for tickers in row.findAll(*find_all_args, href=True)})
                items += 20
            finalurl = "{}{}{}".format(firstpage, "&r=", str(items))

        for data in tickerdict.items():
            print(data)

finviz_crawler().requesting('China')


Comparing list elements in an effective way

Instead of implementing isSame implement equals and hashCode. After that you could use a HashSet (or LinkedHashSet if the order of elements is important). Set is a collection that contains no duplicate elements and inserting/searching is much faster than searching in a list.

Set<GameState> opened = new LinkedHashSet<GameState>();

public void addEverything() {
    List<GameState> list = current.neighbours;
    for (GameState state : list) {
        opened.add(state);
    }
}

If you need a list, you can convert it back after the loop:

List<GameState> openedList = new ArrayList<GameState>(opened);

See also: Overriding equals and hashCode in Java
According to the Java Code Conventions, class names in Java usually starts with uppercase letters.


In short : its an extremely bad piece of code.

Here is a list or "whys":

you are mixing data access with logic ( sql queries should be handled by different object )
you are using global state for DB access
there is some mystical parameter $full in full_name() method
all the methods are getters
the SQL queries happen each time you use a getter
parameter $id means nothing ( is it a string , a number , some other object ? )

Basically what you have there are five standalone procedures wrapped up in an a class just for show.


Presenting and passing data to a modal view controller without using prepare(for:sender:) method

Is it guaranteed that viewDidLoad() will finish before viewWillAppear() is called? Will an even a larger data set be available for rendering as PDF in viewWillAppear()?

Yes. It needs to be loaded before it will appear.

  Is it acceptable to present modally from the UINavigationController?

I think it is.

  Should I be subclassing the main UINavigationController and using its prepare(for:sender:) method (if this is even an option)?

It sounds a bit complicated. prepare(for:sender:) is not a very clean way to do transfer data to begin with and only useful when you use segues in a regular way. Why don't you create the ModalViewController in code, set the value and then push it through code instead?

  In the performSegue(withIdentifier:sender:) method, does the sender argument make any difference?

I used it in rare occasions to understand where the push was coming from.

  Is it preferable to use present() rather than a segue?

I think in your case yes.


Rendering the AuthorName using the DOMParser to read XML

Style

Inconsistent use of line ending semi colon

Undeclared variables parser and xmlDoc

Unused code. let t = a.children[i].textContent; t is never used the line should not be there

Poor naming

Capitalisation of variable names. Only if objects to be instanciated via new token, if accronim (eg HTML, XML) or if a constant (optional).
Examples; AuthorsInfo should be authorsInfo,  AuthorName as authorName, xmlDoc as XMLDoc.
Non descripttive names, a, tt, t
Semanticly inacurate names, AuthorsInfo either authorNodes or just authors

Use for of loops rather than for if loops if you do not need the index counter

Use for of loops rather than Array iterators

Function scoped variables should be declared as var and hoisted to the top of the function

Code design
As you have several potential errors in the code (undeclared variables) you should ALWAYS use the directive "use strict" in your code to ensure these types of syntax problems are caught early in the development process.
Always present your code as a function/s. Presenting code as flat global scoped source string is very poor design practice.
Flat code often ends up performing many tasks that should be separated. Writing functions helps you define task roles under clearly named functions.
The parsing of the XML to HTML is more than one task. I suggest you have two functions parseAuthors to extract the author details, and authorsToHTML to create the markup.
Example rewrite
From your code it is unclear as to the nature of the XML. Can authors have no last name, initials, or affiliations. Do authors always have one last name, does the last name always come before the initials. And many more unanswered questions regarding the XML.
The example assumes that the XML given defines the XML.
The example breaks the code into many smaller functions and puts them all together inside a IIF (immediately invoked function). In the real world you would put all the code inside a module.

"use strict";
// As IFF or better as module (No need for use strict if module)
const authors = (() => {
    const AUTHORS = "Author";
    const AFFILIATION = "AffiliationInfo";
    const LAST_NAME = "LastName";
    const INITIALS = "Initials";
    const SEP = "

";
    const nodeTxt = (node, name) => (name ? node.querySelector(name) : node).textContent;

    function Author(authorNode) {
        const author = {
            lastName: nodeTxt(authorNode, LAST_NAME),
            initials: nodeTxt(authorNode, INITIALS),
            affiliations: []
        }
        for (const affNode of authorNode.querySelectorAll(AFFILIATION)) {
            author.affiliations.push(nodeTxt(affNode));
        }
        return author;
    }

    return {
        parse(XMLString) {
            const authors = [];
            const authorNodes = new DOMParser()
                .parseFromString(XMLString, "text/xml")
                .querySelectorAll("Author");
            for (const authorNode of authorNodes) { authors.push(Author(authorNode)) }
            return authors;
        },
        toHTML(authors) {
            var markup = "";
            for (const author of authors) {
                markup += author.lastName + " " + author.initials + SEP;
                markup += " " + author.affiliations.join(SEP) + SEP;
            }
            return markup;
        },
    };
})();
document.body.innerHTML = authors.toHTML(authors.parse(getXML()));

function getXML() { return `<AuthorList CompleteYN="Y">
<Author ValidYN="Y">
    <LastName>Basree</LastName>
    <ForeName>Mustafa M</ForeName>
    <Initials>MM</Initials>
    <AffiliationInfo>
        <Affiliation>The Cancer Center...</Affiliation>
    </AffiliationInfo>
</Author>
<Author ValidYN="Y">
    <LastName>Shinde</LastName>
    <ForeName>Neelam</ForeName>
    <Initials>N</Initials>
    <AffiliationInfo>
        <Affiliation>The Comprehensive..</Affiliation>
    </AffiliationInfo>
</Author>
<Author ValidYN="Y">
    <LastName>Koivisto</LastName>
    <ForeName>Christopher</ForeName>
    <Initials>C</Initials>
    <AffiliationInfo>
        <Affiliation>Hollings ...</Affiliation>
    </AffiliationInfo>
    <AffiliationInfo>
        <Affiliation>Department ...</Affiliation>
    </AffiliationInfo>
</Author>
<Author ValidYN="Y">
    <LastName>Cuitino</LastName>
    <ForeName>Maria</ForeName>
    <Initials>M</Initials>
    <AffiliationInfo>
        <Affiliation>Hollings...</Affiliation>
    </AffiliationInfo>
    <AffiliationInfo>
        <Affiliation>Department ..</Affiliation>
    </AffiliationInfo>
</Author>
</AuthorList>`
};


Should I treat direct CFC Calls differently than Page Requests?

If you're using ColdFusion 9, you can use onCFCRequest to deal with this type of issue. Which version of CF are you using?


Department of Redundancy Department

There's a lot of unnecessary variables here, so cleaning that up is going to be a good way to go. Your comments indicate this pretty clearly:

private double payPerHour; //regular hourly wage
private double overTimePayPerHour; //regular hourly wage * 1.5

If overtime pay is always regular pay times 1.5, why do we need it as a separate variable? Just drop the overtime setter and have the getter do the right thing:

public double getOverTimePayPerHour()
{
    return this.payPerHour * 1.5;
}

Similarly, basePayHours and overTimeHours can be derived from totalHours:

public double getBasePayHours()
{
    return Math.min(this.totalHours, 40);
}

public double getOvertimeHours()
{
    return Math.max(0, this.totalHours - 40);
}

totalPay can be calculated on the fly and doesn't need to be a member variable.

public double getTotalPay()
{
    return getBasePayHours() * this.payPerHour + getOvertimeHours() * this.payPerHour * 1.5;
}

Invalid states

In addition to removing redundancies, the above changes also get rid of another problem in your code - invalid state. getTotalPay() is only valid after you call calculateTotalPay(), which itself is only valid after you call setOverTimePayPerHour(). That's a lot that the user has to keep track of to use your code correctly, and is extremely error-prone.

Excessive commenting

Comments are for making otherwise difficult code clear. Have a complicated algorithm, or doing something that seems unobvious? Comment!

But when your code speaks for itself (which you should always strive for), the comments are, at best, annoying and could easily deteriorate the quality of the code over time if you update the code but forget to the update the comments.

In each of these examples, the comment is literally restating the code:

return this.totalPay; //returns this object's totalPay value
public double getTotalHours()  //returns this object's totalHours value
public double getOverTimePayPerHour() //returns overTimePayPerHour rate
// etc.

On the other hand, the following comment is incorrect:

public void setPayPerHour(double x) //takes parameter 'x' a d sets that equal to this objects payPerHour variable

It doesn't set the parameter, it sets the object's member. Although the comment itself is unnecessary. If setPayPerHour() doesn't set something related to the hourly pay, it's the function's name that's the problem, not the lack of comment.


Counting subtrees where all nodes have the same value

Allow Node take left and right, and BinaryTree take a node.

new BinaryTree(
    new Node(
        0,
        new Node(1),
        new Node(
            0,
            new Node(
                1,
                new Node(1)
                new Node(1)
            ),
            new Node(0),
        )
    )
)

Takes a fair amount of lines, but clearly shows the shape of the tree and removes the need for the messy tree.root.right.left.right usage.


I find neither approach is good.

What's wrong with the switch?

It needs to be modified with each change and even only if you want to do something with only one shape.
It's bound to key-codes.
You cannot test it.

What's wrong with reflection?

Reflection is usually the last resort solution. I think you are not at a dead end yet.
The way you implemented it is very unsafe because you use the FullName and Contains. What if a Rectangle would be in a namespace like CirclesAndSqures and you are looking for a circle? You'll find something that is not a circle but a rectangle only because its namespace has the name circle in it.
You cannot test it.

Instead I suggest the following. Let's say you have an abstract Shape

abstract class Shape { }

and some concrete types

class Circle : Shape { }

For each type you can write a factory that implements a common interface:

interface IShapeFactory
{
    Shape CreateShape();
}

Each factory of course can depend on other services like reading from the console etc.

class CircleFactory : IShapeFactory
{
    public Shape CreateShape()
    {
        // read params etc
        return new Circle();
    }
}

Finally you create a dictionary with all the shape factories

var shapeFactories = new Dictionary<string, IShapeFactory>(StringComparer.OrdinalIgnoreCase)
{
    [nameof(Circle)] = new CircleFactory()
};

var shapeName = // read shape name...

if (shapeFactories.TryGetValue(shapeName, out IShapeFactory shapeFactory))
{
    var shape = shapeFactory.CreateShape();
}

You can now add as many shapes and factories as you want without touching any other shapes or common code.