Representing an adjacency list (graph) using a hash table of lists

General Comments

Write your code for readability.

You don't normally see templates written like this:

template <typename T, typename K> void printGraph(graph<T, K>& g)

It pushes the information you want all the way to the right. Normally, I would expect to see the template code on the first line, followed by the object it templates (looking like a normal bit of code):

template <typename T, typename K>
void printGraph(graph<T, K>& g)

The space between > when closing a template has not been needed in over 5 years. Let it be consigned to the big bit bucket in the sky.

 list<pair<T, K> > >

I notice your lack of using std:: when declaring your types.

 unordered_map< T, list

This not only means you have using namespace std; in your code, but that you have it in a header file (or you have a lot of using XXXX; but causes the same issues). The use of using namespace std; in normal code is considered bad practice. But the use of it in a header file is so bad that people will ban your code from projects. You are basically infecting any code that includes your header. This can lead to subtle, impossible-to-find errors. Don't do it.

I would also prefer if you would use an initial capital letter for type information. The most important part of C++ is the type system. Being able to identify types easily is essential. Thus, most people use an initial capital letter to identify user-defined types, while an initial lower-case letter identifies an object.

Build your types from smaller types. This will make it easier to maintain your code as it localizes changes. For example, rather than using std::pair<T, K> as your edge definition, prefer to use a named type Edge. That way, if you change the definition of the type, you only have to change it in a single location and not trawl through your code looking for all uses. Also, using a name like that provides context and meaning, which in turn makes your code easier to read.

template <typename T, typename K>
struct Graph
{
    using Edge        = std::pair<T, K>;
    using EdgeList    = std::list<Edge>;
    using AdjencyList = std::unordered_map<T, EdgeList>;

    AdjencyList adjList;
    bool        directed = true; // use real bool(s) not int.
};

Design Comments

You are completely ignoring encapsulation. Your functions may work, but because your data is completely exposed, there is no protection from a bad coder coming along and breaking your constraints. Your methods are supposed to be the only way to manipulate the state (so it can be controlled).

Because of this, your code would fail any competent code review and not be allowed into the code base.


You're building a navigation, however there are no links. It's highly recommended to use anchor tags for linking purposes.

Your naming is a bit loose. What is personal in your context? Please specify that. Even something like personal-navigation is quite loose, but still better.

I've changed your markup a bit to reflect my small suggestions. Note that I changed the ID's from your list items to classes. ID's are only for elements which will occur only once a page in any situation. You can't say that for sure for single navigation items.

Info

Orders

Models

Balance


This yet another way to do it:

sed -r '1{s/$/ /;s/ / \n/g};:a;$!N;s/$/ /;:b;s/\n(.*\n+)(\S+\s)/\2@!@\1/;tb;s/@!@/\n/g;${s/ \n/\n/g;s/\n+$//;q};ba'

This method is somewhat faster and only uses single delimiter which may be crafted to be unique. i.e. @!@ in this example


React onDrop function for a task manager

A Person class encapsulates the attributes/methods and logic for the Person object. Currently inherits from Object, but you can at any time extend this logic by creating an new super class or children and distribute the logic between those hierarchies.

class Person extends Object {
    constructor(props) {
       super
       this.name = props.name
       this.chores = props.chores
    }

    addSubject() {
      if (this.isFound) { return new People().push(person) }
      // your choice to either create a chore class or write some subroutine
      else { person.chores.forEach( chore => chore.addChore ) }
    }

    // either pass targetPerson as param or add it to the Person object as attribute
    isFound() { this.name !== this.state.targetPerson }

}

people = [ new Person('Grace', 'clean kitchen', 'wash dog'..), etc..]

I also believe the onDrop subroutine should just have the responsibility of dropping person or returning a new people object. It would be an instance method of the People class

class People extends Object {
    drop = () => {
      this.each( person => person.addSubject() )
      // etc...
    }

}


Arduino Sketch for sending sensor turn on/off to computer

If I understand correctly, your goal is to report all state changes; a 500 ms blackout is undesirable. If I am correct, read on.

You don't need the nextTime array at all. Change the state array from false/true to LOW/HIGH:

level = digitalRead(i);
if (level != state[arrayIndex]) {
    state[arrayIndex] = level;
    serialWrite(i | (level << 8));
}

(I am assuming that LOW == 0, and HIGH == 1).

Regarding performance: the code runs a busy loop, which is usually undesirable, especially in the embedded world. I seriously recommend to connect your pins to an interrupt, and rewrite the code into a reactive model.


Instead of hardcoding the characters, and their escape values specifically in your .replace call, you can pass a callback function for the replacement. I suggested that you dive into encodeURI:

So, something like:

