In short programs it can be OK, but in general avoid  writing using namespace std. You'll find plenty of material here and elsewhere on why this is so.
To promote proper encapsulation of data, both real and imaginary should be declared under private, i.e., not be visible to the outside.
All of the four member functions that perform arithmetic take on too much responsibility and as a result, are very inconvenient for the user. That is, remember: one function, one responsibility. If you add, then you don't also print. For example, as a user, I just want to use your class for complex arithmetic - I don't want to print every time I do so!
Your four member functions don't modify the state of the object. This makes the whole class and its functionality quite rigid and strange. As it is, the functionality appears as it should be a collection of four free functions not inside any class (indeed, perhaps your background is in Java where I can imagine this is more common). A more intuitive interface for let's say the addition would be void add(const ComplexNumber& other) { ... }, where the implementation actually adds to real and imaginary of *this. Same for the other three operations.
If you wanted to get fancy, you could use operator overloading to allow for a natural way to express complex arithmetic for the user.
It would be useful to add a void print() const { ... } method in case the user wants to print.
Use an initializer list if you need to write explicit constructors, i.e., write ComplexNumber(double r, double i) : real(r), imaginary(i) { } instead. If you don't, the compiler will call default constructors on the members first which in your case is unnecessary.
In modern C++, we have the option of using in-class constructors for default values. This is quite handy, i.e., you could have double real {0.0}; (similarly for imaginary) if you wanted to support the creation of complex numbers without an explicit constructor call.
By the way, you don't have to write ComplexNumber a = ComplexNumber(realA, imaginaryA); when it's much cleaner to write ComplexNumber a(realA, imaginaryA);.
Perhaps you know this, but std::complex<T> does exist if you wanted to do complex arithmetic in a more serious setting.


Insert, update and get in the same php file?

Your concept using the HTTP verbs is pretty much the idea behind REST. You could go one step further and use the less known verbs like PUT, DELETE, UPDATE.

Also u could use the $_SERVER['REQUEST_METHOD'] to switch between the HTTP modes you would like to process.

I would suggest to write a "class Request" to be reused by all your CRUD pages or use / get inspired by (for example) symfony2

https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php

u are using classes like CategoryMySqlDAO why do not u use a CRUD class? u could implement an abstract class CRUD with "create, update, delete" methodes and then use subclasses for each crud page. Then you would inject the DAO and stuff in the constructor and use autoload to get them instead of a smelly required statement in each file.

also having HTML and logic in the same file never is a good idea.

i hope i could give you some inspiration how to improve your current state


Iterative Flood Fill implementation in C

There is no need to have m and n as global variables. Create a structure to hold your data members together and pass a pointer to that structure to your functions.
Variable names are too short and not intuitive: m, n, arr, i, j, x, y etc. Use better names (ex: numberOfRows, numberOfCols etc) that explain what the variable is doing.
For readability reasons I would go with a recursive implementation. My second choice would be a stack based, if recursivity is not an option. And if performance would really be an important point of my implementation that I would do something similar but:

I would create a struct MatrixMap that would hold my matrix, number_of_rows and number_of_cols.
I would represent the position of an element from the MatrixMap using a structure MatrixMapCoordinate having two size_t values, Row and Column.
An element from the MatrixMap can be represented using a structure MatrixMapElement.
Accessing an element can be done with a function similar with:

const MatrixMapElement* ElementAt(const MatrixMap* fromMap, const MatrixMapCoordinate* atPosition);

I would move in my matrix using specialized functions such as MoveWest, MoveNorth, MoveEast and MoveSouth. You can even send flags to control the movement behavior: SkipAllEmptyCells, MoveOneCell etc.

Lastly, what I said at point 2 and 3 I would rewrite my algorithm as close as possible to the actual pseudocode.

//Read "elements" as color in the algorithm.
//  I decided to use element instead of color so you can use it in any kind of problem, regardless of what does your matrix contains.
void FloodFill(MatrixMap* targetMap, const MatrixMapCoordinate* startingCoordinate, const MatrixMapElement* targetElement, const MatrixMapElement* replacementElement)
{
    //If the starting coordinate is out of range we end the fill
    if (HasElementAt(targetMap, startingCoordinate))
        return;

    //Check if the element at the startingCoordinate is of the targetElements.
    if (ElementsAreEqual(ElementAt(targetMap, startingCoordinate), targetElement))
        return;

    //If both target and replacement are equal there is nothing to do.
    if (ElementsAreEqual(targetElement, replacementElement))
        return;

    SetElementValue(targetMap, startingCoordinate, replacementElement);

    FloodFill(targetMap, MoveWest(startingCoordinate), targetElement, replacementElement);
    FloodFill(targetMap, MoveNorth(startingCoordinate), targetElement, replacementElement);
    FloodFill(targetMap, MoveSouth(startingCoordinate), targetElement, replacementElement);
    FloodFill(targetMap, MoveEast(startingCoordinate), targetElement, replacementElement);
}

Note that there is no error or pointer check. I wrote the code just to give you an idea on how it should look from a readability point of view.

You can do a similar implementation for any algorithm you choose.

Because of the poor readability in your initial implementation I didn't spend time to validate your logic. Though I would be more than happy to do it, if you refactor your code using some of the suggestions I gave you.


Multiple SQL statements in a single transaction

In terms of the raw/basic functionality, what you have is fine. The transactional logic is good.

Readability is the only concern I have, and would rewrite your code as (note, there are some spaces I added around some = conditions):

BEGIN TRANSACTION

    UPDATE SalaryTrans
    SET carried_forward_amount = @carriedForwardAmount,
        net_wage = @netWage,
        processed_date = @processedDate
    WHERE employee_id = @employeeID
      AND reference = @reference

    DELETE FROM CarriedForward
    WHERE employee_id = @employeeID

    INSERT INTO CarriedForward (employee_id, carried_forward_amount)
    VALUES(@employeeID, @carriedForwardAmount)

COMMIT;

I assume the business logic is correct. It is unusual to have a table in a database where deletes happen. I am more accustomed to having some sort of history for the data, and the delete is a logical thing, not a real delete. This is normally for audit/reporting purposes.


Find the highest result between two elements in an array using their values and indices

This is not a review, but an extended comment.

Consider the question:

  Given two arrays, A and B, find the maximum of A[i] + B[j]

I suppose you can do it in linear time.

Now rearrange the original equation as (A[k] - k) + (A[j] + j) and consider two auxiliary arrays, formed by A[i] - i and A[i] + i.

Finally realize that you don't need these arrays at all.


Your code it's perfectly fine

I would just change, to stress the fact that the images are the same:

.container img {
    width: 250px;
    height: 250px;
    content: url("http://iancottam.co.uk/img/footy.png");
}

and then

jsbin


Two CSS grids side by side, one is scrollable, the other isn't

Although this is not a full answer It will shorten your code,
You could remove 'background-size:cover;' & replace it with a class of bGCov,
(As your declaring this multiple times & if your application grows larger With many more Images, this will save many, many lines of code)
Aswell as Use Bitly URL shortener, to shorten all of your Image URL links, make sure to name them something farely short but related to the actual image as it makes keeping track of them easier later on.
Also if you started using scss background-position and a few other things could be made into variables.
this would shorten you code for a few lines...


Depth First Search (Adjacency List) in JavaScript

Use object literals

Your code currently refers to the graph object about 15 times. This is unnecessary, as the graph object is simply the eventual output of makeGraphs.

So, instead of creating the empty object graph and adding properties and methods later, you can use a single object literal declaration. Using an object literal allows you to abbreviate initialization of object properties and functions.

Where you have:

    let graph = {};

Replace with:

    return {

Then, all subsequent references to graph can then be removed altogether, or, in rare cases where required, replaced with this. Object literals also clean up the look of your other objects, such as edges and nodes.

For example, your addVertex function would look like this:

    addVertex(node) {
        this[node] = {
            edges: {},
            isVisited: false,
            value: node,
        }
    }

(Note: The arrow operator is not needed because the scope is determined by the object container.)

Handle creating edges / vertices from an array:

The part at the bottom shows how cumbersome it is to add edges and vertices one-by-one. The user would either have to write a loop or a container function. Instead, addEdge and addVertex could be easily modified to take array input. For example:

    addVertex(nodes) {
        for (var node in nodes) {
            this[node]: {
                edges: {},
                isVisited: false,
                value: node,
            }
        }
    }

Then, to add vertices using addVertex:

dfsGraph.addVertex([1,2,3,4,5])


Small graph API to track vertices and edges added to graph

Oh wow... I figured out what was going on. In the GraphInstantiater method, the very first call which passes synMap.keys, keys returns an iterable[Int]. Looks like taking tail on this is a long process, most likely going through the whole set of keys each time.

changing the call to

val gr = vertexAdder( synMap.keys.toList, new DiGraph[Int]( Map() ) )

made everything go faster. Does anyone know what is the underlying implementation of the container returned when you call keys on a Map ?


Let the framework do multithreading for you:

List<string> tasks = new List<string>();
foreach (string value in db.table.select(a => a.value))
{
    tasks.Add(Task.Factory.StartNew(() => CreateNewDocumentAppendValueAndSave(value)));
}
Task.WaitAll(tasks.ToArray());

Where Task is System.Threading.Tasks.Task.


Mocking the class under test with private method calls

You can't.

You need to ask yourself why it is you want to prevent executing Bar during testing.  If it is because you are worried about over-covering Bar during testing, stop worrying.  If it is because your real Bar implementation is long-running, then you probably need to inject another dependency into your class, or re-factor some code into a separate helper class which can then be injected.

As long as your Foo implementation needs to call Bar, your unit tests for Foo ultimately need to as well.  As long as Foo ultimately calls Bar, you cannot fully test Foo without executing Bar.  You shouldn't rely on it calling Bar, but you cannot prevent it from calling Bar in your tests without intentionally crippling your test coverage.


Deleting values from std::vector of different types

Is the next code safe to delete the values?

No. At the very least, you should probably use reinterpret_cast instead of static_cast.Yes.

That said, it seems you are having the x-y problem. Storing data in C++, when you have heterogenous types in a sequence, should be done using a variant type, not void*; in other words, you should create a system that stores your type information per type/variable instance, instead of discarding all type information - like void* does). You are better off maintaining sepatate element lists (sparse arrays or some kind) by type, than you are with a vector<void*> (or vector<unique_ptr<void>> for that matter).

Have a look at boost::any and boost::variant before implementing your solution. You could use one of those, or a separate (similar) implementation.


Word counter using a word list and some text files

You should try to switch inner and outer loop, because it will be much faster to read each wikipedia articles in and count the word frequencies for all 500k words (you anyway have the 500k word list in memory all the time). What you do now is reading 500k times all articles into memory which is time consuming.