function escapeStr(_str) {
  return _str.replace(/([%'"])/g, encodeURI)
}

function unescapeStr(_str) {
  return _str.replace(/(%(?:2[257]))/g, decodeURI)
}
const e = escapeStr, u = unescapeStr;
console.log( e("string") );
console.log( e("some\" char%s") );
console.log( u("string") );
console.log( u("some%22 char%25s") );


Replace the AtomicInteger with a Semaphore holding maxCunnccurent (maxConcurrent, right?) permits. So :

reqcnt = new Semaphore(maxCunnccurent);

Now, each time you get a filter request, you try to get a permit. If you do get a permit, you go ahead and filter, making sure that afterwards you release the permit again. If you don't get a permit, you send your error response :

boolean acquired = reqcnt.tryAcquire();
if (!acquired) {
    ((HttpServletResponse) resp).sendError(TOO_MANY_REQUESTS, EXCEED_MAX_REQUESTS_MSG);
    return;
}
try {
    chain.doFilter(req, resp);
} finally {
    reqcnt.release();
}


excel vba udf: entire column as fn parameter

What you have there is equivalent to =SUM(A:A) - which runs much faster as a native Excel function. Always use Native Excel in Excel itself before resorting to VBA.

As a general note: if you are going to do something bespoke - convert the range to an array and work with the array. This has a significant performance improvement for a number of reasons which have been explained many times on this site. The key ones are that you are not switching between the Excel model and the VBA model each loop and that you can work with data types instead of objects.


inF = gzip.open(FILE, 'rb')
    s = inF.read()
    inF.close()

That reads the whole uncompressed data into memory. Of course it takes 60GB of memory.

Looking at the documentation for gzip, it has this example of compressing a file:

import gzip
import shutil
with open('file.txt', 'rb') as f_in, gzip.open('file.txt.gz', 'wb') as f_out:
    shutil.copyfileobj(f_in, f_out)

If you switch that round to:

import gzip
import shutil
with open('file.txt', 'wb') as f_out, gzip.open('file.txt.gz', 'rb') as f_in:
    shutil.copyfileobj(f_in, f_out)

then I think you'll find the memory usage is much lower.


I created a sorting algorithm, called Grid Sort

Zero based indexing

Counting: when the index, or the position, is dependent on the item. Count from one. (Zero-based index is mathematically wrong.)

I will disagree. The index does not represent a count but rather it is a position. When we measure something we start at 0. For example a length of 5 units. Unit 0 the 1st unit is at 0 to < 1, and the last unit, the 5th is at 4 to < 5. The set of 5 units does not contain the unit 5.
It is not mathematically wrong to use zero based indexing, what is wrong is using the index to represent a count.
Array V Grid AKA hash table

Grid: when the index, or the position, is independent on the item. (e.g. JavaScript array)

I think you understanding of how arrays work is leading to some bad assumptions.
Arrays
Computers use RAM that is a continuous array of addresses. We use arrays because they are very fast when we need to get or set a item at an index.
To locate an item we get the RAM address of the array and add the index multiplied by the size of each item (JS arrays hold references so all array items are the same size) . In one addition and multiplication (a shift if item size is a power of two) we have the memory address of the data we want.
Almost all modern CPUs have special instructions (indexed addressing) to speed up array use.
Hash table
A grid is a little more complicated.
As the index can be any value we can not just offset a RAM address to find an item. We need to know where the item associated with an index is in RAM. That means that another array is needed to hold all the indexes and RAM addresses.
So if you want the item of grid index 10000000, we need the address of the index 10000000 which must be found by searching the array of indexes one at a time. Then we can get the RAM offset of the item we are after.
However computers have been around for a long time and some cleaver people have come up with ways to make "grids" somewhat faster. In javascript we call them Map
in computer science we use the term hash table.
Hash tables avoid the need to search for the index by applying a hash function to the index (key). This provides an offset that we can use to get the RAM address of the data we are after.
Still slower than an array as the hash function needs to be applied each time we index into the table, its a lot faster than searching all indexes each time we want an item.
When JS arrays are not arrays.
On a side note. JavaScript arrays come in two flavors

Dense arrays, each item is held one after the other in a continuous section of memory.
Sparse arrays. Sparse arrays look from the code perspective like dense array, but under the hood sparse array are actually hash tables.

A dense array is converted to a sparse array if you add an item above the array length. Different engines have different rules but generally its a bad idea to add items to an array at random indexes (as you do in your grid sort)
Review
I am not going to review your code as I think it is moot if you consider the above information.
I will say, you saw some institutionalized flaws and you created a better solution (sadly your assumptions were off). You demonstrate an initiative and a healthy skepticism of the status quo.
Most people will just keep at the same old same old and nothing great ever comes from that.
Keep at it.


Counting integers that are within intervals

If you sort your values, you can then make an iterator on the sorted list, forward it to the lower limit, count until the first value is reached that is larger than the upper limit and discard all further values.

The sorting will add \$\mathcal{O}(n\log n)\$ time complexity, but if you have a lot of values larger than (all) your upper bounds, you could get this back.

An implementation using itertools could be:

from itertools import dropwhile, takewhile

def graipher(scores, lower, upper):
    scores = sorted(scores)
    for l, u in zip(lower, upper):
        s = iter(scores)
        yield sum(1 for _ in takewhile(lambda x: x <= u, dropwhile(lambda x: x < l, s)))

Since the scores are now already sorted, you could even use bisect to find the right indices to insert the upper and lower limits. The difference between the two indices will give you the number of values in range:

from bisect import bisect_left, bisect_right

def graipher2(scores, lower, upper):
    scores = sorted(scores)
    for l, u in zip(lower, upper):
        yield bisect_right(scores, u) - bisect_left(scores, l)

Both functions are generators. You can just call list() on them to consume them into a list, giving the same result as your code:

if __name__ == "__main__":
   scores= [5, 8, 7]
   lowerLimits = [3, 7]
   upperLimits = [9, 7]

   print(check(scores, lowerLimits, upperLimits))
   print(list(graipher(scores, lowerLimits, upperLimits)))
   print(list(graipher2(scores, lowerLimits, upperLimits)))

Finally, Python has an official style-guide, PEP8, which recommends using lower_case for variables and functions.

When running your function and my two functions on an input of the maximum defined size for scores and a single pair of limits, I get the following timings:

check: 249 ms ± 3.84 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
graipher: 77.3 ms ± 950 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
graipher2: 53.9 ms ± 772 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

When using a scores of length 10 and the maximum defined size for the lengths of the limits, I get:

check: 2.8 s ± 112 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
graipher: 246 ms ± 2.77 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
graipher2: 73.1 ms ± 612 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

And finally, when using the maximum defined size for both scores and the limits, only graipher2 finishes in a reasonable time (I stopped the other ones after a few minutes):

graipher2: 247 ms ± 4.94 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So, to summarize, sort your scores and use bisection.


Not only is there code that does this type of stuff already out there, freely available. This question has been asked and answered a couple of times before on this site already. This is one such example.

However, given that the answers currently posted here are either incomplete or, IMHO, wrong (suggesting bad practices, or providing incomplete info), I'll post a short review of mine here, too.

You have a simple, procedural script. There's nothing wrong with that, per se. Although, nowadays, people will tell you to pour your code into objects and let each class do its own, specific task.
Why should you use objects here? Well, that's really down to what kind of project you're putting together: is the site going to be a fully dynamic LAMP driven site? Is the code likely to grow, or is it probable that, as you go along, new features will be added to your site? Then yes, you should look into writing your own classes, or adopt a framework (ZendFW, Symfony2,... there are tons to choose from).

If the amount of PHP you'll be using is relatively small, and its role won't exceed simple user input checks and some DB connectivity, then OO code is just going to add clutter, and bloat.

On the code
Connecting to the DB, and executing queries alongside code that actually generates output for the user/client is one of the main reasons why PHP is said to be a badly designed language. Yes, PHP allows you to write that kind of code, but you should know that it's actually seen as bad practice. A saw doesn't prevent you from sawing off the branch you're sitting on, but that doesn't mean it's a good idea to do so... Same thing applies to programming.

If you don't require object-oriented code (yet), at least create functions to handle the DB stuff, put them in a separate file, and call the functions when you need them:

require 'db_functions.php';//or require_once
$db = getDbConnection(
    array(
        'user'  => 'username',
        'pass'  => 'yourpass'
    )
);

Perhaps look into ways to keep the actual login credentials oustide of your code.

Escaping and assigning
I cannot, for the life of me understand why you would do anything like:

$name = $con->real_escape_string($_POST['name']);

with all of your post values. All those values belong together: they represent the data the user posted to your script, to validate and process. Why would you assign them to individual variables? keep that data as a whole.
If you want to check if an array has all values/keys set, then please use isset and then compare the values to an empty string. empty has a couple of oddities you should be aware of.

In this case, validating the post data can be easily done in a single loop:

$keys = array('name', 'username', 'email', 'pass1', 'pass2');
foreach ($keys as $k)
{
    if (!isset($_POST[$k]) || $_POST[$k] == '')
        exit();//<-- more on this later
}

Code like this can be easily poured into a function, to which you can pass both the array to check ($_POST) and the keys to check ($keys). Just 2 simple arguments, and you never need to write code assigning and checking variables again, just a single function call will do.

Now, the real_escape_string calls really are a bad idea. Quote chars, slashes... they're all allowed in email addresses. calling real_escape_string means that there is a chance that you're screwing up perfectly valid user input, and rendering it invalid. don't.

Using prepared statements here would be the only proper way to go: don't process the input a user gave you. If the input is anything other than perfect, assume the input is invalid or possibly malicious.

Avoid too many regex's
Checking for a password that contains both digits and characters can be done through regex, but that might not be the best tool for the job. The actual benchmarking is your job, but a regex often is slower than a simple loop, checking if a char is numeric or not.

Either way: you are using 2 regular expressions for something that can be easily done with just one expression. I've posted an answer here which goes into more details on the matter.

re-assigning again?
After validating the input (that, as I explained above, you may have rendered invalid yourself!), you then check variables like $emailValid again. That really ought to set off alarm bells.

Just think about it: you check some things. If the very first thing you checked showed you the user sent invalid input, you still procede to check, validate, reassign all other values, only to then again check if all input is valid.
That's doing the same thing twice, isn't it? DRY (Do not Repeat Yourself) is a common expression/piece of advice in programming. Your code basically repeats the most basic input validation task. That can't be good, now can it?

That's why throwing an exception is preferable, and that is also why separating output code, and logic/db related code into (at least) functions. These functions (functional units, as their name suggests) could be written to throw exceptions, which will then determine the output message the client will get to see.
Here's a basic example to clear this up. Remeber how I mentioned a function to check if all POST params are set? Here's how that would work in your case:

function checkKeys(array $data, array $keys)
{//note the type-hints!
    foreach ($keys as $k)
    {
        if (!isset($data[$k]) || $data[$k] == '')
            throw new InvalidArgumentException($k.' parameter not set');
    }
    return true;
}
//your code:
try
{
    checkKeys($_POST, array('name', 'username', 'email', 'pass1', 'pass2'));
}
catch( InvalidArgumentException $e)
{//catch Exception works, too
    echo 'Error: ', $e->getMessage();
}

That should be enough to get you started for now ;-P


Handling response from another microservice

In fact, your error handling is quite messed up: in the cases for server error and default you throw an exception, which you immediately replace with a different exception in your own catch block. I don't think that's what you meant to do. Furthermore, you only close() the response object in the exception case, but not in the success branch...

Nevertheless, the throwing of a WebApplicationException leads me to believing that we are in a RESTful application here. Thus, the best way would be to declare an excepton mapper to handle the underlying ProcessingException (which is the only one your catch-all-block should encounter) and do not do the handling internally. For exception mappers, here's a tutorial to start with: https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-en/cn/part1/chapter7/exception_handling.html  (but you will find a lot more resources using your favourite search engine.)

Having this out of the way, the only thing for your method to do is using a try-with-resources block for the response:

public Message getMockMessage() {
    try(Response response = this.webTarget.request().get()) {
        switch (response.getStatusInfo().getFamily()) {
            case SUCCESSFUL:
                return response.readEntity(Message.class);
            case SERVER_ERROR:
                throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
                        Response.Status.BAD_GATEWAY);
            default:
                throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
    }
}


Simplify multiple jQuery click functions

You are correct, you can have one function binding click events to all of your .btn elements.
Working Fiddle Example:
$('.btn').bind("click", function(event) {
  event.preventDefault();
  var index = $(this).parent().index();
  $('.carousel').css({ 'left': '-' + (index*100) + '%' });
});

jQuery documentation about index().
Describing what's being suggested:

Bind the click to the .btn class and within the click event you ascertain the index position:
I've opted to use bind() since it's performance efficient when compared with click().
Another reason is the fact that all your elements share the same class, so, you only need to bind a click event to the class instead of attaching a click handler to each .btn.

Use the index and multiply it by 100 as to get the desired left value:
This way you can easily ascertain the correct value since you have a direct relation between the anchor's parent index and the desired left value.

Using event.preventDefault(); to prevent the browser from following the href:
With this, you tell the browser to leave the href attribute alone, thus preventing it to bubble up.

Safe to use the minus signal all the time, since 0 and -0 is the same thing.

In order to further improve the function, and if using the lastest jQuery, I would give an id to the ul element, thus losing the .btn class, having the click event binded to a single DOM element thru delegation:
$('#myUL').on("click", "a", function(event) {
  event.preventDefault();
  var index = $(this).parent().index();
  $('.carousel').css({ 'left': '-' + (index*100) + '%' });
});

jQuery documentation about on().
Useful reading: Why use jQuery on() instead of click().


Firstly, a bit of humorous wordplay: witch = itch = burn; "She's a witch! BURN HER!" I think you meant "which" in this context. Now that is out of my system, on to the review :)

Why are you extending the stdClass? This is the class reserved for typecasting variables as classes. It is just a wrapper that has no benefits of being extended from. If you are just trying to create a normal class then just drop the extends stdClass bit. Its unnecessary.

Additionally, where did properties $first_name and $last_name come from? They were not declared. This means they either are coming from the parent class, which is impossible as the stdClass is empty, or they are defaulting to the public scope. If you were extending another class and that property was defined there, this would be fine, but default properties are bad. Besides, I have heard rumors that it will be deprecated soon, so prepare for the worst and just manually define their scope.

class User {
    public
        $first_name,
        $last_name
    ;
    //etc...
}

What is the point of the Post class? Just to declare the $author property? This is unnecessary, especially for a full fledged class. The only time I could foresee something like this being ok is if it were part of an interface or abstract class, but then it should also declare the expected methods as well.

Why is your database class completely static? I understand adopting a singleton pattern to ensure only one connection can be made, but after that you should be able to use the rest of your class like normal. Instead you are calling it statically everywhere. This is what you should be able to do with the singleton pattern. Notice how you only have to get the instance once.

$db = DB::getInstance();
$db->setFetchTableNames( 1 );
$sql = $db->select(//etc...

Why are you looping over the same information twice? If you find yourself looping over something in order to create an array so that you can loop over it again, don't. Just do it all the first time.

while( $post = $stmt->fetchInto( new Post(), 'p' ) ) {
    $post->author = $stmt->fetchIntoFromLastRow( new User(), 'u' );
    echo $post->author->getName();
}

Now, I can't really help you much more because you've not posted all of your code, just examples. I can't review your class except in the abstract. If you want a more complete review, you should follow the FAQ and post all related code. For instance, you are asking about your database wrapper, but all you have posted are a couple of slightly related container classes and example usages. Where's the actually database wrapper?


You can use includes on any activerecord relation.

Judging by your message about having N+1 queries I suspect you are calling city_names somewhere in a loop. then the correct placement of the includes is the place where you select the elements to loop past.

I'm guessing it is for a view or something so i write some example code for .html.erb.

In controller:

@travels = Travels.all.includes(destinations: :cities)

In view:

<% @travels.each do |travel| %>
  ... Some code displaying travel info
  <%= travel.city_names %>
  ... More code displaying travel info
<% end %>

And a suggestion in line with what Mark Thomas wrote as a comment. You can refactor you city_names method for more readable code, either according to his suggestion or like this:

def city_names
  self.cities.map(&:name).join(', ')
end


c++ isn't really my language, but I believe this would be an identical loop:

for(int i = 0; i < 15; i++)
{
  char npt = _getch(); // Get input

  if(npt == '\r')
    break;
  else if(npt == '\b')
  {
    if(!name.empty())
      name.erase(std::prev(name.end()));
    if(i >= 1)
      i -= 2;
    else
      i--;
  }
  else if(i == 14)
    i--;
  else
    name += npt; // add input to string

  SetConsoleCursorPosition(hOut, cDraw);
  printf("              ");
  SetConsoleCursorPosition(hOut, cDraw);
  std::cout << name;
}

The only difference between your first if and the else is the final else line, so I moved the conditional to the end to avoid repeating the same logic.

Additionally, I assume there's some way you could pad name with blank spaces so that you only have to call SetConsoleCursorPosition and print once per iteration.


Your approach is rather good but your implementation is hardly extensible.

For starter, you don't need l4 as you can update l3 directly instead:

l3 = {x['id']: {'av': x['av']} for x in l1}
for d in l2:
    l3[d['id']].update(nv=d['nv'])

Second, you can pop the id so you don't have to know the other keys in the various dictionaries:

l3 = {d.pop('id'): d for d in l1}
for d in l2:
    l3[d.pop('id')].update(d)

But this approach has the drawback of modifying all input dictionaries. To mitigate that, we can start with an empty dictionary, update with every keys (including id) and pop the extra key afterwards. This is easily done using a defaultdict:

from collections import defaultdict

result = defaultdict(dict)
for sequence in (l1, l2):
    for dictionary in sequence:
        result[dictionary['id']].update(dictionary)
for dictionary in result.values():
    dictionary.pop('id')

There are few overheads using this approach compared to the first version, but it is way easier to generalize so you are able to merge more than 2 lists. Speaking of which, in such case, you should define a function taking a variable number of lists to merge:

import itertools
from collections import defaultdict

def merge(shared_key, *iterables)
    result = defaultdict(dict)
    for dictionary in itertools.chain.from_iterable(iterables):
        result[dictionary[shared_key]].update(dictionary)
    for dictionary in result.values():
        dictionary.pop(shared_key)
    return result

Usage be like

merge('id', l1, l2)


Print all lines of a text file containing the same duplicated word

You have a bug

I don't think your program works as intended. If a line exists \$N > 1\$ times, it will be printed \$N (N - 1)\$ times. Because:

The first time it's seen, it will be added to duplicates and not printed. So far so good.
The 2nd, 3rd, ... Nth time it's seen, all \$N\$ occurrences will be printed.

When \$N = 2\$, the program will appear to work fine.
But when \$N > 2\$ there will be excess output of duplicates, which is probably not the way you intended.

Performance

There are several inefficient operations.

The worst is re-reading the file for every duplicate. If the million lines contain pairs of 500000 values, the file will be read 500001 times.

Another inefficient operation is storing the unique values in a slice, instead of a map. The contains implementation based on a slice has  \$O(n)\$ time complexity, which would be \$O(1)\$ using a map.

To improve performance you could use a map of counts. Read the entire file once to build this map. Unique values will have a count of 1, duplicates will have > 1. Read the file again, checking the count in the map, if it's > 1 then print the line.

Resource management and error handling

In Go, it's recommended to use defer to close resources soon after you opened them, so you don't forget later. So instead of this:

fh, err := os.Open(path)

// large block of code

fh.Close()

It's recommended to write like this:

fh, err := os.Open(path)
if err != nil {
    panic("could not open file: " + path)
}
defer fh.Close()

// rest of the code

Closely related is error handling. You ignored the error value returned by os.Open, which is not wise. The rest of the program will make little sense if opening the file fails. Always remember and consider to handle errors.

Coding style

It's good to run go fmt on your program before asking for a review.
It automatically reformats it following the standard of Go.

Suggested implementation

Putting the above tips together:

func main() {
    path := "/tmp/store.txt"
    counts := readCounts(path)
    check(path, counts)
}

func check(path string, counts map[string]int) {
    fh, _ := os.Open(path)
    defer fh.Close()

    scanner := bufio.NewScanner(fh)
    for scanner.Scan() {
        line := scanner.Text()
        text := line[7:]
        if counts[text] > 1 {
            fmt.Println(line)
        }
    }
}

func readCounts(path string) map[string]int {
    fh, err := os.Open(path)
    if err != nil {
        panic("could not open file: " + path)
    }
    defer fh.Close()

    scanner := bufio.NewScanner(fh)
    counts := make(map[string]int)

    for scanner.Scan() {
        line := scanner.Text()
        text := line[7:]
        counts[text] += 1
    }

    return counts
}


Remove Duplicates from Sorted List -- LeetCode Solution in C

You can use a simple recursive method like this: basically, we only need to care about the previous node and current node when deleting a node.

ListNode* deleteDuplicates(struct ListNode* head) {
     deleteDuplicates(NULL, head);
     return head;
}

void deleteDuplicates(struct ListNode* pre, struct ListNode* cur) {
   if(cur == NULL)
      return;
   if(pre == NULL){
      deleteDuplicates(cur, cur->next);
   }else if(pre->val == cur->val){//Delete duplicate node
      pre->next = cur->next;
      deleteDuplicates(pre, pre ->next);
   }else{//The current node doesn't need to be deleted, move forward
      deleteDuplicates(cur, cur->next);
   }
}


Answers to your questions

While it considers Ctrl-D as an invalid choice, should it be handled differently? If so, how?

You should treat the end of the file as the definite end of the input, and return immediately with a value that indicates a failure. Not all EOFs are Ctrl-D's, there is no guarantee that you can even continue reading from std::cin after you encounter an EOF; for example the user might have redirected standard input to a file.

It takes user input as an int. Would you suggest taking it as a string instead, and then use either stoi or stringstream to convert it to an int?

As you have probably seen std::cin >> some_int does not read a whole line, instead it tries to read an integer but stops as soon as it encounters something that is not an integer. Instead of fighting against this, use std::getline() if you want to read a line, and then indeed use std::stoi() or something similar to convert that to a number. You still need to deal with the fact that also stoi() stops as soon as it sees the first character that is not part of an integer.

Can it be re-written in a more elegant and concise way?

Yes, see below.

Do you see any potential issues?

There is code duplication and unnecessary complexity dealing with std::cin. Also, the function is not very generic; if you want to get a choice for a different menu you would have to write a new function.
Reading a line with an integer in it
First, read a single line, and check if that succeeded. If not, either return some value indicating an error, or throw an exception. For example:
std::string line;

if (!std::getline(std::cin, line)) {
    throw std::runtime_error("Error while reading input");
}

Then try to convert it with std::stoi() or any of its variants, depending on the type of integer. Use the second argument to std::stoi() to know where it stopped parsing the integer, and check that this was at the end of the string:
try {
    size_t endpos;
    size_t value = stoi(line, &endpos);

    if (endpos == line.size()) {
        // Success!
        ...
    }
} catch (std::logic_error &) {
    // Error parsing the integer
    ...
}

Make getChoice() more generic
You hardcoded the choices in getChoice(). If you have a program with multiple menus, then you would have to write different versions of getChoice(), duplicating a lot of code. So try to make it more generic. For example, you can have getChoice() take two parameters: one is a string with the title of the menu, the second is a vector of strings with the possible choices.
Full example
Here is an example of what it could look like:
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

size_t getChoice(const std::string &title, const std::vector<std::string> &choices)
{
    std::cout << title << "\n"
              << "-------------------\n";

    for (size_t i = 0; i < choices.size(); ++i) {
        std::cout << i << ". " << choices[i] << "\n";
    }

    while (true) {
        std::cout << "Enter choice: " << std::flush;
        std::string line;

        if (!std::getline(std::cin, line)) {
            throw std::runtime_error("Could not read input");
        }

        try {
            size_t endpos;
            size_t choice = stoul(line, &endpos);

            if (endpos == line.size() && choice < choices.size()) {
                return choice;
            }
        } catch (std::exception &) {
            // nothing to do here
        }

        std::cout << "Invalid choice\n";
    }
}

int main()
{
    static const std::vector<std::string> choices = {
        "Add record",
        "Edit record",
        "Delete record",
        "View record",
        "view all records",
        "Exit",
    };

    size_t choice = getChoice("Main menu", choices);

    std::cout << "User chose option " << choice << std::endl;
}

Note that I made the option numbers start with zero, just to keep the code slightly simpler. I also used size_t, as it is unsigned (no need to deal with negative numbers), and it's good practice whenever you deal with indices into arrays, vectors and so on. Note that you don't have to create a named vector in main(), you can even pass a literal to getChoices():
size_t choice = getChoice("Menu", {"First option", "Second option", ...});


From the requirements

  I have a set of rules as follows:

  Product One:

  If either part is acceptable, update both parts

  Product Two:

  If either part is acceptable, and one age is > 55, update both parts

  If either part is acceptable, and neither age is > 55, then update
  whichever part needs updating (or both)

Follows the next, almost literal, straightforward implementation:

Straightforward implementation

So, you could implement this using two Checkers, a Product1Checker and a Product2Checker.

if (this.productName.equals(PRODUCT_ONE))
{
    new Product1Checker().check(this);
}
else if (this.productName.equals(PRODUCT_TWO))
{
    new Product2Checker().check(this);
}

Like this:

class Product1Checker
{

    public check (Product product)
    {
         if (product.isAcceptablePartOne || product.isAcceptablePartTwo)
         {
               product.updatePartOne();
               product.updatePartTwo();
         }
    }
}

Alternative approach

You could have the Checkers implement a ProductChecker interface. Also, each ProductChecker can have a boolean method indicating if this checker applies to a product. Then you can just add all the checkers to a Set, check if they are applicable, and if so, run them on the product

interface ProductChecker
{
    boolean check     (Product p);
    boolean appliesTo (Product p);
}

Set<ProductChecker> checkers = new HashSet<ProductChecker>();
checkers.add(new Product1Checker());
checkers.add(new Product2Checker());

for (ProductChecker checker: checkers)
{
      if (checker.appliesTo(this))
      {
          checker.check(this));
      }
}


Not knowing what your XMl files are like or what you're trying to extract from them, this is mostly speculative:

Generally, you want to strip away as much unwanted data as early as possible in the process. Rather than trying to import an entire file to the worksheet every time, why not strip your document down to a NodeList, and then either target specific nodes (if you're only after certain data) or iterate over them and extract the data values into an array. Then you can print that Array to a worksheet.

I recently built a Tool to extract data from corporate accounts. It loads an XML doc (typically 100kb), parses the Node Tree, searches for specific nodes using XPath, extracts the displayed text of each and sticks it in an array that's printed to a worksheet every 500 lines or so. It grabs 5 sets of nodes from each document, and parses about 1 Million documents/hour, or nearly 300 documents / second.

Below is an extract showing the basic processing of loading, stripping, searching and retrieving.

Public Sub GetDirectorsFromFile(ByVal strFullFilename As String)

    Dim xDoc As MSXML2.DOMDocument
    Set xDoc = New MSXML2.DOMDocument

    Dim colDirectors As Collection
    Set colDirectors = New Collection

    With xDoc

        If .Load(strFullFilename) Then

            .setProperty "SelectionLanguage", "XPath"
            GetDirectorsFromXml xDoc, colDirectors

        End If

    End With

End Sub

Public Sub GetDirectorsFromXml(ByRef xDoc As MSXML2.DOMDocument, ByRef colDirectors As Collection)

    Dim ixItem As Long
    Dim xPathSearchString As String
    Dim nodes As MSXML2.IXMLDOMNodeList
    Dim nodeText As String

        xPathSearchString = "//*[contains(@name,""NameEntityOfficer"")]"
        Set nodes = xDoc.SelectNodes(xPathSearchString )

        For ixItem = 0 To nodes.Length - 1
            nodeText = nodes.Item(ixItem).text
            colDirectors.Add text
        Next ixItem

End Sub


Lazy Load for multiple entities at a time

You code seems to not doing what it is supposed to do.

Assume the following implementation (using the ResetLazy)

Customer and Order

namespace Entities
{
    public class Customer
    {
        public int Id { get; set; }
        public ResetLazy<List<Entities.Order>> Orders {get;set;}
    }
    public class Order
    {
        public int Id { get; set; }
        public int CustomerId { get; set; }
    }
}

Simulated database

public class TheDatabase
{
    public TheDatabase()
    {
        customers.Add(new Entities.Customer { Id = 1 });
        orders.Add(new Entities.Order { Id = 1, CustomerId = 1 });
        orders.Add(new Entities.Order { Id = 2, CustomerId = 1 });
        orders.Add(new Entities.Order { Id = 3, CustomerId = 1 });

        customers.Add(new Entities.Customer { Id = 2 });

        customers.Add(new Entities.Customer { Id = 3 });
        orders.Add(new Entities.Order { Id = 4, CustomerId = 3 });
        orders.Add(new Entities.Order { Id = 5, CustomerId = 3 });
    }
    private List<Entities.Customer> customers = new List<Entities.Customer>();
    private List<Entities.Order> orders = new List<Entities.Order>();
    public List<Entities.Customer> GetCustomersByIds(IEnumerable<int> ids)
    {
        return customers.Where(c => ids.Contains(c.Id)).ToList();
    }
    public IEnumerable<Entities.Order> GetOrdersByCustomerIds(IEnumerable<int> ids)
    {
        return orders.Where(c => IsContained(c.CustomerId, ids));
    }
    private bool IsContained(int id, IEnumerable<int> ids)
    {
        foreach (int currentId in ids)
        {
            if (id == currentId) { return true; }
        }
        return false;
    }
}

And the class containing your methods

class Program
{

    static void Main(string[] args)
    {
        Program p = new Program();
        IEnumerable<int> ids = new List<int>() { 1, 2, 3 };
        List<Entities.Customer> customers = p.GetCustomersByIds(ids);

        int customerId = 1;
        List<Entities.Order> orders = new List<Entities.Order>(customers.Where(c => c.Id == customerId).First().Orders.Value);
        System.Diagnostics.Debug.Assert(orders[0].CustomerId == customerId);
    }

    TheDatabase db;
    private Program()
    {
        db = new TheDatabase();
    }

    public List<Entities.Customer> GetCustomersByIds(IEnumerable<int> ids)
    {
        var customers = db.GetCustomersByIds(ids);
        foreach (var customer in customers)
        {
            customer.Orders = new ResetLazy<List<Entities.Order>>(() =>
                GetOrdersByCustomersLazy(customers, customer.Id));
        }
        return customers;
    }

    protected List<Entities.Order> GetOrdersByCustomersLazy(
        List<Entities.Customer> customers,
        int customerId)
    {
        var orders = db.GetOrdersByCustomerIds(
            customers.Select(customer => customer.Id).AsEnumerable());
        foreach (var customer in customers)
        {
            customer.Orders = new ResetLazy<List<Entities.Order>>(() =>
            {
                customer.Orders = new ResetLazy<List<Entities.Order>>(() =>
                    GetOrdersByCustomersLazy(customers, customer.Id));
                return orders.Where(order => order.CustomerId == customer.Id).ToList();
            });
        }
        return customers.FirstOrDefault(customer => customer.Id == customerId).Orders.Value;
    }
}

The Debug.Assert() method signals the wrong id.

Fixing

By adding a setter to ResetLazy.Value like

set
{

    if (mode != LazyThreadSafetyMode.None)
    {
        lock (syncLock)
        {
            this.box = new Box(value);
        }
    }
    else
    {
        this.box = new Box(value);
    }
}

and changing the GetOrdersByCustomersLazy() method to

protected List<Entities.Order> GetOrdersByCustomersLazy(
    List<Entities.Customer> customers,
    int customerId)
{
    var orders = db.GetOrdersByCustomerIds(
        customers.Select(customer => customer.Id).AsEnumerable());
    foreach (var customer in customers)
    {
        customer.Orders.Value = orders.Where(o => o.CustomerId == customer.Id).ToList();
    }
    return customers.FirstOrDefault(customer => customer.Id == customerId).Orders.Value;
}

The following runs as expected

Program p = new Program();
IEnumerable<int> ids = new List<int>() { 1, 2, 3 };
List<Entities.Customer> customers = p.GetCustomersByIds(ids);

int customerId = 1;
List<Entities.Order> orders = new List<Entities.Order>(customers.Where(c => c.Id == customerId).First().Orders.Value);
System.Diagnostics.Debug.Assert(orders.Count==3 && orders[0].CustomerId == customerId);

customerId = 2;
orders = new List<Entities.Order>(customers.Where(c => c.Id == customerId).First().Orders.Value);
System.Diagnostics.Debug.Assert(orders.Count==0);

customerId = 3;
orders = new List<Entities.Order>(customers.Where(c => c.Id == customerId).First().Orders.Value);
System.Diagnostics.Debug.Assert(orders.Count == 2 && orders[0].CustomerId == customerId);

You shouldn't shorten names of variables. The advantage of typing less is reduced by the lack of readability.

A call to the linq Select() method returns an IEnumerable so a call to AsEnumerable() is not needed.


Flatten JSON to get relevant data in Postgresql

This gets you the same output:

SELECT  id
,   firstname
,   lastname
,   (SELECT string_agg(p->>'Number', ',') FROM jsonb_array_elements(phone) p WHERE p->>'Type' = 'Mobile') AS mobile_phone_number
,   (SELECT string_agg(p->>'Number', ',') FROM jsonb_array_elements(phone) p WHERE p->>'Type' <> 'Mobile') AS unformatted_phone_numbers
,   (SELECT string_agg(e->>'Email', ',') FROM jsonb_array_elements(email) e) AS email_addresses
FROM test.individuals

So basically, rather than creating all the CTEs ahead of time with aggregated results and then joining against them, we just go through the records and compute the results of the last three columns by running some functions on the content of phone/email fields as they're read.

This is the query plan my my version:

Seq Scan on individuals  (cost=0.00..21.22 rows=4 width=111) (actual time=0.114..0.230 rows=4 loops=1)
  SubPlan 1
    ->  Aggregate  (cost=1.51..1.52 rows=1 width=32) (actual time=0.021..0.021 rows=1 loops=4)
          ->  Function Scan on jsonb_array_elements p  (cost=0.00..1.50 rows=1 width=32) (actual time=0.013..0.015 rows=1 loops=4)
                Filter: ((value ->> 'Type'::text) = 'Mobile'::text)
                Rows Removed by Filter: 1
  SubPlan 2
    ->  Aggregate  (cost=2.00..2.01 rows=1 width=32) (actual time=0.012..0.012 rows=1 loops=4)
          ->  Function Scan on jsonb_array_elements p_1  (cost=0.00..1.50 rows=99 width=32) (actual time=0.008..0.009 rows=1 loops=4)
                Filter: ((value ->> 'Type'::text) <> 'Mobile'::text)
                Rows Removed by Filter: 1
  SubPlan 3
    ->  Aggregate  (cost=1.50..1.51 rows=1 width=32) (actual time=0.009..0.009 rows=1 loops=4)
          ->  Function Scan on jsonb_array_elements e  (cost=0.00..1.00 rows=100 width=32) (actual time=0.005..0.005 rows=1 loops=4)
Planning time: 0.297 ms
Execution time: 0.354 ms

And yours:

Hash Left Join  (cost=51.17..56.00 rows=4 width=164) (actual time=0.367..0.386 rows=4 loops=1)
  Hash Cond: (p.id = mob.id)
  CTE persons
    ->  Seq Scan on individuals  (cost=0.00..1.04 rows=4 width=15) (actual time=0.032..0.034 rows=4 loops=1)
  CTE email_ids
    ->  Seq Scan on individuals individuals_1  (cost=0.00..3.03 rows=400 width=36) (actual time=0.034..0.056 rows=4 loops=1)
  CTE email_aggregated
    ->  HashAggregate  (cost=11.00..13.50 rows=200 width=36) (actual time=0.088..0.091 rows=3 loops=1)
          Group Key: email_ids.id
          ->  CTE Scan on email_ids  (cost=0.00..8.00 rows=400 width=36) (actual time=0.037..0.061 rows=4 loops=1)
  CTE phone_numbers
    ->  Seq Scan on individuals individuals_2  (cost=0.00..3.03 rows=400 width=36) (actual time=0.030..0.048 rows=8 loops=1)
  CTE mobile_numbers
    ->  GroupAggregate  (cost=10.01..10.06 rows=2 width=36) (actual time=0.033..0.041 rows=4 loops=1)
          Group Key: phone_numbers.id
          ->  Sort  (cost=10.01..10.02 rows=2 width=36) (actual time=0.025..0.027 rows=4 loops=1)
                Sort Key: phone_numbers.id
                Sort Method: quicksort  Memory: 25kB
                ->  CTE Scan on phone_numbers  (cost=0.00..10.00 rows=2 width=36) (actual time=0.004..0.012 rows=4 loops=1)
                      Filter: ((phone_object ->> 'Type'::text) = 'Mobile'::text)
                      Rows Removed by Filter: 4
  CTE other_numbers
    ->  HashAggregate  (cost=12.98..15.48 rows=200 width=36) (actual time=0.084..0.086 rows=2 loops=1)
          Group Key: phone_numbers_1.id
          ->  CTE Scan on phone_numbers phone_numbers_1  (cost=0.00..10.00 rows=398 width=36) (actual time=0.042..0.069 rows=4 loops=1)
                Filter: ((phone_object ->> 'Type'::text) <> 'Mobile'::text)
                Rows Removed by Filter: 4
  ->  Hash Right Join  (cost=4.97..9.76 rows=4 width=132) (actual time=0.298..0.315 rows=4 loops=1)
        Hash Cond: (oth.id = p.id)
        ->  CTE Scan on other_numbers oth  (cost=0.00..4.00 rows=200 width=36) (actual time=0.085..0.088 rows=2 loops=1)
        ->  Hash  (cost=4.92..4.92 rows=4 width=100) (actual time=0.193..0.193 rows=4 loops=1)
              Buckets: 1024  Batches: 1  Memory Usage: 9kB
              ->  Hash Right Join  (cost=0.13..4.92 rows=4 width=100) (actual time=0.167..0.185 rows=4 loops=1)
                    Hash Cond: (eml.id = p.id)
                    ->  CTE Scan on email_aggregated eml  (cost=0.00..4.00 rows=200 width=36) (actual time=0.090..0.096 rows=3 loops=1)
                    ->  Hash  (cost=0.08..0.08 rows=4 width=68) (actual time=0.059..0.059 rows=4 loops=1)
                          Buckets: 1024  Batches: 1  Memory Usage: 9kB
                          ->  CTE Scan on persons p  (cost=0.00..0.08 rows=4 width=68) (actual time=0.040..0.050 rows=4 loops=1)
  ->  Hash  (cost=0.04..0.04 rows=2 width=36) (actual time=0.052..0.052 rows=4 loops=1)
        Buckets: 1024  Batches: 1  Memory Usage: 9kB
        ->  CTE Scan on mobile_numbers mob  (cost=0.00..0.04 rows=2 width=36) (actual time=0.036..0.048 rows=4 loops=1)
Planning time: 0.719 ms
Execution time: 0.693 ms

Neither are particularly performant, although my version appears about twice as fast, but the stats can't be trusted with so little data, so it's not very useful right now.


Class / Superclass / Specific class matching condition, can it be simpler?

There's not really enough information or context here to make any sort of comment on the efficiency of this pair of methods, but it seems like this could simply be narrowed down into a single method.

We're iterating through a collection so we can call resignField: on specific classes only, and all of the logic in resignField: already works on specific classes only.  The only thing that's left is the check for whatever this exception is:

- (void)resignFieldStackRespondersExcept:(id)fieldException {
    for (id field in self.fieldStack) {
        if ([field isKindOfClass:[AccessoryPicker class]]) {
            [field closePicker:YES];
        } else if ([field isKindOfClass:[TagsTextView class]]) {
            [field saveTrailingTag];
        } else if ([field isKindOfClass:[UITextField class]]
                   && ![[fieldException class] isSubclassOfClass:[UITextView class]]) {
            [field resignFirstResponder];
        } else if ([field isKindOfClass:[UITextView class]]
                   && ![[fieldException class] isSubclassOfClass:[UITextField class]]) {
            [field resignFirstResponder];
        }
    }
}

Now we can eliminate the second method entirely.  The first method is more readable and unnecessary checks have been removed.


Use placeholder there: WHERE ha.house_id = $id"; Placeholder is better due to security approach.

if (count($_POST) > 0) {

$limit = trim($_POST['limit']);
$char = trim($_POST['character']);

You should separate presentation from your logic. It will be better: read all $_POST outside the function and pass in arguments. Maybe you wanna later to play your game via AJAX, or something else, and you won't need $_POST anymore, but you still need the logic.

Due the same approach, returning status and errors from function is a better way, then just prints them out. You can return 2 values from function -- status and errors array.

Then do something like this:

list($status, $errors) = your_function(...);
if (!$status) {
    //printing errors
}

Or you can just return an array, and check length of it. If array contain some errors, print them out.

Rename your variables.

char to character

pid to playerId

limit2 to newLimit? Or what it means?

In your code it isn't clear enough. Especially limit2.


Conditionally selecting random element from array

Confusing explanation

According to your explanation, storing 10 in the board means displaying \$2^{10}\$ or 1024 on the screen.  If so, then storing a 1 in the board would display \$2^1\$ or 2, and storing a 2 would display \$2^2\$ or 4.  But this contradicts your program which chooses a new display value of 1 and 2 using board values 1 and 2.

Either you should be generating board values 0 and 1, or your explanation was wrong.  I'm guessing that your explanation was wrong and that storing x in your board represents \$2^{x-1}\$ and not \$2^x\$.

Random number generation off by one

You said you wanted to generate 1 with 90% frequency, but you actually are generating it with 89% frequency.  You need to change your < to a <= to fix that.

One easy way to see that you are off by one is if you change the 90 to a 100.  Then you will see that you still have a 1% chance of generating a 2 instead of a 0% chance.

Deterministic way of choosing empty cell

Instead of randomly picking cells until you get an empty one, you can count the number of empty cells, then pick among them.  For example, if you count 5 empty cells, then you can pick a number between 0 and 4, and then go back through the cells and find the nth empty cell, where n is the random number you picked.

Sample rewrite

Here is an example of how you could implement the above suggestion:

void randCell(int _board[BOARD_SIZE][BOARD_SIZE]) {
    int num_spaces = 0;

    // Count the number of empty spaces.
    for (int i = 0; i < BOARD_SIZE; ++i) {
        for (int j = 0; j < BOARD_SIZE; ++j) {
            if (_board[i][j] == EMPTY)
                num_spaces++;
        }
    }

    if (num_spaces == 0)
        return;

    int rand_space = randRange(0, num_spaces - 1);
    for (int i = 0; i < BOARD_SIZE; ++i) {
        for (int j = 0; j < BOARD_SIZE; ++j) {
            if (rand_space-- == 0) {
                _board[i][i] = (randRange(1, 100) <= 90) ? 1 : 2;
                return;
            }
        }
    }
}


Decoupling tests from implementation and increase their resilience

Without trying to sound tautological, the tests in your original question are coupled to your implementation because that's exactly what they are testing.

You're testing that -

Remove is called on a database abstraction
The method doesn't throw an exception for an invalid slug
The method returns true when it finds something to delete
The method returns false when it does not find something to delete

These are all quite low level concepts, are any of them important?

As a developer that's new to a code base, I look to the tests to tell me what's important and needs to be preserved. Most of the time, this boils down to behaviour that the user can observe and interact with.

If you re-focus your tests so that they ensure -

When there are Posts in the repository, a user can view them
When a Post is deleted, it is no longer listed on an index
When a Post is deleted, it can no longer be viewed

Then you will not be coupling them to such details as "my repositories return false when they can't find something to delete".


Clean way to handle file not found exception

I would suggest not opening the file in your function but instead returning the path or None, such that the caller can open the file using a with statement.


Search products from database on base of search filters

At least a couple things to note:

Bug?

I think this part doesn't work because you don't assign the result of this query back to the variable.

if(search.filter != null)
{
    var fs = search.filter.SelectMany(c => c.Value.Select(a => new Models.Custom_Model.IdName {Id = c.Id,Name = a}));
    products.Where(z=>((z.productattributes.Select(c=>new Models.Custom_Model.IdName {Id = c.AttributeId,Name = c.Value})).Intersect(fs)).Any());
}

Naming

Public properties should be in PascalCasing (msdn) private variables in camelCase.

Also, some using-statements would remove the namespace-clutter.

Line breaks

I think couple of line breaks would make long lines more readable. First line as an example.

var products = _db.products
    .Include(a => a.category)
    .Include(c => c.subcategory)
    .Include(c => c.productattributes)
    .Where(c => c.SubCategoryId == subcategoryId && c.subcategory.isActive && c.category.isActive);

Refactoring to smaller methods

Pagination (skipping and taking x records) is pretty general concept, so it should perhaps be moved to to its own, generic function.

Also, sorting could be moved to its own method

SearchModel refactoring

I remove private variables from SearchModel because they are only used for defaults. I would set defaults in constructor so defaults are in one place. Filter doesn't need to be set but I set it here for consistency.

I also renamed Criteria to SortingCriteria to make the meaning clearir. If it is only Criteria, it is not clear if it is used to filter the query or sorting.

public int PageSize { get; set; }
public int PageNumber { get; set; }
public Enum.SortingCriteria SortingCriteria { get; set; }
public List<FiltersViewModel> Filter { get; set; }

public SearchModel()
{
    PageSize = 50;
    PageNumber = 1;
    SortingCriteria = Enum.SortingCriteria.New;
    Filter = null;
}


Create a lodash chain, use _.groupBy() to get a dates map, and then reduce it to percentages:

function getNumOfYes(data) {
  return _(data).groupBy('date').reduce(function(percentage, answers) {
    var numOfYes = _.countBy(answers, 'answer').yes || 0;
    percentage.push(numOfYes / answers.length * 100);
    return percentage;
  }, []);
}

var data = [{
  "date": "1-1-2013",
  "answer": "yes"
}, {
  "date": "1-1-2013",
  "answer": "no"
}, {
  "date": "2-1-2013",
  "answer": "no"
}, {
  "date": "2-1-2013",
  "answer": "no"
}, {
  "date": "2-1-2013",
  "answer": " " //this is not answered!
}, , {
  "date": "2-1-2013",
  "answer": "no"
}];

var numOfYes = getNumOfYes(data);

console.log(numOfYes);

document.getElementById('results').innerText = JSON.stringify(numOfYes);


Cron expression validator for Apache Quartz

In terms of overall hierarchy here, the CronTester class is just 'fluff' and does not do anything except provide an main method. The interesting class is: CronDateCreator.
CronDateCreator is a very lightweight class. It essentially does nothing that requires it to be a class... it wraps a String value in a CronExpression, is that CronExpression reused for anything?
It strikes me that the standard use-case for this class would be:
CronDateCreator cdc = new CronDateCreator(input);
List<Date> dates = cdc.createValidTimeDatesFromNow(numberOfDates);

and then the cdc will be forgotten.
Is this a case of where a static method is maybe all you need?
Something like:
public static List<Date> createValidTimeDatesFromNow(String expression, int numberOfDates) {
    ....
}

Just a thought...
Date
Now, about the Date return values.
Date is a much maligned class in Java. It has so many nuances, issues, and tweaks that it was initially 'forked' and rewritten as JodaTime in an open source library, then, in Java8, they have pulled the best from JodaTime, and incorporated some other compatibility and functionality changes, and created the new java.time.* package.
Any code written to support Java8 or newer should essentially abandon Date, and work with Instant  instead.
You should use your class/static methods to translate the Dates back to Instants, and go from there.
Actual code:
Your method here could be neatened up a lot:

public List<Date> createValidTimeDates(Date startingDate, int numberOfDates) {
    Date nextValidDate = cron.getNextValidTimeAfter(startingDate);
    List<Date> results = new ArrayList<>();

    for (int i = 0; i < numberOfDates; i++) {
        results.add(nextValidDate);
        nextValidDate = cron.getNextValidTimeAfter(nextValidDate);
    }

    return results;
}

For a start, you know how large the ArrayList will be, so set the size on the constructor:
List<Date> results = new ArrayList<>(numberOfDates);

Then, your loop logic is off... how about the following?:
public List<Date> createValidTimeDates(Date startingDate, final int numberOfDates) {
    List<Date> results = new ArrayList<>(numberOfDates);

    for (int i = 0; i < numberOfDates; i++) {
        startingDate = cron.getNextValidTimeAfter(startingDate);
        results.add(startingDate);
    }
    return results;
}


Returning a pseudo-random Gaussian number

A do while would be an equivalent construct. I don't really think either is more or less preferable, but is an alternative that avoids the appearance of an infinite loop:

do {
    returningNumber = (generator.nextGaussian() * rangeMean/PERCENT_97) + mean;
} while (returningNumber < min || returningNumber > max);
return returningNumber;

That still leaves open a possibility of an eternal loop, though. You should probably at least validate your params to guard against that (eg., a min of 1 and max of 1 would run forever). You may also want to put an iteration counter to give up and throw an exception after so many iterations. At that point, a for loop with an early return if one is found may be a better choice than stuffing it all into the where or if conditionals:

for (int i = 0; i < MAX_TRIES; i++) {
    returningNumber = (generator.nextGaussian() * rangeMean/PERCENT_97) + mean;
    if (returningNumber > min && returningNumber < max) {
        return returningNumber;
    }
}
throw new IGiveUpException();


Refactor this jQuery datepicker code to be as small as possible

You'll want to use setDefaults to clean up your code a bit. Also with a few variables you can clean it up even more.

$.datepicker.setDefaults({
    showOn: 'both',
    buttonImage: '/assets/images/calendar_symbol.png',
    buttonImageOnly: true,
    dateFormat: 'dd/mm/yy',
    constrainInput: true
});

var minDate = new Date(
    <?php echo date("Y")?>,
    <?php echo date("m")-1?>,
    <?php echo date("d")?>
);

var setEndDate = function() {
    $('#enddate').val($('#startdate').val());
};

$('#startdate').datepicker({
    minDate: minDate ,
    onClose: setEndDate
});

$('#enddate').datepicker({
    minDate: minDate
});

$('#filter_startdate').datepicker({
    onClose: setEndDate
});

$('#filter_enddate').datepicker();


How can I check if a sequence is alternating?

It's not correct for short sequences with less than 3 items.
The method incorrectly returns true for these example sequences:

empty sequence
singleton list (one item)
sequence with two items that are equal

For the first 2 cases you might even want to throw IllegalArgumentException as arguably it doesn't make much sense to test for alternation in lists with 0 or 1 item, but I think returning false is reasonable.

You can do this by adding these conditions at the start of the method:

    if (sequence.length < 2) {
        return false;
    }
    if (sequence.length == 2) {
        return sequence[0] != sequence[1];
    }

But actually I would simplify the body of the for loop like this:

    if (sequence.length < 2) {
        return false;
    }
    int prevCompare = Integer.compare(sequence[0], sequence[1]);
    if (prevCompare == 0) {
        return false;
    }
    for (int i = 1; i < sequence.length - 1; ++i) {
        int compare = Integer.compare(sequence[i], sequence[i + 1]);
        if (prevCompare != -compare) {
            return false;
        }
        prevCompare = compare;
    }
    return true;

To verify the implementation I recommend adding some unit tests, for example:

@Test
public void testEmptyList_Is_NotAlternating() {
    assertFalse(alternating(new int[0]));
}

@Test
public void testSingletonList_Is_NotAlternating() {
    assertFalse(alternating(new int[]{1}));
}

@Test
public void test2Items_Increasing_Is_Alternating() {
    assertTrue(alternating(new int[]{1, 2}));
}

@Test
public void test2Items_Decreasing_Is_Alternating() {
    assertTrue(alternating(new int[]{3, 2}));
}

@Test
public void test2Items_Same_Is_NotAlternating() {
    assertFalse(alternating(new int[]{3, 3}));
}

@Test
public void test3Items_Same_Is_NotAlternating() {
    assertFalse(alternating(new int[]{3, 3, 3}));
}

@Test
public void test4Items_Same_Is_NotAlternating() {
    assertFalse(alternating(new int[]{3, 3, 3, 3}));
}

@Test
public void test3Items_Increasing_Is_NotAlternating() {
    assertFalse(alternating(new int[]{3, 4, 5}));
}

@Test
public void test4Items_Increasing_Is_NotAlternating() {
    assertFalse(alternating(new int[]{3, 4, 5, 6}));
}

@Test
public void test3Items_Decreasing_Is_NotAlternating() {
    assertFalse(alternating(new int[]{43, 34, 25}));
}

@Test
public void test4Items_Decreasing_Is_NotAlternating() {
    assertFalse(alternating(new int[]{43, 34, 25, 16}));
}

@Test
public void test4Items_AlternatingThenMonotonic_Is_NotAlternating() {
    assertFalse(alternating(new int[]{43, 34, 35, 16, 16, 16}));
}

@Test
public void test4Items_Alternating_Is_Alternating() {
    assertTrue(alternating(new int[]{43, 34, 35, 16}));
}


General comments:  I would move the timeout and batch sizes into private fields.  I don't know what version of c# you are using but you could create a class or if you have the nice tuple support you can just create it like so

private readonly (TimeSpan timeout, int buffer) _saveBatchSettings = (TimeSpan.FromSeconds(3), 1000);
private readonly (TimeSpan timeout, int buffer) _publishBatchSettings = (TimeSpan.FromSeconds(1), 500);

It's nice to have these outside the main program because typically with batching you have to tweak the timeouts and size to find the sweet spot and this make it simpler to find what you need to change.

Also you have no way to complete the source.  I would recommend making the class IDisposable and in the dispose mark the source as complete.

TPL DataFlow comments:   Why not use a BroadcastBlock that is tied to the BatchBlocks then it's one send and not two.

Move this

var res = x.GroupBy(d => d.Ticker).Select(d = >d.OrderByDescending(s =>s.DateTime).FirstOrDefault()).ToList();

Into a TransformBlock and make the ActionBlock just contain the code to publish the result.

For ActionBlock, this is just my preference, I make a method that the action block calls to instead of inline lambda it.  That code is typically the processing code and it's easier to maintain and read if it's in it's own method and outside the pipeline setup.

ReactiveExtensions:  If you are willing to add ReactiveExtensions to your project you can mix and Rx and TPL DataFlow Blocks.  Rx has a built in method for your buffering called Buffer.  The DataFlow blocks has an AsObservable and AsObserver to switch to and from Rx and TPL. This would be an example for using Rx with TPL

public class StreamMessagePipeline<T> : IDisposable
    where T : StreamingMessage
{
    private BroadcastBlock<T> _source;

    private readonly (TimeSpan timeout, int buffer) _saveBatchSettings = (TimeSpan.FromSeconds(3), 1000);
    private readonly (TimeSpan timeout, int buffer) _publishBatchSettings = (TimeSpan.FromSeconds(1), 500);

    public StreamMessagePipeline()
    {
        _source = new BroadcastBlock<T>(x => x);
        SetupSaveBatchPipeline();
        SetupPublishBatchPipeline();
    }

    public async Task Handle(T record)
    {
        await _source.SendAsync(record);
    }

    private void SetupSaveBatchPipeline()
    {
        var actionBlockSave = new ActionBlock<IList<T>>(SaveBatch);

        // Instead of action block you could stay in Rx and just use Subscribe
        _source.AsObservable()
            .Buffer(_saveBatchSettings.timeout, _saveBatchSettings.buffer)
            .Where(x => x.Count > 0) // unlike TriggerBatch Buffer will send out an empty list
            .Subscribe(actionBlockSave.AsObserver());
    }

    private void SetupPublishBatchPipeline()
    {

        var transformBlock = new TransformBlock<IList<T>, IList<T>>(x =>
        {
            return x.GroupBy(d => d.Ticker)
                .Select(d => d.OrderByDescending(s => s.DateTime).FirstOrDefault()).ToList();
        });

        var actionBlockPublish = new ActionBlock<IList<T>>(PublishBatch);

        transformBlock.LinkTo(actionBlockPublish, new DataflowLinkOptions()
        {
             PropagateCompletion = true,
        });

        _source.AsObservable()
            .Buffer(_publishBatchSettings.timeout, _publishBatchSettings.buffer)
            .Where(x => x.Count > 0) // unlike TriggerBatch Buffer will send out an empty list
            .Subscribe(transformBlock.AsObserver());
    }

    private void SaveBatch(IList<T> messages)
    {
        // Save the batch
    }

    private void PublishBatch(IList<T> messages)
    {
        // publish the batch
    }

    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                _source.Complete();
            }
            disposedValue = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    #endregion

}

Update If you don't want to use Rx you can still make a custom block to that has the same functionality.

public static class TimerBatchBlock
{
    public static IPropagatorBlock<T, T[]> Create<T>(int batchSize, TimeSpan timeSpan, GroupingDataflowBlockOptions options = null)
    {
        var batchBlock = new BatchBlock<T>(batchSize, options ?? new GroupingDataflowBlockOptions());
        var broadCastBlock = new BroadcastBlock<T[]>(x => x);
        var bufferBlock = new BufferBlock<T[]>();

        // timer setup (System.Threading.Timer)
        var timer = new Timer(x => ((BatchBlock<T>)x).TriggerBatch(), batchBlock, timeSpan, timeSpan);
        var resetTimerBlock = new ActionBlock<T[]>(_ => timer.Change(timeSpan, timeSpan)); // reset timer each time buffer outputs
        resetTimerBlock.Completion.ContinueWith(_ => timer.Dispose());

        // link everything up
        var linkOptions = new DataflowLinkOptions()
        {
            PropagateCompletion = true,
        };
        broadCastBlock.LinkTo(resetTimerBlock, linkOptions);
        broadCastBlock.LinkTo(bufferBlock, linkOptions);
        batchBlock.LinkTo(broadCastBlock, linkOptions);

        return DataflowBlock.Encapsulate(batchBlock, bufferBlock);
    }
}

You would link BroadCastBlock -> TimerBatchBlock -> ActionBlock


MASM) assembly implementation of recursive Fibonacci

dec eax
mov edx, eax

This you can write as the single instruction lea edx, [eax-1], but your code doesn't need to use the extra register EDX at all. The single dec eax is enough.
If you really want to optimize code then don't use constructs like .IF eax > 1 .ENDIF (and many others) for which you don't necessarily know how they get encoded.
invoke, proc, local, and endp will very probably entail that prologue and epilogue codes are inserted. This is fine for the interfacing with the main program but is demanding on the recursion.
push ebp        ; Prologue
mov  ebp, esp
sub  esp, 4     ; Local
...
mov  esp, ebp   ; Epilogue
pop  ebp
ret  4          ; Parameter removal

With a separate recursive routine DoFib, you can:

avoid using the above and rely on the faster [esp] relative addressing.
reuse the argument from the first recursive call. All it takes is a second dec on the already decremented value.
pass the single dword argument via the EAX register instead of on the stack.

;extern "C" unsigned long fibonacci_asm_canonical(unsigned long number)
fibonacci_asm_canonical proc number: dword
    mov  eax, number
    call DoFib           ; -> EAX
    ret
fibonacci_asm_canonical endp

; IN (eax) OUT (eax)
DoFib:
    cmp  eax, 1
    jbe  .done
    sub  esp, 8         ; Room for local storage
    dec  eax
    mov  [esp], eax     ; (number - 1)
    call DoFib          ; -> EAX
    mov  [esp+4], eax   ; Store lhs result
    mov  eax, [esp]     ; (number - 1)
    dec  eax            ; (number - 2)
    call DoFib          ; -> EAX
    add  eax, [esp+4]   ; rhs + lhs
    add  esp, 8
  .done:
    ret


Parse through an XDocument efficiently and match values to matching object

I'm going to revew only this part as I think the rest of it is just for demonstration purposes.

private static void UpdateParams(XDocument xDoc)
{
  IEnumerable<Param> filteredParamList;
  foreach (XElement xElement in xDoc.Root.Elements())
  {
      filteredParamList = paramList.Where(param => param.xmlName == xElement.Name.LocalName);
      if (filteredParamList != null && filteredParamList.Any())
      {
          filteredParamList.Single().Value = double.Parse(xElement.Value) * filteredParamList.Single().scalingFactor;
      }
  }
}

Try to avoid writing methods like this one, where one of the parameters is some static field. This makes it very difficult to test because of the external dependency. If possible you should pass the parameter as anoter argument. I had a hard time understanding your code.
Try to also avoid modifying methods parameters like you do here with the paramList. It's usually much better to return a new result. Such methods are called pure methods and are much easier to test and to maintain. Modifying global objects can make debugging very painful.
Use the smallest possible type for parameters (or the most general/abstract). This means, your method doesn't need the XDocument, it can do its job just fine with an IEnumerable<XElement>.
Choose more meaningful method names. UpdateParams is too general and doesn't say anything about what is going to be updated.
You neither need the foreach, nor Where, nor Any, nor Single, nor the null check. All this can be replaced by a much nicer join.

This is how it could look like after refactoring:

private static IEnumerable<Param> ScaleParameterValues
(
    IEnumerable<XElement> elements,
    IEnumerable<Param> parameters
)
{
    return
        from xe in elements
        join p in parameters on xe.Name.LocalName equals p.xmlName
        select new Param(p.xmlName, p.scalingFactor)
        {
            Value = p.scalingFactor * double.Parse(xe.Value)
        };
}


Writing a Python class that provides default instance succinctly

I'd say a much easier way to accomplish this is to use a module instead of a class.  In a language like Java the primary form of encapsulation is a class, while in Python, the primary form of encapsulation is a module.  For example,

foo.py

class Example:

    def __init__(self, customizable):
        self.customizable = customizable

    def do_something(self):
        print("*** {} ***".format(self.customizable*2))

default_instance = Example(0)

main.py

import foo

my_foo = foo.Example(20)
my_foo.do_something()

foo.default_instance.do_something()

Output:

*** 20 ***
*** 0 ***

If you really wanted the default instance to be a class level attribute of Example, then you could add this line to foo.py

Example.default_instance = Example(0)

Personally, I don't think making this read only adds that much value; in general we let people do what they want in Python (that's why we don't have language defined private/protected/internal/public/etc features).  If the user wants to mess with something they shouldn't, that's on them.


Finding the maximum inclusive distance between two duplicate numbers in an array

Avoid unnecessary flag variables

The variable duplicate is unnecessary, because you could drive the same meaning from highestSpan > 0. It's an extra hurdle to keep this flag, I suggest to drop it.

Improving the algorithm

I believe this can be solved in \$O(N)\$ time and space, by using a map to record the position of the first occurrences of numbers. If a number was seen already, check the distance and update the max distance if necessary. Otherwise record the current position.


You have two nested while loops, so your solution is O(n2). A good solution should be possible in O(n) — that is, one pass through numbers.

Also, the while loops are rather clumsy. Idiomatic Ruby would usually use #each to iterate, or #each_with_index if you need the indexes as well. Here, you don't care about the indexes. If you return as soon as you have encountered a solution, it will necessarily be the leftmost solution.

require 'set'

def sum_pairs(numbers, sum)
  seen = Set.new
  numbers.each do |n|
    return [sum - n, n] if seen.include?(sum - n)
    seen.add(n)
  end
  nil
end


Starting from minor issues - please follow naming conventions (variables should be camelCased and methods PascalCased, do add access modifiers, give variables meaningful names).

Your design breaks Open-Closed principle: Queue knows all the possible commands it can handle. In case when you need to add a new command you'll have to change the queue rather than add new code.

Also it breaks Single Responsibility Principle since queue knows not only about scheduling the execution but also serves as a repository for all possible actions to be run for commands.

Both issues as well as those you have mentioned (type casting, different signatures) can be easily solved if you create a separate class per command type. Command will encapsulate parameters required for execution as well as the action to be executed:

public interface ICommand
{
    void Execute();
}

public class ScaleDveCommand : ICommand
{
    public CgManager CgManager { get; set; }
    public string FirstString { get; set; } //TODO:Rename to meaningful name
    public string SecondString { get; set; } //TODO:Rename to meaningful name
    public bool SomeBool { get; set; } //TODO:Rename to meaningful name

    public void Execute()
    {
        dispatcher.Invoke(() => CgManager.ScaleDVE(FirstString, SecondString, SomeBool));
    }
}

public class PlayAnimationCommand : ICommand
{
    public CgManager CgManager { get; set; }
    public VideoTemplate VideoTemplate { get; set; }
    public string SomeMeaningfulNameHere { get; set; } //TODO:Rename to meaningful name

    public void Execute()
    {
        dispatcher.Invoke(() => { CgManager.playAnimation(VideoTemplate, SomeMeaningfulNameHere); });
    }
}

And your "queue" class will look like:

public class RfxQ
{
    private readonly SortedList<long, ICommand> _queue = new SortedList<long, ICommand>();   // The queue of events

    public void PushEvent(ICommand command, TimeSpan delay)
    {
        _queue.Add(DateTime.Now.Add(delay).Ticks, command);
    }

    // This is actually done in a thread. Simplified here
    private void ExecEvent()
    {
        ICommand command;
        // item is pulled from _queue here
        command.Execute();
    }
}

And usage will look like:

q.pushEvent(new PlayAnimationCommand
    {
        CgManager = _cgManager,
        VideoTemplate = template,
        SomeMeaningfulNameHere = "inserton"
    }, TimeSpan.FromSeconds(3));


First off, as far as I remember the gif is only loaded once regardless of how many there are on the page (Just opened the dev tools on that page and it does. Thank you crystal ball.) So HTTP request overhead isn't a problem.

As for rendering, slower machines and browsers will tend to crawl when rendering a lot of animated gifs. So 40 of those would considerably be a pain to do.

Now off to your code, yes it is a problem because you are you are getting all .play on every mouseenter, create and append a new image object for each of them. The overhead lies in the creating of a jQuery object for the .play set on each mouseenter as well as the generation of an image for each .play on each mouseenter.

I think the JS solution is better because it doesn't render 40 animated gifs all at once, and your code can be tweaked a bit for optimization. We can create the image just once and move it around using appendTo. Also, since the mouseover handler already has a reference to the target being hovered, we can use that as target for appendTo.

// Create an image just once
var img = $('<img src="http://media.giphy.com/media/5Vb7xQB7Z3ScE/giphy.gif">');

// Since we can't hover on .play because it's behind .img-circle, we designate
// .img-circle as our hover target, and use previousSibling to get the .play
$('.day').on('mouseover','.img-circle',function(event){

  // Here, we are not generating any new objects. img and this.previousSibling
  // are already provided for
  img.appendTo(this.previousSibling);
});

Here's a working demo


Function to remove specified html tags from string

Alright!  You made me do it.  I'm posting an answer :)

Parsing arbitrary HTML via regular expressions is nearly impossible.  If you were using this on HTML code that you control yourself, it is certainly possible, because you can make sure that all of the edge cases never happen.  However, if you are going to set this loose on arbitrary HTML from the internet, you will find that it fails to work in a number of cases.  Your use case is a little simpler because you are just trying to remove the tags themselves (and not their contents), but even still it can be surprisingly tricky.  You probably need a straight-up HTML parser.  There are a bajillion of them for PHP.  Other than the easy ones I mentioned in my initial comment, here are some more variations that I think will completely sink your current code.  I have actually seen this first one in use on the intertubes: it is technically valid HTML:

Hover me

Another good one: your new regular expression allows for more flexibility in the tag contents at the expense of tag specificity.  In other words, I'm pretty sure that if you use your script to try to remove  tags, you will also end up removing
 tags.

These, and the examples in my initial comment, are some exceptions I came up with just off the top of my head.  In contrast, the internet cumulatively has a bajillion hours experience writing hard-to-parse HTML strings.  Sure, your code might even work 90% of the time, but if you stick with regular expressions it will definitely fail on a regular basis.  It's up to you to decide if the failure rate is low enough.

Especially important: If you are trying to use this as a security tool then definitely don't.  It is nowhere near reliable enough.  Sorry.  It's not that your algorithm isn't well thought out.  It's just that HTML is a full dialect that needs an actual parser: regular expressions just aren't meant for this kind of thing.  It's like trying to build an actual house out of toothpicks.

See this similar question/answer:

Regex to remove inline javascript from string


Dig through the source code for expm, which leads ultimately to a rather extensive bit of code in scipy.sparse.linalg.matfuncs.py.  This uses a well known Pade approximation.  It is specifically designed to work with on a square nxn matrix.  So generalizing to a (m, n, n) matrix without iterating on m does not work.

Years ago I sped this up by using f2py to calculate an analytical (n,3,3) inverse.  But I recall a simpler expm implementation.  The current one appears to have a lot of helper functions and special cases, presumably hoping to gain speed.

If your matrix is always (m, 2,2) there might be a special case.

This might be better as a Stackoverflow question, since it has less to do with programming style or code organization, and more with calculation alternatives in the numpy and scipy libraries.  But a SO search for expm and numpy/scipy turns up very few questions.  The closest suggests looking at the source code just as I suggested.


Controller action to process orders and payments

I would suggest using a service object. I would like to see what others think about this. It looks like there's too much going on for the controller.

The controller should be responsible for execution and value return. The model for processing the object. The service for wiring up the object and giving it prepared params to do its job.

This is not tested, but just to give you an idea. I would go further and condense the paid! and process! methods in the model so that the service just receives an error or an OK to give back to the controller.

def create
  @order = OrderCreationService.new(params).process

  if @order.processed?
    render json: { status: 200 }
  else
    render json: { error: @order.errors }
  end
end

Your service would look something like this:

require 'json'

class OrderCreationService
  attr_reader :order_params, :customer_params, :payment_method_nonce, :errors

  def initialize(params)
    @order_params = JSON.parse(params['order'])
    @customer_params = JSON.parse(params['customer'])
    @payment_method_nonce = JSON.parse(params['payment_method_nonce'])
    @errors = []
  end

  def process
    order = Order.create_from_result(order_params, customer_params)

    if order.persisted?
      result = order.make_payment(payment_method_nonce)

      if result.success?
        order.process!
      else
        errors << result.message
      end
    else
      errors << order.errors
    end

    self
  end

  def processed?
    errors.none?
  end
end

Some would argue that a service object adds a needless complication. They may have a point. I think it depends on each use case.


You don't need to create the database file if it doesn't exist, the SQLite driver will take care of it; to ensure your table does not exist on creation, you can just add IF NOT EXISTS to the query.

I would also close the connection every time, this has already been covered by other answers. In addition I would make the class stateless as it doesn't need a state if we open/close the connection every time (Being stateless brings a lot of other advantages).

I would also remove any logic from the constructor, to do this you will need a state or you will have to check on every command unfortunately so I left it to you.

Here is my 0.02:

internal class Timesheet
{
    private const string SelectTaskQuery = "SELECT id, description, begindate, enddate, status FROM task";

    private readonly string _filePath;

    public Timesheet(string filePath)
    {
        _filePath = filePath;

        InitializeDb();
    }

    private DataTable Tasks() => ExecuteWithConnection(Tasks);

    private void InitializeDb() => ExecuteWithConnection(connection =>
    {
        using (var command = connection.CreateCommand())
            CreateSchemaIfNotExists(command);
    });

    private SQLiteConnection GetConnection() => new SQLiteConnection("Data Source=" + _filePath + ";Version=3;");

    private void ExecuteWithConnection(Action<SQLiteConnection> action)
    {
        using (var connection = GetConnection())
        {
            connection.Open();

            action(connection);
        }
    }

    private T ExecuteWithConnection<T>(Func<SQLiteConnection, T> action)
    {
        using (var connection = GetConnection())
        {
            connection.Open();

            return action(connection);
        }
    }

    private static DataTable Tasks(SQLiteConnection connection)
    {
        var adapter = new SQLiteDataAdapter(SelectTaskQuery, connection);

        var datatable = new DataTable();

        adapter.Fill(datatable);

        return datatable;
    }

    public void Update(DataTable dataTable)
    {
        ExecuteWithConnection(connection =>
        {
            var adapter = new SQLiteDataAdapter(SelectTaskQuery, connection);

            var builder = new SQLiteCommandBuilder(adapter);

            adapter.Update(dataTable);
        });
    }

    private static void CreateSchemaIfNotExists(IDbCommand command)
    {
        const string query = "CREATE TABLE IF NOT EXISTS task (id INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT, begindate TEXT, enddate TEXT, status INTEGER default 0)";

        command.CommandText = query;

        command.ExecuteNonQuery();
    }
}

I would also add a small ORM like Dapper and add statically typed entities for insert/update.


Styling

You can align centered elements relatively to their parent.

#middle {
  margin-left: 900px;
  margin-top: 300px;
}

#middle {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  top: 50%;
  transform: translateY(50%);
}

Naming

In my opinion, for algorithms it is OK to use short variable names.

let first_row = document.getElementsByClassName('row1');
let second_row = document.getElementsByClassName('row2');
let third_row = document.getElementsByClassName('row3');
let sudoku = [
  [first_row[0].value, first_row[1].value, first_row[2].value],
  [second_row[0].value, second_row[1].value, second_row[2].value],
  [third_row[0].value, third_row[1].value, third_row[2].value]
]

let r1 = document.getElementsByClassName('row1');
let r2 = document.getElementsByClassName('row2');
let r3 = document.getElementsByClassName('row3');
let sudoku = [
    [r1[0].value, r1[1].value, r1[2].value],
    [r2[0].value, r2[1].value, r2[2].value],
    [r3[0].value, r3[1].value, r3[2].value]
]


A C function for returning the address of the calling function

Didn't totally work
After porting the code to gnu C style, it only "sort of" worked for me.  I was able to have foo() print that it was called from bar() or baz().  However, if foo() was called directly from main(), then it crashed when trying to find its caller.  That's probably because on my system (Cygwin 32-bit, using Gnu C compiler), main() doesn't have a caller on the stack.
Clobbered register
It's not safe to write to ebx without pushing it on the stack and popping it off later.  ebx is considered non-volatile, which means that a function must preserve its value.  If you don't, then the calling function will be affected because its local variable may be stored in ebx, for example.  You can safely use eax, ecx, and edx though, because they are all considered volatile registers (i.e. you are allowed to clobber them).  So you should change your ebx accesses to ecx instead.
Not portable
Your asm statement assumes that the compiler will insert these lines at the top of the function:
    pushl   %ebp
    movl    %esp, %ebp