To sum up all usages of a word, you can use the map which already exists. Just read out the current sum for a given word, add the occurrences in the current article and write it back to the map. Right now you are just writing one entry to the map, convert it to a string and clear it right afterwards. I assume, you had the idea in mind to do it how I described.

Don't worry about Java execution speed in general, because the code will get compiled (just-in-time-compilation) to machine code eventually.


Ah sorry guys i found a solution:
Will simply do the following and null checks will be handled in constructor
 LocalDateTime tokeDateAndTimeStamp = tokenService.getPreviousLoginStamp(request,userEntity, LocalDateTime.now()).orElseGet(null);
    LocalDateTime latestRetrievedDocumentDateAndTime = auditRepository.getLatestRetrievalDocumentDateAndTime(userEntity.getId()).orElseGet(null);
    AuditEntity auditEntity = auditRepository.getLatestSendEmailDateAndTime(userEntity.getId()).orElseGet(null);


Checking where/if another creature lies in a creature's field of view

In this case, you should divide your world into a 2D grid, where each grid cell is at least as large as your viewing distance. Lets say that the grid has \$k\$ cells. Then, in each step of the iteration you place each creature into its appropriate gridcell \$(O(n))\$, then for each cell you iterate over the creatures in it, and check it against every creature in the up to 9 closest cells \$(O(\frac{9n^2}{k}))\$.

This is still not perfect, but it could provide a significant speedup if you have a lot of creatures, and if your viewing distance is small compared to the size of your world. This would imply that you can make \$k\$ large, and thus you could make your algorithm 10-1000 times faster depending on your situation.

Another thing: since calculating the difference in heading takes longer time than checking pairwise distance, you should check the distance first, and only compare the heading if the creatures are close to each other.

If you want to get even more efficient, you could save half the pairwise distance checks by not comparing B to A if you have already compared A to B. To do this, you could sort the creatures by some ID once, and in your iteration you only compare distances if the first creature has lower ID than the second. However, this will most likely not impact you runtime significantly.

EDIT: I tried implementing a grid structure, but since the creatures are spaced on a 500x500 area, and their view distance is 100, the maximum speedup is only about \$\frac{25}{9}\$. However, I managed to get everything running about 3 times faster by switching to checking distance first, checking distance squared instead of distance, and using a grid. It's not very pretty, but it's something that can be improved:

import math
import random
import time

def getAngle(c1, c2):
    dx=c2.x-c1.x
    dy=c2.y-c1.y
    rads=math.atan2(dy,dx)
    return rads

def getDist(c1, c2):
    return (c1.x-c2.x)**2 + (c1.y-c2.y)**2

def angleDiff(source,target):
    a = target - source
    a = (a + math.pi) % (2*math.pi) - math.pi
    return a

class Creature(object):
    """A virtual creature"""
    def __init__(self):
        self.x = 500*random.random()
        self.y = 500*random.random()
        self.heading=random.random()*2*math.pi
        self.vision_right = False
        self.vision_left = False
        self.FOV = 60/180*math.pi
        self.viewDistanceSq = 100**2

def check_visibility(creature, other_creature):
    if getDist(creature, other_creature) < creature.viewDistanceSq:
        ang = angleDiff(creature.heading,getAngle(creature,other_creature))
        if abs(ang) < creature.FOV:
            if ang < 0:
                creature.vision_left = True #vision_left side
                if creature.vision_right:
                    return True
            else:
                creature.vision_right = True #vision_right side
                if creature.vision_left:
                    return True
    return False

def check_neighbors(creature, grid, i, j):
    for di in range(-1, 2):
        if not 0 <= i+di < 5:
            continue
        for dj in range(-1, 2):
            if not 0 <= j+dj < 5:
                continue
            for other_creature in grid[i+di][j+dj]:
                if creature == other_creature:
                    continue
                checked = check_visibility(creature, other_creature)
                if checked:
                    return

def run_simulation(creatures, grid):
    for creature in creatures:
        grid[int(creature.x/100)][int(creature.y/100)].append(creature)

    for i, row in enumerate(grid):
        for j, cell in enumerate(row):
            for creature in cell:
                check_neighbors(creature, grid, i, j)

creatures=[Creature() for _ in range(2000)]
t0 = time.clock()
for _ in range(1):
    grid = [[[] for i in range(5)] for j in range(6)]
    run_simulation(creatures, grid)
t1 = time.clock()
print(t1-t0)


Why are you using a symbol for the data? If you're hoping for private variables, you're out of luck.
return JSON.stringify(res.join(' ')); Why? Why not just return JSON.stringify([...this]) or something? Why both join into a string and JSON stringify?
return this[data].slice(-1)[0]; is inefficient as it needlessly copies the array for each call. return this[data][this.size()]; should be (if marginally) better.
Why is your reverseArrayGenerator generator function not in Utils?
isDefAndNotNull, while nice, can be shortened or completely dropped. Shortened to object != null which is exactly the same thing, or dropped altogether in favor of:   object && typeof object[Symbol.iterator] === 'function';

I won't repeat what the other answer says, but it's also correct.


Boolean flags encoded as integer implemented with EnumSet

It looks fine. Some notes about the tests:

Test methods should be in another class (ClientCapabilitiesTest) and in a separate source tree. For example, Maven projects usually store sources under src/main/java and test sources under src/test/java. (Introduction to the Standard Directory Layout).

The first parameter of assertEquals is the expected value and the second is the actual one, so you should change

assertEquals(targetBuffer[1], (byte) 0x85);

to

assertEquals((byte) 0x85, targetBuffer[1]);

JUnit error messages assumes this order.