That may be what your compiler does, but it's not a certainty.  For example, with my GNU C compiler, it normally outputs the above code.  But with the -O2 option, it does this instead:
    subl    $28, %esp

If you want to make sure that you get the function prologue you need, you should write the whole thing in assembly and include the prologue/epilogue you require.


Continued fraction with relative precision in Python

Nice code, it does what it should and it is short. But it can be improved :)

General python tips:

Use type annotation. You can look at the type annotation of Sam Stafford in the previous answer, it will make your code more readable and will prevent bugs.
Remove redundant imports. Is numpy really needed here? You can use a simple abs.
Don't use lambda functions. According to PEP 8 "do not assign lambda expression, use a def", there are several reasons why, mostly due to readability.

Optimisation tips:
Note these tips contradict each other. Choose one and use it but you cannot use both.

If N is the number of elements until convergence, and a and b is the calculation time of each function (Assuming equal for every x) The time complexity now is O(N ^ 2 * a * b), for each i you calculate the entire series over and over.
If you will use exponential search you can reduce the complexity to O(N * log N * a * b). Which will be much much faster!
Readability vs. Runtime. If the readability is important to you you can ignore this tip. You can replace the recursion with a dynamic programing approach, this will remove the recursion and the iteration over i, the time complexity will be O(N * a * b) but you will need to rewrite a lot of the code.


Since you have numpy arrays, you should use their vectorized methods wherever possible. This can make your code a lot faster:

In [1]: x = np.arange(10000000)

In [2]: %timeit max(x)
988 ms ± 42.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit x.max()
9.67 ms ± 114 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

This includes not casting your arrays to list.

I would also make this a function that normalizes a single array:

import pickle
import numpy as np
from typing import Iterable, Any

def normalize_one(x: Iterable[Any]) -> np.ndarray:
    if not isinstance(x, np.ndarray):
        x = np.array(list(x))
    low, diff = x.min(), x.ptp()
    return (x - low) / diff

# -- load data
prop_1    = np.random.rand(10)*20
prop_2    = np.random.rand(10)*10
prop_3    = list(np.random.rand(10)*30

# -- normalize
prop_1 = normalize_one(prop_1)
prop_2 = normalize_one(prop_2)
prop_3 = normalize_one(prop_3)

If you do have many arrays that need to be normalized, you can always do it in a list comprehension:

properties = [prop_1, prop_2, prop_3]
properties = [normalize_one(prop) for prop in properties]

If you have many of them and they all have the same structure, I would use something like this (now limited to numpy arrays as input):

def normalize(x: np.ndarray, axis: int = 1) -> np.ndarray:
    """Normalize the array to lie between 0 and 1.
    By default, normalizes each row of the 2D array separately.
    """
    low, diff = x.min(axis=axis), x.ptp(axis=axis)
    # Indexing needed to help numpy broadcasting
    return (x - low[:,None]) / diff[:,None]

properties = np.random.rand(3, 10)
properties[0] *= 20
properties[1] *= 10
properties[2] *= 30

properties = normalize(properties)

For props = np.random.rand(10000, 10) I get the following timings:

Author      Timed function call                       Time [s]
Blade*      list(normalize_blade(props))              68.7 ms ± 749 µs
Linny       list(normalize_linny(*props))             127 ms ± 1.42 ms
Graipher    [normalize_one(prop) for prop in props]   119 ms ± 7.4 ms
Graipher    normalize(props)                          2.32 ms ± 113 µs

The code I used for the test with the code in the OP is this one, which is just the generalization to many properties:

def normalize_blade(properties):
    l_bound, u_bound = [], []
    properties = [list(prop) for prop in properties]
    for prop in properties:
        l_bound.append(min(prop))
        u_bound.append(max(prop))
    for i, prop in enumerate(properties):
        yield (np.array(prop) - l_bound[i]) / (u_bound[i] - l_bound[i])


Implementing multiple Producer Consumer using custom Blocking queue

Your produce and consume methods are both buggy for the same reason: you've got a time of check/time of use bug.

Imagine a queue with size 1. Start two producer threads at the same time. They'll both see queue.size() == 0 in produce() and they'll both happily proceed to queue.add() without a lock, overflowing your queue (and causing other problems if that add() method isn't thread-safe itself).

Same thing exactly on the consumer side. If there's one item in the queue and two threads enter consume() at the same time, both will try to extract an item and at least one will fail.

You need to hold a lock that covers the check and the produce/consume actions.

You can't call notifyAll() on an object unless you own the object's monitor. You'll get a IllegalMonitorStateException if you try to run your code.


I want my money back!
Your total is 15
Dealer has a 4 showing.
[H]it or [S]tay?
s

It is now the dealer's turn!

The player has 15.
The dealer has 23.   <<=====

The dealer wins!     <<=====

Your casino is cheating! Also you're not handling aces, all face cards are supposed to have a value of 10, and there are 13 ranks in a suit but your getCard function can only return 11 different values (2 to 12).
This means that you can lose right off the bat:
$ ./a.out
================================
Your total is 24       <<======     :-(
Dealer has a 9 showing.
[H]it or [S]tay?

In turn, if the player enters h and doesn't bust, you're not setting stay - this happens to work given the code flow, but it looks odd. Set it before returning.
If the user enters gibberish, you always interpret that as stay. That's not user-friendly.
In main:
bool stay;
char choice = NULL;

That's not a valid initializer for a char - chars are not pointers. And leaving a variable (stay) uninitialized is not a good idea. You should move stay inside the loop, only declare it when you give it its first value. (I'd also use two separate variables for the dealer and the player.)
Remove choice from main altogether. Only turn needs it, so handle the user input in there completely. (And have turn return hit/stay so you don't need that out parameter.)
This shouldn't be inside the loop:
std::srand(std::time(0));

You should initialize the RNG only once, do that at the very start of main. C++11 introduced new random generation facilities, you should look into them.
These lines are too long:
// Display winner
std::cout << "\n\nThe player has " << pTotal << ".\nThe dealer has " << dTotal << ".\n\n";
if ((std::abs(21 - pTotal)) < (std::abs(21 - dTotal))) std::cout << "The player wins!\n";
else std::cout << "The dealer wins!\n";

Try something like:
// Display winner
std::cout << "\n\nThe player has " << pTotal
          << ".\nThe dealer has " << dTotal << ".\n\n";

if ((std::abs(21 - pTotal)) < (std::abs(21 - dTotal))) {
  std::cout << "The player wins!\n";
} else {
  std::cout << "The dealer wins!\n";
}

And once you fix your logic so that a bust directly ends the players turn, and a dealer bust makes the player win, you can get rid of the std::abs since both scores will be at most 21.


Optimized list filtering on implementation of Project Euler 23

Add type signatures. Without type signatures, your integral types will default to Integer. So let us add type signatures:

projectEuler23 :: Int
projectEuler23 =
  let a = abundantNums 28124 in
  sum [x | x <- [1..28124], not $ isSumAbundant x a]

isSumAbundant :: Int -> [Int] -> Bool
isSumAbundant n a =
  any (\x -> (n - x) `elem` a) (takeWhile (<n) a)

abundantNums :: Int -> [Int]
abundantNums n =
  [x | x <- [1..n], (>x) $ sum $ properDivisors x]

properDivisors :: Int -> [Int]
properDivisors n =
  let  limit = (floor.sqrt.fromIntegral) n in
  [limit | limit^2 == n]
  ++ ((1:) $ concat [ [x, div n x] | x <- [2..limit - 1], rem n x == 0])

Note that a type signature on projectEuler23 would have been enough. Operations on Int are usually faster than Integer.

In isSumAbundant you can stop at n`div`2, e.g.

isSumAbundant n a = any (\x -> (n - x) `elem` a) $ takeWhile (<= (n `div` 2)) a

Similar in abundantNums, you can use scanl1:

abundantNums n =
  [x | x <- [1..n], any (x <) $ scanr1 (+) $ properDivisors x]

This models your "break" from imperative languages.