Create more tests which helps defect localization. A parameterized test class would be fine:

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class ClientCapabilitiesTest {

    private final byte[] input;
    private final EnumSet<Flag> expected;

    @Parameters
    public static Collection<Object[]> data() {
        // TODO: add more cases
        final Object[][] data = new Object[][] {
                { new byte[] { (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00 },
                        EnumSet.of(Flag.CLIENT_LONG_PASSWORD) },
                { new byte[] { (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00 },
                        EnumSet.of(Flag.CLIENT_FOUND_ROWS) },
                { new byte[] { (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00 },
                        EnumSet.of(Flag.CLIENT_LONG_PASSWORD, Flag.CLIENT_FOUND_ROWS) },
                { new byte[] { (byte) 0x85, (byte) 0xa6, (byte) 0x03, (byte) 0x00 },
                        EnumSet.of(Flag.CLIENT_LONG_PASSWORD,
                                Flag.CLIENT_LONG_FLAG,
                                Flag.CLIENT_LOCAL_FILES,
                                Flag.CLIENT_PROTOCOL_41,
                                Flag.CLIENT_INTERACTIVE,
                                Flag.CLIENT_TRANSACTIONS,
                                Flag.CLIENT_SECURE_CONNECTION,
                                Flag.CLIENT_MULTI_STATEMENTS,
                                Flag.CLIENT_MULTI_RESULTS) } };
        return Arrays.asList(data);
    }

    public ClientCapabilitiesTest(final byte[] input, final EnumSet<Flag> expected) {
        this.input = input;
        this.expected = expected;
    }

    @Test
    public void testDecodingClientCapabilities() {
        final ClientCapabilities capabilities = new ClientCapabilities(
            PacketByteBuffer.readIntFromFourBytes(input, 0));

        Assert.assertEquals(expected, capabilities.getFlags());
    }
}

I'd add one case for every flag and some cases with multiple enabled flags.


Geolocation check and error management for Google Maps

A tricky question,

navigator.geolocation.getCurrentPosition will always return undefined, regardless of browser or whether or not the the user allowed the location to be retrieved.

That means that //Do nothing as script has started, This if clause is to force IE9 to error out instead of hanging when geolocation throws a PERMISSION_DENIED error. sounds like a superstitious approach. I believe you that it works, but it's not because you provided an empty if.

Also please read this, if you must provide callbacks, then that means that //Note that the if condition does not start until the end of the entire geolocation procedure. is wrong.

From the little code in your question, I believe you should always call displayPostcodeSelect first, and if there is a geoLocation success you trigger your function. This means you no longer need to catch failures anymore since you want displayPostcodeSelect in that case anyway.

Furthermore, production code should not have console.log, it just looks bad.

Finally, 1 liner function that are used only once do not make sense, you should inline the checkGeolocate function.

All in all, I would counter propose:

//Start by showing the PostcodeSelect
displayPostcodeSelect();
if ('geolocation' in navigator)
{
  var geoOptions =
  {
        timeout            : 5000,  //5 seconds
        maximumAge         : 90000, //1.5 minutes
        enableHighAccuracy : true
  };
  navigator.geolocation.getCurrentPosition(function(position)
  {
        userLat.val(position.coords.latitude);
        userLng.val(position.coords.longitude);
        userDist.val(25);

        start();

        mapControls.fadeIn(200);
        mapOverlay.fadeOut(100);
  }, function(){}, geoOptions );
}


Determining if f(n) = n^2 + 3n + 5 is ever divisible by 121

I don't know Lisp, but you can speed up the calculation by observing that n² + 3n + 5 is never divisible by 11 (and hence never divisible by 121), except when n mod 11 == 4.

If you check the equation for the remaining candidates (11*k+4) in the "full" module 121 (e.g. using Lisp, but I did it in Excel), you get always an remainder of 33, so the conjecture is indeed true.

I would consider this exercise as "bad style", as it encourages the "brute force" instead of the "think" approach. There are enough not-so-easy to solve conjectures (e.g. Goldbach's conjecture) where falling back to brute force actually makes sense.

[More Explanation]

Modular arithmetic is described here, but I will try to give a short introduction: Let's say we want to know the remainder of the polynom by division by 11 when n is of the form 11*k + 3. We could write

(11*k+3)² + 3*(11*k+3) + 5

But as we are only interested in remainders, not the numbers itself, we "forget" all multiples of 11 and write in modular arithmetics:

3² + 3*3 + 5 | mod 11
9 + 9 + 5 | mod 11
23 | mod 11
1 | mod 11

This says that when we have a number 11*k + 3, our polynom will always have a remainder of 1 when divided by 11. n=3 gives a polynom value of 23, which is 1 mod 11. n=256  gives 66309, which is again 1 mod 11. As 121 = 11², if a number is not divisible by 11, it isn't divisible by 121 either. So no number n = 11*k + 3 is ever divisible by 121. Testing all the cases from n = 11*k + 0 to n = 11*k + 10 I found, that only for 11*k + 4 the polynom is divisible by 11. Checking all the values 11*k + 4 in module 121 (that are 121*u + v with v = 4, 15, 26, 37, 48, 59, 70, 81, 92, 103, 114) I found that all leave a remainder of 33, proving the conjecture (let's say we take n = 121 + 15 = 136, we get a polynom value of 18909, and as expected, a remainder of 33 when dividing by 121).

So there is nothing wrong with your code (and as I said I don't know Lisp), but in my opinion the "better" solution would be to say: It can be shown directly (even with paper and pencil) that the polynom is never divisible by 121, so no test is needed.


Few comments from my side:
Looks like a code bug:
I think you want to use ReentrantLock to manage concurrent operations in multithreaded environment. But in your code I don't see any place where you have made a call to lock (neither lock() nor tryLock(long timeout, TimeUnit unit)). While unlock() is used couple of time, which is of no use in this case.
Other suggested updated:

CacheAlgorithm interface should be rather renamed to Cache only. Because it doesn't make sense in any class to make use of word Algorithm.

Code should prevent using abbreviations as much as possible. So LFU should be renamed to LeastFrequentlyUsed. Which is not a very big name. Along that it should be ended with Cache to make it more clear to user. So the better name would be LeastFrequentlyUsedCache.

It would be better to have a default constructor with default capacity, as Java API has for Collection classes.

Avoid auto-boxing and auto-unboxing in code. As these are heavy operations. Rather do custom boxing and unboxing as below:

final int frequency = frequencies.get(key).intValue();
final Set<K> keys = frequencyToKeys.get(Integer.valueOf(frequency));


Largest Prime factor (Project Euler in Rust)

I think
    for p in sieve((600851475143_f32.sqrt()) as usize).iter().rev() {

should be
    for p in sieve(((n as f32).sqrt()) as usize).iter().rev() {

Alternative approach
You could chain an iterator in runtime:
#[test]
fn main_playground() {
    // Sieve iterator-style
    let number: u128 = 600851475143;
    let upper_limit: u128 = (number as f32).sqrt().floor() as _;

    let mut sieve: Box<dyn Iterator<Item = _>> = Box::new(2..=upper_limit);

    while let Some(prime_number) = sieve.next() {
        sieve = Box::new(sieve.filter(move |&x| x % prime_number != 0));
        if number % (prime_number as u128) == 0 {
            dbg!(prime_number);
        }
    }
}

The answer is still 6857. But output is
running 1 test
[src\problem_003.rs:12] prime_number = 71
[src\problem_003.rs:12] prime_number = 839
[src\problem_003.rs:12] prime_number = 1471
[src\problem_003.rs:12] prime_number = 6857

I can think of many more approaches to this. I'd actually build a Sieve iterator
if I were you.


I haven't worked with CodeIgniter before, so if I say something that argues their standards, please excuse me.

It's such a basic piece of code that there isn't too much to be said. One things I notice right off the bat, your checkbox_group() function has a first parameter with a default value. I'm surprised you haven't done anything about this because it should be throwing you a warning.

  Note that when using default arguments, any defaults should be on the
  right side of any non-default arguments; otherwise, things will not
  work as expected.

As per the PHP Functions page

To better separate the function's business and the view, consider creating an output string and returning it to be echoed. You'd then have:

$output = '';
// setting hidden field for null, if no checkbox selected
$output .= form_hidden($name . '[]', 'null');

// start checkbox loop
foreach ($checkboxes as $check => $label_text) :

    $checked = FALSE;
    $selects = get_config_row($name);
    if (in_array($check, $selects))
        $checked = TRUE;

    $output .= '
';
    $output .= form_label(form_checkbox($name . '[]', $check, $checked, 'id="' . $check . '" class="checkbox"') . $label_text, $check);
    $output .= '
';
endforeach;
return $output;

Now you call:

// render checkboxes useing function
echo checkbox_group($checkboxes, 'indexes');


Mergesort that has `man 3 qsort` ANSI C prototype

Better show your includes too, that makes evaluating your code easier and more meaningful.
Anyway, it's <stdlib.h>, <stdio.h> and <string.h>.
You know you can combine multiple conditions into a single expression with &&?
You can avoid all those casts if you use char* instead of void* internally.
Why don't you reuse a single allocation instead of doing n*log(n) ones, each local?
You know doing a single combined memcpy is far more efficient than multiple consecutive smaller ones?
If you only move the first nlft elements out of the way, you only need half the extra-space and save on copying.

Your test-program:

Your test-program doesn't seem to exercise your code...
You lost a newline at the end of your test-program.

Modified code:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

void* malloc_or_exit(size_t size) {
    void* result = malloc(size);

    if (!result && size) {
        fprintf(
            stderr, "Failed to malloc %zu bytes: %s",
            size, strerror(errno)
        );
        exit(EXIT_FAILURE);
    }

    return result;
}

static void mergesort0_impl(
    char* as, char* xs, size_t n, size_t s,
    int (*cmp) (const void*, const void*)
) {
    if (n < 2) return;

    const size_t nlft = n / 2;
    const size_t nrgt = n - nlft;

    char* ys = xs + nlft * s;

    mergesort0_impl(as, xs, nlft, s, cmp);
    mergesort0_impl(as, ys, nrgt, s, cmp);

    char* const bs = as + nlft * s;

    memcpy(as, xs, nlft * s);

    const char* i = as;
    const char* j = ys;
    for (; i != bs && j != xs; xs += s) {
        if (cmp(i, j) <= 0) {
            memcpy(xs, i, s);
            i += s;
        } else {
            memcpy(xs, j, s);
            j += s;
        }
    }
    if (i != bs)
        memcpy(xs, i, bs - i);
}

void mergesort0(
    void* xs, size_t n, size_t s,
    int (*cmp) (const void*, const void*)
) {
    if(n < 2) return;
    void* as = malloc_or_exit(n / 2 * s);
    mergesort0_impl(as, xs, n, s, cmp);
    free(as);
}

#include <stdio.h>

void test(int nr, const int xs[], size_t n) {
    int* a = malloc_or_exit(2 * n * sizeof *xs);
    int* b = a + n;
    memcpy(a, xs, n * sizeof *xs);
    memcpy(b, xs, n * sizeof *xs);
    qsort(a, n, sizeof *a, compare_int);
    mergesort0(b, n, sizeof *b, compare_int);
    printf("Test %d %s: ", nr, !memcmp(a, b, n * sizeof *xs) ? "OK" : "FAILED");
    for (size_t i = 0; i < n; ++i)
        printf("%d%c", xs[i], " \n"[i == n - 1]);
    free(a);
}

int main() {
    int xs[] = {1, 2, 3, 4, 5};
    int ys[] = {5, 4, 3, 2, 1};
    int zs[] = {3, 1, 2, 4, 5};
    int as[] = {1, 1, 1};
    int bs[] = {3, 2, 2};
    int nr = 0;
    #define TEST(a) test(nr++, a, sizeof a / sizeof *a)
    TEST(xs);
    TEST(ys);
    TEST(zs);
    TEST(as);
    TEST(bs);
    #undef TEST
}


How to write elegant conditional bits of markup in Razor views?

If you find a pattern getting too repetitive, you can use @helper instead:

@helper ShowIfNotNull(string header) {
    @if (!string.IsNullOrEmpty(header))
        @:
header

    }
}

@Model.Title

@ShowIfNotNull(Model.Subtitle)


Mean π: Archimedes vs. Gauss - π computation through generalized means

Convergence testing

    if pi == piold:
        break

This is not usually done, because float equality has a lot of gotchas. In this case it's possible due to the numbers being Decimal, but if you need to move away from Decimal you're going to encounter issues.

Usually, convergence is measured as the absolute error decreasing below a chosen epsilon, a very small positive number. One advantage is that if you start checking for convergence to epsilon, your code will be compatible with arbitrary-precision math, where the two numbers will never equal each other exactly but you still need sane termination criteria.

Formatting/rounding

D(str(pi)[:-3])

This looks troublesome. You're converting a float to a string, and then selecting a certain number of fixed digits. Don't do this. Instead, just use the built-in round, which works with Decimals just fine.

Order of Operations

pi = ((a + b)**2) / (2 * t)

Exponentiation takes precedence over division, so you can drop the first pair of outer parens.

Import assignment

D = decimal.Decimal

Usually you shouldn't do this, and instead you should use normal import syntax:

from decimal import Decimal as D


Beginner programmer on sending error messages

one way to do it is to use coalesce :

/// <summary>
/// Handles the Ouverture event of the PrescriptionVue control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void PrescriptionVueOuverture(object sender, EventArgs e)
{
    var message = ServiceCouchePolygoneFacade.Instance.RecalculerSuperficiePolygone() ?? ServicePrescriptionFacade.Instance.MettreAJourTablePrescription();

    if(message != null)
    {
        this.prescriptionVue.AfficherMessage(message);

        this.prescriptionVue.Fermer();
    }

    this.InitialiserVue();
}

the coalesce would evaluate the left-hand operand, if it's null, then it'll get the right-hand operand.


Number of right cyclic shifts to give the biggest number

Your solution seems fine.
I would suggest some coding style improvements though:

To avoid errors, avoid magic numbers, put them in constants, for example:

MAX_N = 0x3fffffff
MAX_SHIFT = 30

The variable m doesn't need to be initialized before the loop. In fact, it doesn't need to be declared before the loop. Move it inside.
res is not a great name to store the number of shifts to get the highest number. shiftCount would be better.
solution is not a great name for the method to get the shift count for the highest number. getShiftCountToHighestNum would be better.

With the above suggestions applied, the code becomes:

private static final int MAX_N = 0x3fffffff;
private static final int MAX_SHIFT = Integer.toBinaryString(MAX_N).length();

public int getShiftCountToHighestNum(int N) {
    long max = N;
    int shiftCount = 0;
    for (int i = 1; i < MAX_SHIFT; i++) {
        long m = (N >>> i) & MAX_N | (N << (MAX_SHIFT - i) & MAX_N);
        if (m > max) {
            max = m;
            shiftCount = i;
        }
    }
    return shiftCount;
}

As for the time complexity,
I believe this is indeed \$O(\log N)\$.
The number of calculation steps is proportional to the number of bits in \$N\$, which grows much slower than \$N\$ itself.


At first glance your code looks nice and clean. And even though the naming goes against PEP8 would be near perfect style.

I then entered your code into PyCharm, and then and there I knew this was unfortunately a facade.

Firstly I don't think you've set your linter up correctly. As within seconds I knew your code wasn't PEP8 compliant due to using camel case function names.

  I have feed it through a PEP8 program and it returned no errors

PEP 8 convention is to use snake_case rather than quitContinue or CtoF_Calc.
You have a couple of miss-spelt words, Prog and "entet".
It's advised against having bare except statements as they catch too many errors and lead to hard to debug errors. This can actually be seen in your program, it's hidden a bug that you probably don't know about.
celciusCalc is undefined, and so is a bug in your program.
PEP8 and linters are quite finicky when it comes to whitespace. value*(9/5) should have spaces either side of the operators.
You have a 'pointless statement', FtoC_Calc. This is as you forgot to call the function. And so causes a bug in your program.

And so I recommend you look into configuring your linter to get the maximum amount of warnings possible. I personally use Prospector and Flake 8 with a butt tone of plugins.

In FtoC_Calc you state the range in celsius, which is confusing. If I'm using your program I likely won't know what the equivalent in Fahrenheit is.
Keep the code in the try statement to be as small as possible. Looking at the except it looks like the purpose is to handle when you don't enter floating point integer values.

You haven't put the call to float in the try and so you have another bug.
You should use except ValueError.
You can put all the code that is currently in the try in an else statement.
You should replace celciusCalc() with FtoC_Calc and CtoF_Calc.

Currently your design is sub-optimal, FtoC_Calc interacts with the user and performs the mathematical calculations.

It also uses recursion rather than loops to cycle through the function calls, leading not only to spaghetti code, but toward getting a RuntimeError where you exceed the recursion depth.

This is all rather easy to deal with. Split the function into three distinct functions:

One that gets a floating point integer from the user. And handles interactions with the user if they enter an incorrect value.

If a user enters an incorrect value you'll want to have your try statement in a while loop to continuously ask for input.

By giving a range or an 'is_invalid' function to this function you can reduce the amount of duplicated code.
The function to convert C to F.
The function that calls both of these functions.

The majority of your code in make_selection is not needed. No exceptions should be raised from these functions, and it isn't the correct place to handle them.
quit_continue should be changed to a function that returns a boolean. This can be used in mainProg to determine if the user will continue using the program or exit.

This means mainProg should contain a while loop to continuously allow the user to enter values they want to convert.

It should be noted that quit_continue shouldn't need the try and should never reach the except. However adding more code the way you did would make this assumption to be less safe as the program becomes more and more problematic.
I changed your string delimiters as one of my tools errors on ", as I commonly use '. Using " is perfectly acceptable.

#!/usr/bin/python
"""
Program: Temperature Coversion (C to F, or F to C)
Date:    02 May 2019
Author:  Jason P. Karle
Remark:  This program was inspired by a Python exercise that
asks you to create a program that will convert one Celsius value to Fahrenheit;
so a program that can be executed with three lines of code.
However, I wanted to make something that would allow the user to
convert to and from either C of F, and do so multiple times, until the user
decides to end the program. This was also an exercise for me to
advance not only my code skills, but how I structure a program.
"""

def input_float(prompt, is_invalid):
    while True:
        try:
            value = float(input(prompt))
        except ValueError:
            print('That is not a number!')
        else:
            if is_invalid(value):
                print('That is not a valid number.')
                continue
            return value

def c_to_f(value):
    return (value * (9 / 5)) + 32

def f_to_c(value):
    return (5 / 9) * (value - 32)

def convert_c_to_f():
    print('\nThank you, please enter the')
    print('value you want to convert.')
    print('Enter a value between -273.5°C to')
    print('+5.5 dectillion °C')
    celsius = input_float(': ', lambda v: v < -273.5 or 5.5**30 < v)
    fahrenheit = c_to_f(celsius)
    print(f'{celsius}°C equals: {fahrenheit}°F')

def convert_f_to_c():
    print('\nThank you, please enter the')
    print('value you want to convert.')
    print('Enter a value between -459.5°F to')
    print('+42 dectillion °F')
    celsius = input_float(': ', lambda v: v < -459.5 or 42**30 < v)
    celsius = f_to_c(fahrenheit)
    print(f'{fahrenheit}°F equals: {celsius}°C')

def quit_continue():
    print('\nDo you want to:\n')
    print('     1. Make another conversion; or')
    print('     2. Exit the program?\n')
    answer = input('Make you selection: ')
    return answer == '1'

def main():
    while True:
        print('Please enter the number')
        print('corresponding to what you')
        print('want to convert:')
        print('     1. Celsius to Fahrenheit')
        print('     2. Fahrenheit to Celsius')
        print('     3. Exit\n')
        selection = input('Enter 1, 2 or 3: ')
        if selection == '1':
            convert_c_to_f()
        elif selection == '2':
            convert_f_to_c()
        else:
            return
        if not quit_continue():
            return

if __name__ == '__main__':
    print('Welcome to the temperature')
    print('conversion program!\n')
    main()


SRFI 13 has string-join. Are you sure you really need to reinvent the wheel?

But since you asked for a review, sure, I'll review.

Your docstring is in the wrong place. It should be the second subform of the lambda (after the parameters), not after the internal definitions. If that gives you a syntax error, then your implementation does not support docstrings, and you shouldn't try to shoehorn docstrings into a non-standard location.
Your procedure doesn't work if the incoming list of strings is empty. You should probably keep track of whether to print the delimiter based on whether you're printing the first element, not whether the list will end soon.
You should use for-each rather than a manual loop; it expresses your intent more clearly.

Putting all these suggestions together, we get (tested on Racket and Guile):

(define (string-join ls delim)
  "Join list of strings together by delim into one string."
  (define out (open-output-string))
  (for-each (lambda (delim item)
              (display delim out)
              (display item out))
            (cons "" (circular-list delim))
            ls)
  (get-output-string out))

(The code above requires SRFI 1 for for-each and circular-list.)

If you want your code to be portable to implementations which don't support docstrings, you can use call-with-output-string to avoid the internal definition:

(define (string-join ls delim)
  "Join list of strings together by delim into one string."
  (call-with-output-string
   (lambda (out)
     (for-each (lambda (delim item)
                 (display delim out)
                 (display item out))
               (cons "" (circular-list delim))
               ls))))


naive suffix tree construction in Python

It's pretty readable, and all comments are pretty minor ones.

You can probably squeeze out a little performance increase, but not much. One thing you could do is to skip setting variables like n = len(prefix) (you also don't use n in the following line).

You could also consider collections.deque instead of list where relevant, which can sometimes give you a little extra speed. Or if you have the option to use list comprehension, do so.

And doing if suffix_tree: instead of if len(suffix_tree) == 0: is also faster; ca 30 ns vs 85 ns on my machine (Python 3.8.1).

On the time and space complexity, you have to make a judgement call if time or space is more important; only other way you could have O(1) lookup would be with a set.

Finally, you don't need to keep track of found_match---you can just use a for-else with a break-statement.

PS. You should be wary of mutating objects you're iterating over.


To me, this seems like a perfectly good way to create the area graph! I think you've done something that's simple, straightforward, and easy to understand. Nice work!

Don't Repeat Yourself

The one thing that I think could be improved is the drawing of the line graphs. You have 2 functions which look identical except one is using line1dataPoints and the other is using line2dataPoints as its input. If you ever decide that something needs to change in the drawing or you need to add or remove anything, you now have to do it in 2 places. Why not just have a single function and pass in the array you want to use? Something like this:

func drawLineGraph(let dataPoints: [CGPoint]) {

    let graphPath = UIBezierPath()
    graphPath.moveToPoint(dataPoints[0])

    for i in 1..<dataPoints.count {

        let nextPoint = dataPoints[i]
        graphPath.addLineToPoint(nextPoint)

    }

    let lineLayer = CAShapeLayer()
    lineLayer.lineWidth = 1.0
    lineLayer.path = graphPath.CGPath
    lineLayer.strokeColor = UIColor.redColor().CGColor
    lineLayer.fillColor = UIColor.clearColor().CGColor
    self.view.layer.addSublayer(lineLayer)
}

Naming

You probably noticed that I renamed the function above to something more descriptive. Your original name was kind of vague. addFirstLine() leaves me wondering what you're adding it to?

But you are actually adding a layer to something at the end of the function. That's kind of surprising! Your original name implied a line was being added to... something. But really what's being added is a layer! And this is a side effect of the function!

Avoid Side Effects

If you want to add a layer to another layer, you should make that explicit in the function's name and definition. You should be either returning the layer that needs to be added, or passing in the layer to add the new layer to. As it is, this function creates a drawing path, then creates a layer to draw it into, then adds it to another layer. But the function definition looks like it just examines some data points. A better function definition might look something like this:

func addLineLayer(let dataPoints: [CGPoint], to layer: CALayer)

Now when you call it, you'll write:

addLineLayer(line1DataPoints, to:self.view.layer)

and it's much more clear to a reader what's going on. (Personally, I'd rename line1DataPoints to something more descriptive, too. Data points from what? Do they represent some maximum or minimum values?


Get owner of ~5 million files and folders using Powershell and Robocopy

Your robocopy command lists /NC and /NJH twice.

$Folders and $Folder contain objects with properties, use these instead of treating them as strings (which implicit casts them as such) or pipe to Select-Object -ExpandProperty FullName
Same with $Files and $File

I'd not reuse variable names but define neccessary ones from begin.
Proper indenting eases reading/understanding the code IMO better than excess white space.

The following script isn't tested at all, see it as rough template:

## Q:\Test\2018\08\12\cr_201527.ps1
Import-Module NTFSSecurity

$Logs  = 'D:\AutoAssign\Data\RoboLogs\'
$Final = 'D:\AutoAssign\Data\Final\'
$Folderpath = "G:\DEPT"

#Gets initial file and folder list
$Folders = Get-Childitem $Folderpath

ForEach ($Folder in $Folders) {
    Start-Job -ScriptBlock { Param($Folder,$Logs)
        robocopy "$($Folder.FullName)" NULL /L /S /NJH /FP /NC /XJ /NS /NJH /NC /NJS /LOG:"$Logs$($Folder.Name).txt"
    } -ArgumentList $Folder,$Logs
}

#Wait until all jobs are finished
Get-Job | Wait-Job

<# functionality integrated into next sction
    #Trims out white space and empty lines
#>

#Gets Owner for each file And Create CSV

ForEach ($File in (Get-ChildItem $Logs)){
    Start-Job -ScriptBlock { Param($Logs,$File,$Final)
        $OutputFile = Join-Path $Final "$($File.Name).csv"
        $Results = ForEach ($Path in ((Get-Content $File.FullName).Trim() -ne '')){
            $Owner = (Get-NtfsOwner $Path).Owner.Trim()
            If ($Owner -ne "BUILTIN\Administrators" -and
                $Owner -ne $null                    -and
                $Owner -ne "Domain\Domain Admins"   -and
                $Owner -notlike "S-1*"){
                [PSCustomObject]@{
                    Path = $Path
                    Owner = $Owner
                }
            }
        }
        $Results | Export-Csv -NoTypeInformation -Path $OutputFile
    } -ArgumentList $Logs,$File,$Final #Ends Initial ForEach

}  #Ends Job Script Block

#Wait unitl all jobs are finished
Get-Job | Wait-Job

#Merge all files into one CSV
Get-ChildItem  D:\AutoAssign\Data\Final | Select-Object -ExpandProperty FullName |
    Import-Csv | Export-Csv D:\AutoAssign\Data\G.csv -NoTypeInformation -Append

#Delete all original files
Get-ChildItem D:\AutoAssign\Data\RoboLogs | Remove-Item
Get-ChildItem D:\AutoAssign\Data\Final | Remove-Item


The last time I saw source for a C run-time-library implementation of memcpy (Microsoft's compiler in the 1990s), it used the algorithm you describe: but it was written in assembly. It might (my memory is uncertain) have used rep movsd in the inner loop.

Your code says, //Start copying 8 bytes as soon as one of the pointers is aligned. When you're performance-testing you should know (because that's when you might expect the best performance) whether both buffers are aligned.

On the subject of alignment there as an interesting (but unrelated to your question) question here on StackOverflow: Why speed of memcpy() drops dramatically every 4KB?

I vaguely understand what kind of an effect you're looking for in your code. I don't know what assembler your compiler is actually producing.

The accepted answer to this StackOverflow question demonstrates the kind of assembly that is used nowadays: Very fast memcpy for image processing?


Multi-threaded Winforms Conventions for Main()

I would second Steven Doggart's comment about it being pointless to spawn a thread that does nothing.

To address your separation of concerns issue, though: If you are using one of a number of design patterns for your UI (e.g., MVC, MVVM, MVP, etc.), your MainForm class will merely be binding to one or more data objects and raising events from the user.  The real work and asynchrony will be done in another class.

For example, in the MVP pattern, you might have MainForm, MainPresenter, and MainViewModel.

MainForm binds various controls to properties exposed by MainViewModel
MainViewModel implements INotifyPropertyChanged and raises PropertyChangedEvents when those properties change.
MainForm updates those properties as the result of users manipulating those controls.
MainPresenter responds to events raised by MainForm and updates MainViewModel properties as well, causing MainForm to respond through the PropertyChangedEvents

It is then up to MainPresenter (or more appropriately, other classes MainPresenter uses) to figure out how to handle threading.  MainForm itself never has to know or care that you are using separate threads.


This is not unique_ptr, it is auto_ptr, which has problems, mainly that copying a value modifies it, which is counter intuitive.

Assuming you really do not have move semantics and cannot do better (you should, C++11 is old now), there are still some problems:

There is no way to release a pointer. If I am not happy with your SmartPointer I want to do something like SmartPointer<T> sp; shared_ptr<T> ssp = sp.release();.
You forgot to return the stream inside ostream& operator <<. This should be a compilation error.
There is no need for friend. I don't know who made it popular to make the ostream& operator << a friend but I'd like to give that person a stern look. Without friend this works just fine:

template <typename E>
std::ostream& operator<<(std::ostream& stream, const SmartPointer<E>& smartPointer){
    return stream << &(*smartPointer);
}

Your copy-constructor is wrong. It copies the pointer eventually resulting in a double delete. You probably meant to have other.pointer = nullptr;.
Consider making the assignment operator return void. You are supposed to return *this to allow chaining like in a = b = c = nullptr;. However, since the assignment takes the value away there is no point chaining assignments, so better cause a compiler error.
Your assignment operator causes a memory leak in the following case:

SmartPointer<int> sp1 = new int{1};
SmartPointer<int> sp2 = new int{2};
sp1 = sp2;

The memory for the first allocation is never deleted.

Edit: There is a different memory leak case:

SmartPointer<int> sp = new int;
sp = sp;

I would suggest nullptr instead of NULL, but I guess your compiler does not know what that is.


As a general direction for improvement, your technique for finding those keywords uses startsWith, which will effectively compare any given character once per potential keyword or operator. If you switch to regular expressions, by compiling a Pattern that matches any keyword or any operator, you build (what amounts to) a lookup table that typically allows one comparison per character, reducing the total number of comparisons significantly.

You can even use Pattern.quote to make building the String easier.

public Pattern fromList(List<String> strings) {
  StringBuilder builder = new StringBuilder();
  boolean isFirst = true;
  for (String string : strings) {
    if (!isFirst) {
      builder.append('|');
    }
    builder.append(Pattern.quote(string));
    isFirst = false;
  }
  return Pattern.compile(builder.toString());
}

After that, search for every occurrence of the String using either Pattern.matcher() (or Scanner.next()), which will save you those repeated comparisons. At that point you can use the start and end methods on Matcher (or the same on Scanner.match()).

I do notice that your algorithm will tend to highlight the first half of terms like publicValue even if the compiler does not detect it as a keyword. For this, you may want to customize the patterns you generate to match word boundaries.


MVC Controller in Java Swing Apps - Singleton or public static

It's been a long time ago since I last used an MVC approach in Swing, but I immediately notice some things I wouldn't do.

Don't use a singleton, singletons are evil!
Passing view components to the controller? When I do MVC, I tend to pass the controller to my view elements, preferably just an interface. The view can request actions on the controller. This allows for total decoupling of the view. So you can also switch to something else than Swing. This probably isn't the 'default' approach of MVC with Swing however.

So yeah, it seems I would agree with you. Perhaps try looking for other MVC examples with Swing. This article doesn't look particularly appealing IMHO.


Time complexity

The solution doesn't meet the required \$O(N)\$ complexity.
Can you spot why?

       Collections.sort(list);

As it stands, the time complexity of your implementation is \$O(N\log N)\$. To get the minimum element of a collection, do you really need to sort all the elements?

Unused values, unnecessary complication

The p field of Holder is not used in the compareTo implementation.
In general, it's suspicious when a class implements Comparable but compareTo doesn't use all the fields of the class.
In fact this field is not used anywhere in the program.
So you can simplify by removing it.
And once this field is gone,
Holder will have only one field left.
A class with a single field in it is highly suspicious.
Is it really useful?

With Holder eliminated, the implementation can become much simpler, cleaner and faster.


Printing the minuend and subtrahend in a Minimum Difference algorithm

Sorting

Arrays.sort(int[]) performs an in-array sorting, which may not be desirable if the caller of your method isn't expecting so. You may want to make a copy of the input via Arrays.copyOf(int[]) first.

Calculation

int temp = Math.abs(arr[i] - arr[i + 1]);
if (temp < difference) /* ... */

Since you have sorted the array in ascending order, you have two possible approaches:

Leave temp as negative so that you're looking for the largest negative number, e.g. -1 to find the smallest difference.
Use arr[i + 1] - arr[i] so that the comparison afterwards can remain the same.

Using Math.abs() is therefore unnecessary.

Initializing values and array references

You treat arr.length = 1 differently from a multi-valued array when it comes to printing the value, but with some adjustment to how you initialize minuend and difference, you don't have to do so, e.g.:

int minuend = arr[0];
int difference = Integer.MAX;

In addition, consider storing just the difference and the array index where you have the smallest difference, so that you don't need to remember subtrahend.


Be consistent with #include
We have C++ <cstdio> (which defines the C names in the std namespace), but the C-style <math.h> (which puts the identifiers in the global namespace).  For new C++ code, prefer <cmath>.  And don't use using namespace std; - that can be harmful.
Allow the compiler to define assignment
We don't need to do anything in operator=() that's different from the compiler-generated (member-by-member copy) assignment.  Declaring our own actually prevents some optimizations that can be done for so-called "trivial" types (without the operator, the compiler knows it can simply copy the object's memory, but with one, it must assume that copying is more involved than that; it also inhibits the generation of a move assignment operator).
Similarly, we don't need to define a destructor - let the compiler generate that, too.
Pass by value for primitive types
There's no benefit to passing a reference to const int in the constructor - just pass the int by value.  That's simpler and (before optimization) faster.
Actually, why is this an int, when we could accept any double value?  And why is the default 1.0?  I think that 0.0 (an empty circle) would be less surprising (it's then more like the numbers, where default initialization uses zero).  Consider also some validation - is a negative radius meaningful for your code?
It's better to return double by value from getRadius() for much the same reasons.
Mark the constructor explicit
Unless you like surprises, it's better if you don't allow numbers to convert automatically to circles.
Don't return 'const' values
The const double return type of getArea() is no different to plain double - the const will be ignored (and that's a good thing).  So it's useless clutter to write it (and GCC will warn you, assuming you turn on a reasonable set of warnings).
Operators
What does it mean to subtract one circle from another?  In a geometry library, I'd want to get an annulus back (i.e. a circle with a hole cut out) or not be allowed to subtract at all.  Similarly for addition.
If you do choose to provide operators, you'll want to declare them with your interface (so this could be moved to a header).  And you should consider whether to provide the corresponding assignment operators (+= and -=).
On the positive, you have the correct argument and return types here.
Portability
Your environment clearly provides you with M_PI for a value of π.  That's not a standard identifier, and although it's a common extension, it's more portable to define your own.  Popular expressions producing π include 4 * std::atan(1) and std::acos(-1)  These are both compile-time constants, so cost nothing to the program's users.
A thing I like in the getArea() is that you write radius * radius and didn't get seduced by std::pow(radius, 2) - which is generally slower and less accurate than multiplication (it's more versatile, because it supports fractional powers, but we don't need that here).
Prefer C++ formatted output
The <iostream> header provides I/O with better type-checking than the C-style <cstdio> functions.  Consider providing a << operator to stream to a standard library stream.

Modified code

#include <cmath>
#include <iosfwd>

namespace corey
{
    class Circle
    {
        static constexpr double pi = 4 * std::atan(1);
        double radius;

    public:
        explicit Circle(double r = 0);

        double getRadius() const;
        double getArea() const;
    };

    Circle operator+(const Circle&, const Circle&);
    Circle operator-(const Circle&, const Circle&);

    std::ostream& operator<<(std::ostream&, const Circle&);
}

#include <ostream>

namespace corey {
    Circle::Circle(double r)
        : radius(r)
    {}

    double Circle::getRadius() const
    {
        return radius;
    }

    double Circle::getArea() const
    {
        return pi * radius * radius;
    }

    Circle operator+(const Circle& lhs, const Circle& rhs)
    {
        return Circle(lhs.getRadius() + rhs.getRadius());
    }

    Circle operator-(const Circle& lhs, const Circle& rhs)
    {
        return Circle(lhs.getRadius() - rhs.getRadius());
    }

    std::ostream& operator<<(std::ostream& os, const Circle& c)
    {
        return os << "Circle made with radius " << c.getRadius()
                  << " & area " << c.getArea();
    }
}

#include <iostream>

int main()
{
    using corey::Circle;

    Circle c1(2);
    std::cout << c1 << '\n';

    const Circle c2(6);
    std::cout << c2 << '\n';

    Circle c3;
    c3 = c2 + c1;
    std::cout << c3 << '\n';

    c1 = c3;
    std::cout << c1 << '\n';
}


This question is on the edge of being off-topic, there's really not much code to review here.

However your IAppUow interface has a number of flaws:

Naming: I don't see a need for the App part. I think a better name would be more like IUnitOfWork.
Inconsistency: You have IRepository<Customer>, and then IOrderRepository - why don't you have IRepository<Order> or IOrderRepository? When/if you do add repositories to your UoW interface, do you add a IRepository<Entity> or a IEntityRepository? This inconsistency makes it very hard to tell.

  If I need to add a new repository of whatever type, I have to change the UoW. Is this a good practice? If not, is there a better way?

An interface shouldn't be designed to change, as every change to an interface is a breaking change. I think you're mixing up the abstraction with its implementation; UoW encapsulates a transaction - and these things can be committed or rolled back. Thus, if I were to wrap the EF UoW into another layer of abstraction (I'll get back to that), I'd have a void SaveChanges() and void DiscardChanges() methods on the UoW interface.

  If I run Commit() { context.SaveChanges(); }, it will save the state of all the context's repositories. Is this a good way?

This is how Entity Framework works. DbContext is a unit of work; if you Dispose() the context before saving any changes, nothing gets to the database. If you SaveChanges(), the unit of work commits all changes made.

DbContext is an implementation of a unit of work - it exposes repositories (IDbSet<TEntity>) and a method to commit changes (and stuff about entity state management and model generation).

This might not be what you want to hear, but this answer sums up my thoughts pretty well: https://softwareengineering.stackexchange.com/a/214022/68834 - in short, you don't need the pattern if you're using an Object/Relational Mapper.


Sum of all arguments ever passed to accumulator

An alternative to the closure is to add an attribute to the function, so rather than:

lst = []
def accumulate(n):
    lst.append(n)
    ...

you have:

def accumulate(n):
    accumulate.lst.append(n)
    ...
accumulate.lst = []

It's a little more typing, but one advantage is that it allows easier access to the list so far from outside the function:

>>> accum = make_accumulator()
>>> accum(7)
7
>>> accum(8)
15
>>> accum.lst
[7, 8]

With the closure, this would be accum.func_closure[0].cell_contents.

Using indices is not a very Pythonic way to handle iterating over a list, and x = x + y can be simplified to x += y; compare:

...
length = len(lst)
for index in range(length):
    total = total + lst[index]
...

with:

...
for item in lst:
    total += item
...

There is also sum(lst), which the specification doesn't forbid.

  How can I think of writing pure functional code for above program
  (i.e., without any state change)?

I don't think that this can be achieved in a purely functional way as specified - you are explicitly told to use a list to store the values passed, so there will always be state, and the function you create will give different outputs for the same inputs depending on the previous inputs (no referential transparency).


Bright side

Your code gives the correct output and delivers on the premise of extensibility.

 Suggestions

Here are some suggestions:

The name key is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict with responsesByMultiples. Then It would have made more sense for the latter to be named keys. Personally, I'd prefer to call responses or rules.
These rules expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.
You can easily decompose a tuple this way:

for (multiple, response) in responsesByMultiples {
    ...
}

Calling the first element multiple is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability that n is actually a multiple of multiple. It would make more sense to me to name the first element of the tuples dividsor.
n is a bit too generic, use dividend instead.
You don't have to specify the type in isMultiple: Bool, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.
Instead of using (n % multiple) == 0, there is a nice syntax in Swift 5 :

n.isMultiple(of: multiple)

(this syntax exacerbates the problem mentioned in 4.)
To check that a String is empty, it is more efficient to check the .isEmpty property. Here is a benchmark that confirms it:

import Foundation

let array = (0..<1_000_000).map { _ in
    Double.random(in: 0..<1) < 0.8 ? "" : String("Hello".shuffled())
}

do {
    let start = Date()
    let result = array.filter { $0 == "" }
    let end = Date()

    print(result.count, end.timeIntervalSince(start))
}

do {
    let start = Date()
    let result = array.filter { $0.isEmpty }
    let end = Date()

    print(result.count, end.timeIntervalSince(start))
}

The execution times are respectively 44ms and 34ms.

 Putting it all together ❤

Here a version of your code that takes the previous points into account :

func fizzBuzz (
    number dividend: Int,
    rules: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]
    ) -> String {

    var result: String = ""

    for (divider, response) in rules
        where dividend.isMultiple(of: divider) {
        result += response
    }

    return result.isEmpty ? String(dividend) : result
}

 Further reading

You can find many implementations of this classic question on Code Review. Here is a quite informative one.


Caesar Cipher in Haskell, on every other character

I'm also in the (early) process of learning Haskell, so please take my advice with a grain of salt.

First, let's talk about your coding style

I am assuming the indentation is only messed up in your question, as the code in your post would not compile.
I am also going to assume that you are either supposed to implement the cipher recursively or don't know a better method, yet (map). You also seem not to know about function composition (using . and $). In case you do, you should generally* use it wherever possible (*unless it reduces readability, but I haven't seen such a case yet).
xs is not used to represent scalar (single) values, but values such as lists that can contain many x's. Pattern matching a list using cons is often written as x:xs, f:fs, etc.
Using guards to check the same value for equality multiple times is redundant. Using a case ... of expression is more concise and readable:

cipher x n = case x of
  'x' -> 'a'
  'y' -> 'b'
  'z' -> 'c'
  _   -> [xs..'z'] !! n
-- alternatively: cipher 'x' n = 'a' etc.

even (pos) can be written as even pos.
I think using guards instead of if .. then .. else would make your code more readable. Instead of

caesarCipherAux codedMessage pos (xs:s) n =
  if even (pos) then
    -- things
  else
    -- other things

write

caesarCipherAux codedMessage pos (x:xs) n
  | even pos  = -- things
  | otherwise = -- other things

Your use of whitespace is not always consistent (++ in lines 8 & 10).
Consider surrounding infix operators by whitespace to increase readability. In my opinion something like f (x+1) is fine, but | xs == 'x'='c' decreases readability.
Avoid ++. Appending lists repeatedly can get somewhat costly (in this case the cost is negligible, but when theres a better way why not choose it). Given that you only append a char, a better way of doing so is consing it: toUpper xs : codedMessage instead of codedMessage++[toUpper xs]. This means, of course, that the end result needs to be reversed: caesarCipher = reverse . caesarCipherAux [] 0 with function composition or caesarCipher = reverse (caesarCipherAux [] 0) without. In cases where you want to append two lists, such as two strings, you can use a list of strings, cons (:) the lists and concat them at the end.
Avoid !! and if you use it, make sure its safe. caesarCipher "Hello" 30 will result in an exception. Instead of [xs..'z'] !! n use something like

let abc = [xs..'z']
in abc !! mod (length abc) n

Unless abc is empty, this is safe. abc will be empty if xs > 'z', so you have to check that beforehand. Still, not using !! in the first place  would be better.

About the implementation

I think your implementation is a good effort for a beginner, but flawed. As long as letters are not shifted past z (or a, if n is negative), it works. It they are, your code either a) yields the wrong result or b) crashes.

a) You tried to implement wrapping letters by hardcoding cases for 'x', 'y' and 'z', but those are only correct for n=3. If n is not 3, the result will be incorrect: caesarCipher "xyz" (-1) is "XbZ" in your implementation (y + 3 = b, where y, b are numerical representations of 'y', 'b'). But it should be "XxZ" because y - 1 = x.

b) Applying caesarCipher to "xwz" 10 results in an exception (*** Exception: Prelude.!!: index too large) because ['w'..'z'] only contains four characters and you did not harcode a case for 'w' (or any of the other letters).

Also, your function does not handle characters outside of ['a'..'z']. I assume that this is outside the scope of your exercise.

Fixing it

Prelude contains ord :: Char -> Int and chr :: Int -> Char to convert a Char to Int and vice-versa. In conjunction with mod, which returns the remainder of an Integral division, those functions are enough to implement letter shifting accurately and safely. Consider this example (w/o function composition):

shift :: Char -> Int -> Char
shift ch n = chr x'
    where r  = 26 -- length alphabet
          a  = ord 'a'
          x  = ord ch
          x' = a + mod (x - a + n) r

works      = shift 'a' 26 == 'a'
stillworks = shift 'b' (-26) == 'b'
wontbreak  = shift 'c' (26 * 4234789) == 'c'

This implementation fixes both problems because it does not use unsafe functions such as !! and works on any character (no hardcoded cases). If you apply it to characters outside the 'a'..'z' range, it will still evaluate successfully and the result will be constrained to said range (which is probably not what you want, so only apply this function to characters that are in the alphabet). To shift upper case letters properly, convert them to lower-case first before applying the function, then they can be converted back (again, not using composition):

foo (x:xs) n acc
    | isUpper x = foo xs n ((toUpper (shift (toLower x))):acc)
    | otherwise = foo xs n (shift x:acc)

Finally, instead of checking for an even/odd number, you can take two characters at once; one will be even, the other odd:

foo []       = "null"
foo [x]      = "x is even"
foo (x:y:xs) = "x is even, y is odd"

Thats all, I think. I hope it helps.


Is it a good choice to define my own JSON util class like this?

Are you changing the fields that you expose from your objects depending on certain conditions?

On the whole it would be best to use reflection only as a last gasp. Gson works fine with collections in general see the documentation over at Google.

If you want to exclude some fields from serialization then you can use the @Expose annotation, as documented here. This requires you to annotate all fields that you want to serialize with the @Expose annotation, and to use a builder to instantiate your Gson Object like so:

Gson gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

In general try to limit how much you are working with the type Object and reduce as far as possible your use of reflection.


Simple name-drawer using Python and Tkinter

from random import *
from Tkinter import *

Wildcard imports are against PEP 8.  I realize that from Tkinter import * is the usual form expressed in the documentation, but it is still not recommended by PEP 8.

I see s7, s8, and m10 used in many places.  I know what they are only because I can see what the texts of your buttons are.  Ideally, every line of code should be clear without any context.  I would use names that are more clear.  Also, self.m is not a very descriptive name.  I would suggest that you use a better one, but I see that it isn't used anywhere except its definition.  Therefore, it should be taken out completely.

Your equals signs are a little strange.  I give you two rules from PEP 8:

  Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=,-= etc), comparisons (==,<,>,!=,<>,<=,>=,in,not in,is,is not), Booleans (and,or,not).

and

  Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value.

You seem to have those two rules switched up.  You have, for example, self.count_s7=0, but self.b1 = Button(..., text = ...).  Mind you, I mention = specifically, but you also break the rule with +=.

Your capitalization is a little messed up.  From PEP 8 on Method Names and Instance Variables:

  Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

You break that rule with self.Results and self.Quit.

get_names doesn't seem to be a fitting name.  It doesn't return anything; it sets the text of self.Results.  Perhaps set_names would be more appropriate?

I don't like that you define the class names within the methods.  What you could do, actually, is make your __init__ method take a dictionary as an argument with the class names for keys and the student names for values.  Then, for each key-value pair, define a button and a random color and give command as just a single method.  It's fairly hard to explain without code, so I'll give an example:

def __init__(self, master, students):
    ...
    i = 2
    for class_name, student_names in students.iteritems():
        students[class_name] = [student_names, 0]
        button = Button(self.frame,
            text='Get Random Name: {}'.format(class_name), width=50,
            command=lambda name=class_name: self.draw_from_class(name),
            bg='#' + hex(randint(16777215))[2:] # 16777215 is FFFFFF
        )
        button.grid(row=i, column=1)
        i += 1

def draw_from_class(self, name):
    class_info = self.students[name]
    self.draw_names(*class_info)

You could then do:

app = App(root, {
    'Science 7': ['Name1', 'Name2', ...],
    'Science 8': ['Kid1', 'Kid2', ...],
    'Math 10': ['Student1', 'Student2', ...],
})

That way, it is very easy to add more classes.

It is generally a good idea to use if __name__ == '__main__' for your module-level code if you don't want it to run when this file is imported.


At the end of the day, only you can tell what performs best. But there are two things that in most cases will help improve performance.
1. Reduce the number of queries.
Essentially, you do
DAL.group_table group = DB.group_table.Find(gid);
sharedFolders = group.sharedFolders_table.ToList();

And in the view, for each sharedFolders_table you diplay
sharedFolders_table.folder_table.folderName

That's one query for each sharedFolders_table.
So you end up having 1 + 1 + n queries.
No doubt, it's better to turn these into one. For example:
sharedFolders = DB.sharedFolders_table
                  .Include(s => s.sharedFolders_table)
                  .Where(s => s.groupId == gid).ToList();

But since you only seem to use folder_table.folderName it should be better yet to get only folder_table objects:
sharedFolders = DB.sharedFolders_table
                  .Where(s => s.groupId == gid)
                  .Select(s => s.folder_table)
                  .ToList();

(Note that this changes your model data type.)
2. Use a projection
These queries return complete entities. But in the end, you only display one field (let's ignore the fact that in reality you probably do more). So you may as well get that field only.
Reducing the number of fields in a query can considerably improve performance, especially when records are wide and many joins are involved. I often see people focus on reducing the number of records, but reducing the number of fields is equally important.
In your reduced example, it's enough to get only the names from the database:
sharedFolders = DB.sharedFolders_table
                  .Where(s => s.groupId == gid)
                  .Select(s => s.folder_table.folderName)
                  .ToList();

(again, this changes the model type)
Now you have one lean and mean query, instead of 1 + 1 + n wide queries.


When you call sum, make sure you start with 1 (and not 0).  Otherwise, you get an error of + 2 y_0 h / 3.  In case of (simpsons-rule cube 1 2 1000), this error is 0.000666....

Another way to rewrite the series is to group even and odd terms together, excluding the first and last terms.

(h / 3) * (y_0 + y_n + 4 * (y_1 + y_3 + ... + y_n-1) + 2 * (y_2 + y_4 + ... + y_n-2))

This gives us another possible implementation:

(define (simpsons-rule f a b n)
  (define h (/ (- b a) n))
  (define (y-k k) (f (+ a (* k h))))
  (define (next n) (+ n 2))
  (* (/ h 3.0) (+ (y-k 0) (y-k n) (* 4 (sum y-k 1 next (- n 1))) (* 2 (sum y-k 2 next (- n 2))))))


Calculate number of co-occurrences for two vectors

sum(d$rs & d$occ)
#[1] 2

The goal is "...simply counting the number of occurrences that the variables rs and occ appear together." If you feel that your code is long and cumbersome, the vectorization process of R is uniquely capable of speeding up the task without for loops and nested conditionals.

As mentioned in the previous answer, R coerces certain classes onto vectors when specific functions are called on them. The two columns in question are both a series of 1's and 0's. They are numeric values. I would like them to be thought of as TRUE's and FALSE's to evaluate my logical condition. Thanks to the brevity of R code I do not have to literally ask R to do that. As soon as I use the & operator, R will immediately treat all 0's as FALSE and other numbers as TRUE logical values.

Finally, sum does a similar action but in the opposite direction. It coerces (forces the class) to numeric in order to calculate the sum. It treats TRUE as 1 and 0 as FALSE. In the case of this code, Many complicated relationships are being handled by the R computing engine and, thankfully, not by us.

If you would like the other two values for unique and zero use:

sum(xor(d$rs, d$occ))
[1] 4
sum(!d$rs & !d$occ)
[1] 14

The function xor tests what is called the "exclusive or". So the code read aloud would be "How many pairs have a one in rs or occ, but not in both." The operator ! negates what comes after it. That code would read, "How many pairs have a value that is not 1 in rs and not 1 in occ."


Project Euler 39: Integer right triangles

You are using a dictionary data = {"most": 0, "num": 0} where you could just as well use local variables. The locals would be more readable and faster.
The built-in max function is convenient when looking for a maximum. You could write find_most_solutions_upto like this:

def find_most_solutions_upto(limit):
    return max(xrange(limit/2, limit + 1), key=find_pythagorean_triples)


Storing Temporal Message Lists in ASP.NET MVC TempData

On the whole the approach is fine, but do not use TempData unless you're looking to populate this information across redirects. TempData comes with a host of issues, and its behaviour isn't quite what you think.

ViewData, on the other hand, is designed exactly for this purpose but comes with the caveat that it doesn't persist across redirects.

Therefore, if you're looking to put something in place which allows developers to push messages into your views easily, you need to expose the ability to put data in either ViewData or TempData, depending on whether they want to redirect or not.

Another option is to clear the TempData entry manually after the call has finished, but I wouldn't recommend this approach.

As a final point, your function names SetMessage and SetErrorMessage are misleading in that they imply you've got one spot only for the message. To me, as a user of your function, when doing this:

this.SetMessage("Foo");
this.SetMessage("Bar");

I would assume that my message is now set to "Bar", but behind the scenes it's a list with both "Foo" and "Bar". I'd recommend changing your function names to AddMessage and AddErrorMessage instead, which implies that behind the scenes there is a collection of elements.


Quick comment: If you have code which is supposed to run when you call the script (in your case its the "run the game" part of the code), its good practice to put it in a main() function and call the main function rather than keep all that code at the highest level of the file. At the bottom of the file, it would look something like this:

def main():
    functions_to_play_math_game()

if __name__ == "__main__":
    main()

When a python script runs, it gets a __name__ attribute depending on how it was called. If it was run through the command line (with $ python my_script.py), the __name__ attribute gets set to "__main__". So the second part of my code sample checks if the __name__ attribute indicates the script is being called to run, and if so, executes the code inside main().

The reason this is important is because when you import a module in python, it runs all the code inside that file. Now, if the file only contains function definitions, nothing out of the ordinary happens. But if you imported your file into another file, at the import my_file line your game would start running because there is no safeguard to prevent it from going. The catch is that when being imported, __name__ is not set to __main__ like it is when you call the script from a command line. So, if you have this safeguard at the bottom of your code, it wont run when its imported.


Without more code / context it is hard to give much of an answer, but a few comments:

You can make ammo a read only attribute by using attr_reader :ammo then inside the class or module you can access it using @ammo just like you do in your initializer.
Don't over-complicate your code. Given what you have now there is no reason to do any of what you want. Wait till your code gets complicated enough that you need to break it up then you won't just be guessing what the best option is.
Consider using delegation rather than inheritance or modules. So your gun could have an ammo_clip attribute referencing an AmmoClip instance.
This code:

Rof = {:sustained => rand(3..9), :rapid => rand(5..9),
       :cyclic => rand(1..200), :cease => 0}

probably doesn't do what you expect. Those random numbers will be calculated once at program startup, not each time a gun is fired.


Multithreaded app for writing to a MySQL database

Yes, your code will use pooling.

You might, for the sake of server efficiency, use a smaller MinimumPoolSize (say, 20), and a larger MaximumPoolSize (something a little larger than your maximum number of threads).

You probably don't need all those connections all the time.  If your threads do anything significant between their uses of the function you've shown, a significant number of your connections will be idle.

Unless you're sure you need all those connections all the time, you should reduce the RAM and thread burden on your server with a smaller MinimumPoolSize.


For this, I am going to go through your program in the order it is written:

Don't use if twoplayer == False:.  You can simply say if not twoplayer:  You don't even need that, though the first time because you do the same thing in the if and elseblocks`.
You can use " ".join("_" * lengthword) instead of  for i in range(1, lengthword): userguess.append("_ ").  Besides making it cleaner, you weren't adding enough underscores.  The second argument to range() is exclusive.  Imagine if the length of the word is two.  In that case, range(1, 2) returns [1] because the second argument is exclusive.  That has length 1 instead of the same length as the word: 2.
Don't use wordarray.remove(wordarray[i]).  Instead, use wordarray.pop(i).  If you use .remove(), the first occurrence of the word will be removed, not necessarily the one you want to be removed.
When you ask "Do you want to play 2 player?", you account for "y" and anything else.  What if the user says "yes"?  It would still count as no.  Instead, you should use a while loop:

twoplayer = input("Do you want to play 2 player? [Y/N] ")
while twoplayer.lower() not in ("y", "n"):
    twoplayer = input("[Y/N] ")

Instead of setting twoplayer inside of the if and else blocks, you can just do twoplayer = ("n", "y").index(twoplayer.lower())
If the word is too short, you don't want to call pickword() again because pickword() asks "Do you want to play 2 player?"  If the word is too short, that doesn't mean the user wants to change his mind on that question.  Instead, use a loop:

while len(word) < 3:
    print("That word is too short")
    word = input("Player 1, enter the word you want player 2 to guess, don't let them see! ")

How do you know how many lines to print?  Instead of printing an arbitrary number of lines, print("\033c") will clear the terminal.
You call start(word, twoplayer) in both the if and the else block.  That is a sign that it shouldn't be in either one.  Put it after both blocks so that you aren't duplicating code.
While we're at that point in the program, you want only one line in your try: block: word = random.choice(...).  twoplayer should be defined as I outlined above, so we don't need that here at all and start(word, twoplayer) will be outside of the if and else blocks, so we don't need that.  Besides, the only reason you want the try block is because you are dealing with a file.  If anything else is throwing an error, you want the traceback because it shouldn't be.
Don't use a bare except:  You have certain errors that you think you might get; list them here.  In this case, it's except IOError:
sys.exit(), when given an argument, uses that argument as the exit code.  In this case it is failure, so you should use sys.exit(1).
Your check for guess1's validity is not the best.  To make sure that it is one character, use len(guess1) != 1 as the check.  Also, guess1.isdigit() is probably not the only thing that is invalid.  For example, $ shouldn't be in the word, right?  Instead, use not guess1.isalpha() to make sure it is an alphabetic character.
Instead of using recursion and typing out all of those variable names, use a loop:

print(' '.join(userguess))
guess = input("Enter your guess: ")
while len(guess) != 1 or not guess.isalpha():
    print("Invalid input")
    guess = input("Try again: ")

checkuserguess(wordarray, userguess, guess, usedletters, tries, word)

You have duplicate code in lose() and win(): Would you like to play again.  Instead, define a function that asks that question, and use it in lose() and win().  Make sure that in that function you use if again.lower() == "y": as you did in lose().  if again == "Y" or "y": does not work how you would expect it to.  See this StackOverflow post for why.
You check if "_ " is in userguess, but you should be checking for just the underscore, not the underscore with a space.  If the underscore is at the end of the word, there shouldn't be a space.  If there is, you're doing it wrong and you shouldn't depend on it.

This is my first complete review, so if anyone has suggestions, I would be happy to modify it.


Some small changes I'd recommend listed below:

D.R.Y.

Why don't you call event.preventDefault before your control statement since it will be called in both the if and the else case?

Avoid doubling up on lookups

I am not very experienced in jQuery, but can't you make some if checks not double up on lookups?

var liGroup = $groupSiblings.find('li')
if (liGroup.hasClass('is-expanded')) {
     liGroup.removeClass('is-expanded');

Also check the specs on removeClass()..perhaps you can call removeClass() without checking hasClass?

Formatting/Readability

Your code is difficult to read without more formatting. For example, it's not clear which if matches up with the else from skimming the code. It shouldn't be necessary for a reader to parse parens/brackets to figure out what the if...else pairing is.

Also a few more comments would be helpful. For example, comments describing your control statement branching in a few words would be welcome.


Welcome to Code Review SE, nice first question! Here are some of my comments, not pertaining to performance:

There's no reason to import modules in the body of scrape_coin_marketcap(). Just do it at the top of the source code file. If you need to be sure the modules are present at all, you can catch ImportError:

import sys

try:
    from bs4 import BeautifulSoup
    import requests
    import pandas as pd
except ImportError:
    sys.exit("This script requires Beautiful Soup 4, Requests and Pandas.")

Note: I'm using sys.exit() here instead of print(), because I'm assuming this is a standalone script and an ImportError should therefore be fatal.
The URL for the webpage is unlikely to change in the future, and isn't supposed to be modified at runtime, so you should mark it as a constant variable. Constants use the UPPERCASE_WITH_UNDERSCORES naming convention:

HISTORICAL_DATA_URL = "https://coinmarketcap.com/historical/"

This comment:

#Download HTML of links to historical CoinMarketCap data

... is pretty pointless. Anyone familiar with Python doesn't need that comment to understand what the snippet of code below it does. Only add comments to difficult to comprehend code, or to snippets that need extra attention for whatever reason.
The following pattern:

my_list = []
for x in some_iterable:
    my_list.append(some_function(x))

... is a good candidate for a list comprehension:

my_list = [some_function(x) for x in some_iterable]

... so in your case:

raw_links = [link.get("href") for link in soup.find_all("a")]

In fact, the part where you remove non-historical links could benefit from a list comprehension too:

historical_links = [
    "https://coinmarketcap.com/" + link for link in raw_links
    if "201" in str(link)
]

Don't mix single and double quotes. Either choice is valid, but mixing them is a bad idea. As an exception, you are encouraged to use single quotes if you need to output literal double quotes, and vice versa.
Unless you need access to the result of r.text later, don't bind it to a variable.
Debug / error messages should not be sent to stdout, but to stderr. You can do that by explicitly passing sys.stderr as a parameter to print():

import sys

...

print("Loading Packages...", file=sys.stderr)


You are right, the code could be tigher

This

var action = "";
if  {
    action = "expand";
}
else {
    action = "expandheatmap";
}

could be reduced with a ternary operation to:

var action = (activeTab.toLowerCase() == 'table') ? 'expand' : 'expandheatmap`;

Since you repeat this in every handle, you should consider building a function for this, in case the logic ever changes.
I am a bit confused by your code, you seem to build the href, get the href, modify that string and then set the href again ? Why ? The following should work in my mind ( I took the last click handler ) :

$(".gridoptions-anchor").click(function (e) {
    var href = "/home/xx/Index" + "/?columnchooser=1"
    var action = (activeTab.toLowerCase() == 'table') ? 'expand' : 'expandheatmap`;
    $(this).attr("href", href  + "&from=" +action + "&expand=" + Expand + "");
});

This brings me to my next point; activeTab, action, and Expand are not defined with var in this code
Finally you could consider a dedicated URL building function to have the string concatenation in one place:

function buildURL( href, action, expand, addTabActive )
{
  var tabActiveParameter = addTabActive ? ( '&tabactive=' + action ) : '';
  return href + "&from=" + action + "&expand=" + expand + tabActiveParameter;
}

Which brings me to my last point if tabactive shows the action, then activetab would be a better name.


Match all youtube links in a string of text

[^\s] is effectively just \S
For checking against youtu.be links, you can have:

youtu(\.be|be\.com)

If you do not want to store every matched group, use (?:...)
[A-Za-z0-9_] can be simplified to \w.
Use a different delimiter than / so that you won't have to escape it in pattern.

Therefore:

preg_match_all(
    '@(https?://)?(?:www\.)?(youtu(?:\.be/([-\w]+)|be\.com/watch\?v=([-\w]+)))\S*@im',
    $this->content,
    $matches
)


There's no need to predeclare the subs (sub whatever;).
There's no need to assign the initial values to %resulthash.
my $filename; does the same as my $filename = undef;. There's no need to specify the undef.
Hash keys are autoquoted if they are simple (i.e. follow the same rules as variable name). Instead of $resulthash{'IPADDR'} you can type just $resulthash{IPADDR}.
shift in a sub operates on @_. So you can just write my $hash = shift;.
Instead of shifting @_ several times, assign all the variables at the same time: my ($key, $value) = @_;.

Plus, you're comparing $fields[0] to various strings, maybe a "dispatch table" would be a bit clearer. See my version of the script:

#!/usr/bin/perl
use strict;
use warnings;

use Getopt::Long;
use Tie::File;

my %resulthash;
my $filename;

GetOptions ('filename=s' => \$filename,
            'IP=s'       => \$resulthash{IPADDR},
            'NETMASK=s'  => \$resulthash{NETMASK},
            'GATEWAY=s'  => \$resulthash{GATEWAY},
            'DNS1=s'     => \$resulthash{DNS1},
            'DNS2=s'     => \$resulthash{DNS2})
or die 'Error in input values';

open my $fd, '>>', $filename
    or die "Cannot open file $filename";

tie my @array, 'Tie::File',  $filename
    or die "Cannot tie file '$filename': $!";

for my $line (@array) {
    my @fields = split /=/, $line;

    { BOOTPROTO => sub { $fields[1] = '"static"';
                         $line = join '=', @fields; },
      IPADDR    => sub { $line = setValueForField('IPADDR', @fields); },
      NETMASK   => sub { $line = setValueForField('NETMASK', @fields); },
      GATEWAY   => sub { $line = setValueForField('GATEWAY', @fields); },
      DNS1      => sub { $line = setValueForField('DNS1', @fields); },
      DNS2      => sub { $line = setValueForField('DNS2', @fields); },
    }->{ $fields[0] }->();
}

untie @array;

addMissingValues(\%resulthash);

close $fd;

sub addMissingValues {
    my $hash = shift;

    while (my ($key, $value) = each %$hash) {
        createNewField($key, $value) if defined $value;
    }
}

sub createNewField {
    my ($key, $value) = @_;
    print {$fd} join '=', $key, $value;
    print {$fd} "\n";
}

sub setValueForField {
    my ($fieldname, @fields) = @_;

    $fields[1] = $resulthash{$fieldname};

    return join '=', @fields;
}

You can also keep the dispatch table outside of the loop, but you need to pass parameters to the callbacks.

my %DISPATCH = (
    BOOTPROTO => sub { $_[1] = '"static"';
                       join '=', @_ },
    IPADDR    => sub { setValueForField('IPADDR', @_) },
    NETMASK   => sub { setValueForField('NETMASK', @_) },
    GATEWAY   => sub { setValueForField('GATEWAY', @_) },
    DNS1      => sub { setValueForField('DNS1', @_) },
    DNS2      => sub { setValueForField('DNS2', @_) },
);

for my $line (@array) {
    my @fields = split /=/, $line;
    my $sub = $DISPATCH{ $fields[0] };
    $line = $sub->( @fields) if $sub;
}


A cross platform function to get current time in seconds with precision of micro second

Leveraging the standard library is the best way to obtain cross-platform code, so you're on the right track. The problem is that your doesn't compile with one of the compilers I've tested it with (clang 8). Using auto would make your code simpler and avoid problematic conversions:

double time_in_seconds() {
    // now compiles with both clang 8 and gcc 9
    auto tp = std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now());
    auto tmp = std::chrono::duration_cast<std::chrono::microseconds>(tp.time_since_epoch());
    auto time_micro = tmp.count();
    return time_micro / 1000000.0;
}

Besides, there is no need for those intermediary, ill-named variables tp and tmp. If your function is contained in an implementation file (.cpp), where it should be, importing the std::chrono namespace is perfectly fine, and it becomes quite readable:

double time_in_seconds() {
    using namespace std::chrono;
    return duration_cast<microseconds>(system_clock::now().time_since_epoch()).count() / 1000000.0;
}

auto would also be a better choice for the return type:

auto time_in_seconds() {
    using namespace std::chrono;
    return duration_cast<microseconds>(system_clock::now().time_since_epoch()).count()
           / 1000000.0l; // long double literal
}

auto here avoids any discrepancy between the promotion done in the arithmetic operation (the division by 1.000.000) and the promotion to the return type. For instance:

long double foo() { // seemingly long double precision
    return some_integer / 100.01f; // actually float precision
}

A last improvement I think of is the use of enhanced literals:

auto time_in_seconds() {
    using namespace std::chrono;
    return duration_cast<microseconds>(system_clock::now().time_since_epoch()).count()
           / 1'000'000.0l; // you can separate thousands with '
}