VCF parser for eventual genomic data visualization

Your code is good, but it could be improved:

Nesting

Try and avoid massive nesting like this, but reversing the conditions and continueing:

class Genome {
  constructor(name) {
      this.name = name
      // Find genotype by rs-ID without having to know chromosome
      this.findByRsId = (rs_id) => {
        for(var chr in this) {
          if (chr.substring(0, 1) === 'c') {
            for(var id in this[chr]) {
              if (id == rs_id) {
                return this[chr][rs_id]
              }
            }
          }
        }
      }

Into something a little less nested:

class Genome {
  constructor(name) {
      this.name = name
      // Find genotype by rs-ID without having to know chromosome
      this.findByRsId = (rs_id) => {
        for(var chr in this) {
          if (chr.substring(0, 1) !== 'c') continue;
          for(var id in this[chr]) {
            if (id != rs_id) continue;
            return this[chr][rs_id]
          }
        }
      }

Consistency

This is the only semi-colon you use in your entire script:

const fs = require('fs');

You should keep your consistency in check, and either do or don't use semicolons (I would suggest the former), but keep consistent.

Naming

You're shouldn't be sacrificing readability in your code just to save space.

getSampGenotype: Literally two characters missing to massively improve readability
handleGFGChunk: This could be improved, however I would assume those working your code would know what it means, I, on the other hand, don't.

What is rs??!??

You use the abbreviation/term rs everywhere in your code, but to anyone without a doctorate, this might not be clear.

switch it to better code:

Excuse the horrible pun there, but...

Your switch statement can be simplified:

      case '0':
        return rs.genotype
        break
      case '1':
        return rs.genotype
        break
      default:
        return rs.genotype
        break

Here, you're defining multiple cases that have the same result.

There's two ways to approach this problem, while the first is better for readability, it's redundant in this case not to use the second

switch statements use fall throughs, which means, if you don't explictly declare break, it will keep falling down and down.

Take this snippet for example:

document.getElementById("testbutton").addEventListener('click', function(){
    var sample = "ACTA",
        result = "";
    switch(sample){
        case "ACTA":
            result += "A";
        case "AATC":
            result += "B";
        case "UUCA":
            result += "C";
        case "FAIL":
            result += "D";
        default:
            result += "E";
    }
    document.getElementById("content").innerText = result;
});
<button width="200" height="200 id="testbutton">Test</button>

What do you think would print?

   You would expect that to print A, because it's the only case that matches, but because it falls through, it catches all of them and alerts ABCDE.

Change sample to UUCA and watch what happens:

   CDE is alerted.

Number 1: So, seeing as content inside a case is optional, as shown above, you can "merge" cases, like the following:

      case '0': case '1': default:
        return rs.genotype
        break

However, Number 2: default is a catch-all of sorts, anything that isn't declared as a case above is caught by default, so not declaring case '0' and case '1' is  the same as declaring them in this case.

Depending on how you feel about readability, you could make it look like:

      case '0': case '1': default:
        return rs.genotype
        break

Which, while redundant, it readably shows that cases 0, 1 have been considered and their result determined.

Indentation:

Your block at the moment, looks like this:

(function iife() {

'use strict'
class Genome {
  constructor(name) {
  }
}
})()

I see two things wrong with this:

After your IIFE declaration, there isn't an added indentation
You're using two-space indentation, when you should be using four-space indentation.

Duplication:

You have a bit of duplication in this code block:

if(!myGenotypes["chr_"+row[0]]) {
  myGenotypes["chr_"+row[0]] = {}
} else {
  // If no rs_[num] exists, make one and set it to genotype
  if (!myGenotypes["chr_"+row[0]][row[2]]) {
    myGenotypes["chr_"+row[0]][row[2]] = {
      'genotype': row[3]+row[4],
      'quality': row[6],
      'fit': row[9]
    }
  }
}

See how many times you needed to call "chr_" +row[0]? That's how you know you deserve a variable.

var propertyName = "chr_" + row[0]
if(!myGenotypes[propertyName]) {
  myGenotypes[propertyName] = {}
} else {
  // If no rs_[num] exists, make one and set it to genotype
  var subPropertyName = row[2]
  if (!myGenotypes[propertyName][subPropertyName]) {
    myGenotypes[propertyName][subPropertyName] = {
      'genotype': row[3] + row[4],
      'quality': row[6],
      'fit': row[9]
    }
  }
}

Magic numbers:

Building on the last point, you call array indexes at 0, 2, 3, 4, 6, 9:

What are these points? What is at row[0] that may or may not be in myGenotypes?

You ought to move these array indexes to their own variables to declare the importance that each of these indexes holds.

Object and array properties

An object's properties can be accessed in two different ways: Object.property or Object[property].

In JavaScript, an array is basically an object where the index position is the key, however you cannot use the first syntax option with arrays.

Normally, you would use the Object.property version to visually show that this variable is an Object and not an array,
whereas you would use Object[property] when you have to load the property in from a variable, and not specifically by name:

var property = "cats";
Object.cats == Object[property];

IIFE:

In your IIFE, you give it the name iife, however in an IIFE that function name has no meaning, the function itself is discarded in favour of its result, meaning the name is redundant.

Miscellanous:

  this.getRefGenotype = (rs_id) => {
    var rs = this.findByRsId(rs_id)
    return rs.genotype
  }

This can be simplified down to:

  this.getRefGenotype = (rs_id) => {
    return this.findByRsId(rs_id).genotype
  }


Find the Maximum Sum of a Contiguous Subsequence in a List

The first solution is quite fine, with minor issues:

It doesn't support empty list
Instead of for i in range(1,len(arr)):, it would be simpler to for value in arr[1:]:
Formatting and function naming doesn't follow PEP8

Given that the first solution is simple and efficient,
I don't see much point in a second solution that uses \$O(n)\$ extra storage.
Other minor issues with it:

It's strongly recommended to use consistent indent width (preferably 4 spaces)
It's recommended to use a line break after the : in a if cond: statement
If you are using Python 3, then use range instead of xrange
Some comments above for the first solution apply here too

Finally, the testing code is overcomplicated, when much simpler alternatives are supported out of the box, for example doctests:

def maxSubArraySum(arr):
    """
    >>> maxSubArraySum([6, -1, 3, 5, -10])
    13
    >>> maxSubArraySum([5])
    5
    >>> maxSubArraySum([])
    0
    >>> maxSubArraySum([-1, 1, -3, 4, -1, 2, 1, -5, 4])
    6
    """
    ...


Seeking the seeds for writing tidy event handlers in JS

The simple way of avoiding needing to define a named function like double_increment is just to use a lambda. You could simply write

d3.select('#inc').on('click',
    () => {
        incrementer1.increment();
        incrementer2.increment();
    });

You could also get fancy and loop through the incrementers too

var incrementors = [incrementer1, incrementer2]

d3.select('#inc').on('click',
    () => {
        for (inc of incrementors) {
            inc.increment();
        }
     };

This lets you easily add new incrementors later if needed.


Fetching data from a MySQL database using Promise

Resource leakage: put con.release() outside the else block.


Python class inheritance - using super() and __str__

In general, calling the parent class implementation, keeping the result and then processing it is perfectly acceptable OOP practice. However, there is a problem with your string handling; concatenation (+) is not the most efficient way of doing things (e.g. a + b + c becomes (a + b) + c, creating intermediate strings that aren't needed). Instead, when implementing __str__ and __repr__, you can use str.format, for example:

class Employee:

   ...

   def __str__(self):
      return '{0._name!s} {0._salary!s} {0._position!s}'.format(self)

class Director(Employee):

   ...

   def __str__(self):
      return '{0} {1.managementteam}'.format(super().__str__(), self)

You aren't entirely compliant with the style guide; for example, managementteam/mngteam should really be management_team. Additionally, you have an odd mix of private-by-convention (leading underscore, e.g. _salary) and public (no leading underscore, e.g. supervises) instance attributes - why? Should these be protected? Should the instance be immutable? Some docstrings would be nice, too.

I would be inclined to add some validation of inputs - for example, if salary should always be a positive integer, you could add checking for that. One way to do that is in __init__, but a more thorough approach is with a property:

class Employee:

    def __init__(self, ..., salary, ...):
        ...
        self.salary = salary  # note assignment to salary not _salary
        ...

    ...

    @property
    def salary(self):
        return self._salary

    @salary.setter
    def salary(self, new_salary):
        if new_salary < 0:
            raise ValueError('salary must be positive')
        self._salary = new_salary


I would do it as a singleton, so that the core functionality can be protected and private. All that is exposed is the Interface, .add(),start(),clear(),and the semaphore .done

Using prototype is only an advantage if the object that it belongs to is instanced many times. If you only create the object a few times, or once then adding to the prototype is actually more work for the javascript engine.

I also added a start method so that the queue could be created and started when needed. Once started you can add to the queue as long as done === false

// singleton. Assuming you only need one copy of timed queue
const timedQueue = (function(){
    var API;                // internal referance to interface
    const queue = [];       // array to hold functions
    var task = null;        // the next task to run
    var tHandle;            // To stop pending timeout
    function next(){  // runs current scheduled task and  creates timeout to schedule next
        if(task !== null){          // is task scheduled??
            task.func();            // run it
            task = null;            // clear task
        }
        if(queue.length > 0){       // are there any remain tasks??
            task = queue.shift();   // yes set as next task
            tHandle = setTimeout(next,task.time) // schedual when
        }else{
            API.done = true;
        }
    }
    return API = {
        add : function(func,time){
            queue.push({func : func, time: time});
        },
        start : function(){
            if(queue.length > 0 && API.done){
                API.done = false;   // set state flag
                tHandle = setTimeout(next,0);
            }
        },
        clear : function(){
            task = null;            // remove pending task
            queue.length = 0;       // empty queue
            clearTimeout(tHandle);  // clear timeout
            API.done = true;        // set state flag
        },
        done : true,
    }
})();

// usage.
function test1(){
    console.log("Test1 run");
}
function test2(){
    console.log("Test2 run");
}

timedQueue.add(test1,1000)
timedQueue.add(test2,1000)
timedQueue.add(test1,3000)
timedQueue.add(test2,100)
timedQueue.start();


My advice: don't do this.

Building devices that encourage you to write expressions that are useful only for their side effects is poor functional style.
You are abusing "Select" when you use it as an implementation detail of "ForEach". "Select" does not have the semantics of "ForEach"!  The purpose of "Select" is to compute a projection, not to cause a side effect.
You are building yourself a little time bomb. Because your implemenation of ForEach is to build a Select query, the "ForEach" executes lazily.  When you say "blah.ForEach(whatever);" that doesn't do anything. It just builds up an object that represents doing the side effects in the future.  Since you never use that object for anything, the side effects remain undone.  If, by contrast, you do use that object, you run the risk of using it twice and causing the same side effects again.

That said, the idea of what you're doing is sound; the idea of representing a sequence of side-effecting operations in a lazily-evaluated object is how side effects are represented in Haskell. But if that's what you want to do, then actually build yourself a real monad that clearly and unambiguosly represents the semantics of "I'm building an object that represents a sequence of side effects in the future". Don't be all coy about it! Be explicit that that's what you're doing.


This isn't really an Abstract Factory. Going on the theme of what you've got above (although I'm not sure what trains, planes and buses have to do with parsing!), an Abstract Factory would look something like the following:

public interface Parser
{
    List<ITransport> getBusList();
    List<ITransport> getTrainList();
    List<ITransport> getPlaneList();
}

public interface ParserFactory
{
    Parser getParser();
}

public class XMLParser implements Parser
{
     //Implementation of Constructors and Interface methods from Parser
}

public class CSVParser implements Parser
{
     //Implementation of Constructors and Interface methods from Parser
}

public class XMLParserFactory implements ParserFactory
{
    public Parser getParser()
    {
        return new XMLParser();
    }
}

public class CSVParserFactory implements ParserFactory
{
    public Parser getParser()
    {
        return new CSVParser();
    }
}

This is then used in some way like the following:

public class Main
{
    //Note: Using a String is for illustrative purposes only. Ideally
    //it should be using some system or file setting. Half the point
    //of this pattern is that the caller doesn't know what kind of
    //object they are getting back (which probably doesn't make too much
    //sense for parsers, really).
    public static ParserFactory createParserFactory(String type)
    {
        if(type.equals("XML") {
            return new XMLParserFactory();
        } else {
            return new CSVParserFactory();
        }
    }

    public Main(ParserFactory factory)
    {
        Parser parser = factory.getParser();
        List<ITransport> bus = parser.getBusList();
    }

    public static void main(String[] args)
    {
        new Main(createParserFactory("XML"));
    }

So what's the point of all this (it's quite a lot of code, after all). Well, firstly, it insulates the caller from knowledge of the concrete type. They don't know what kind of Parser they're getting back, the implementation details are hidden from them. Secondly, it localizes all object creation through a single point, which means client code will need very minimal updates when things change. For example, say we want to add a new kind of Parser - let's say a JSONParser - to our code. Then we create a factory and parser like we did previously:

public class JSONParser implements Parser
{ // Implementation details
}

public class JSONParserFactory implements ParserFactory
{
    public Parser getParser() { return new JSONParser(); }
}

Then we simply add it to our getParserFactory method:

    public static ParserFactory createParserFactory(String type)
    {
        if(type.equals("XML") {
            return new XMLParserFactory();
        }
        else if(type.equals("JSON") {
            return new JSONParserFactory();
        } else {
            return new CSVParserFactory();
        }
    }

Note that any client code will be calling createParserFactory() and then getParser from that - so ideally, if they want to switch in a JSONParser, the only thing that needs to change in their code is the call to createParserFactory("JSON").

Hopefully this has cleared things up a little bit (and not confused you too much).


Archiving data while running update statement

You don't need to change anything as long as the code performs what you need. If you want to insert records to another table on every update (and not only in this place) you should probably take a look at triggers


Quicksort implementation equivalent to Collections.sort()

As far as your understanding of generics, I think you've pretty much got it.

On other matters:

(x, y) -> x.compareTo(y) - that can be reduced to a function reference Comparable::compareTo.  In this specific case, it's also available to you as Comparator.naturalOrder()
You should double check your random number generator for getting your pivot.  It looks to me like you're taking a pivot element from anywhere in the list, not in the sublist that you're sorting.


There are only two versions of the main function:

/* 1 */
int main(int argc, char *argv[]) { ... }

/* 2 */
int main(void) { ... }

Note the void keyword in the second version. In C, if the function has no parameters it should be declared as

 <type> f(void)

Please, take a look at this SO answer for details.
Do not write one-line code:

for(int i = 0; i < counter; i++) if(strcmp(store_arr[i],arr_to_print)==0) return 1;

I'd rewrite it this way:

for (int i = 0; i < count; i++)
    if (strcmp(store_arr[i], arr_to_print) == 0)
        return 1;

Do not use int as type for array indexing. It is not guaranteed  that int can hold any possible index value of an array object. The only type that can hold any index of an array object is size_t. See this SO answer for details.
I'd replace

printf("\n");

with

putchar('\n');

Do not cast the result of malloc call. Really, you have to do it in C++, but not in C. See this SO question for details.
Do not repeat yourself. Consider this line:

int* n_arr = malloc(length * sizeof(int));

You declare n_arr as a pointer to int. It would be better to rewrite this line in this way:

int *n_arr = malloc(length * sizeof *n_arr);

In this case you don't have to change the expression of the sizeof operator if you change n_arr type. It is very common C idiom.
Do not computer factorial using recursion. It is really slow. Usually, you can just create the factorial table and hardcode it:

static const unsigned long long factorial_table[] = {
    1,
    2,
    6,
    24,
    120,
    720,
    ...
};

In this line:

char* src_arr = "ABCDE";

you create a pointer to a string literal. It would be better to create just a static array:

static src_arr[] = "ABCDE";

And you can make it const since it never changes:

static const src_arr[] = "ABCDE";


Calculating delta in SpriteKit using Swift

You are inconsistent with the optional semicolons.  It's optional in Swift, but all the example code I've seen from Apple excludes them.  They may be excluding them simply to drive home the point that they're not necessary, but it will probably end up being standard to exclude them.  Either way, you've included them in 3 lines and excluded them in 5.  Consistency is actually more important then what "best practice" says to do, and your code isn't consistent in this regard.
In Swift, the parenthesis around if statements are optional.  Like the semicolons, you've been inconsistent in this.  You include the parenthesis once and omit them once.  Again, all the example code I've seen from Apple omits them and that will probably become the Swift standard, but again, what's most important is consistency.
Perhaps in an effort to force some Swift into your code, you've needlessly declared delta as an optional.  There's no possible path through this method which results in delta being uninitialized, and that becomes pretty evident when we force unwrap it as we pass it to an argument expecting a non-optional.
updateWithTimeSinceLastUpdate() is probably copied over from a method that looks like this in ObjC: updateWithTimeSinceLastUpdate:, which might be okay.  It's a method called update that takes a variable which describes the timeSinceLastUpdate, right?  In Swift, the method might be a bit Swift-ier if timeSinceLastUpdate is actually the name of the argument: update(timeSinceLastUpdate:delta).  This makes it more clear.  The part outside the parenthesis describes what the method actually does, while the part inside the method describes what sort of arguments to send.


Processing a string containing product variants

This code is not very easy to follow.

(I am going to assume that the variables $search_db_row['variations'] and $variation where previously initialized)

Firstly, Your spacing is not very clear:
This way:

$variations = explode("|", $search_db_row['variations']);

foreach ($variations as $variations_arr1) {
    $variations_arr1_exp = explode("-", $variations_arr1);
    $variations_arr[$variations_arr1_exp[0]][] = $variations_arr1_exp[1];
}

foreach ($variations_arr as $variations_arr2k => $variations_arr2v) {
   $variation.= $variations_arr2k.": ";
   foreach ($variations_arr2v as $variations_arr2_value) {
      $variation.= mb_strtolower($variations_arr2_value, "utf-8").", ";
   }
}

makes it easier to see what is connected to what.

Secondly, consider changing the variable names.
Something like this:

$initial_variations = explode("|", $search_db_row['variations']);

foreach ($initial_variations as $initial_variations) {
    $each_variation = explode("-", $initial_variations);
    $variations_arr[$each_variation[0]][] = $each_variation[1];
}

foreach ($variations_arr as $variation_types => $variations_values) {
   $variation.= $variations_types.": ";
   foreach ($variations_values as $variations_value) {
      $variation.= mb_strtolower($variations_value, "utf-8").", ";
   }
}

Makes it easier to follow because the variable names themselves tell me what is happening.

As far as reducing the code/getting rid of the foreach's, you could try like this:

foreach ($initial_variations as $initial_variations) {
    $each_variation = explode("-", $initial_variations);
    if ($previous_type != $each_variation[0]){
        $variation .= $each_variation[0].": ";
    }
    $variation .= mb_strtolower($each_variation[1], "utf-8").", ";
    $previous_type = $each_variation[0];
}

two more points (homework):

you have a trailing comma at the end of each group (this prints Size: xs, xl, Color: red, green, instead of Size: xs, xl Color: red, green)
this could use a comment (or two)


Euler Project 14 Longest Collatz Sequence

Useless calls to int

When n is an integer:

n * 3 + 1 is an integer as well, you don't need to call int
int(n / 2) can also be computed using the "floored quotient" with the // operator.

You don't need a class

I highly recommend watching Jack Diederich's talk called "Stop Writing Classes". Classes are a great tool but they are not always needed, sometimes the problem can be solved with simple tools like functions.

In your case, the whole class can be restricted to a simple function, shorter, clearer, more efficient, easier to use.

def get_collatz_length(n):
    if n == 1:
        return 1
    return 1 + get_collatz_length((3 * n + 1) if (n & 1) else n // 2)

You don't need recursion

Once again, recursion can be a great way to write a concise solution for a given problem. However, in Python, it is sometimes best to avoid it: there is no tail-recursion optimisation and the call stack has a fairly limited size.

You could write something like:

def get_collatz_length_loop(n):
    l = 1
    while n != 1:
        n = (3 * n + 1) if (n & 1) else n // 2
        l += 1
    return l

To be continued: memoization

Is bitwise optimisation relevant?


Scan the user input and then work with these letters

You just wrote this program and it's perfectly clear in your mind, imagine to come back after 1 year: you will need to re-read everything to understand what it is doing because everything is in one big function (which is also hard to test, something you will definitely love to have when writing production code).

First of all let's split the logic into smaller functions, do it in small steps:

#define MAX_INPUT_LENGTH 10

int main()
{
    char input[MAX_INPUT_LENGTH + 1] = {0};
    if (!read_input_text(input, MAX_INPUT_LENGTH))
        return EXIT_FAILURE;

    while (1)
    {
        print_menu();

        switch (read_menu_option())
        {
            case 0:
                puts("KONEC PROGRAMU, SEE YOU SOON :) ");
                return EXIT_SUCCESS;
            case 1:
                print_input(input);
                break;
            case 2:
                print_count_lowercase_letters(input);
                break;
            case 3:
                print_digits(input);
                break;
            case 4:
                print_input_toggled(input);
                break;
            default:
                puts("Invalid option.");
        }
    }

    return EXIT_SUCCESS;
}

You can further split this code and menu may be well handled with a dictionary of functions to call (it will be easier to extend) but I think you understand the point. Few things to note:

I initialized input to zero, now you do not need to last_index because you simply can use strlen(). Also to print the string is as simple as puts(input) because you  have a valid null terminated C string (note the extra array item added to hold the string terminator).
Variable-length arrays are a subtle thing, you may avoid them unless they're absolutely required.
I'm using EXIT_SUCCESS instead of 0, it's a small thing but I think it helps to make the intent clear (and it's easier to search...)
I'm using puts() instead of printf() when I simply need to print a string to stdout: it's faster, easier and better communicate the intent (compiler may also detect what you're doing and use puts() for you, BTW).

Now let's examine the core logic. As you can already imagine the input function might be simplified:

bool read_input_text(char* input, size_t maximumLength)
{
    for (size_t i=0; i < maximumnLength; ++i)
    {
        int c = getchar();

        if (c == EOF)
            return false;

        if (c == '.')
            return true;

        input[i] = (char)c;
    }

    return true;
}

Few notes:

I'm using a for loop to read needed characters, I think it's shorter and easier to understand than the equivalent while.
I check for EOF, user may press CTRL+D/CTRL+Z or stdin may be redirected and input file may be too short. As Chux noted you may consider EOF when string is still empty as a valid input (returning true).
When user type . I do not write it to input and because it's already zeroed then I simply can exit.
I'm using bool and other macros defined in stdbool.h.
I'm not allocating memory in this function, you may also change it to be char* read_input_text() but it's less error-prone (in bigger programs) to have a clear ownership for dynamically allocated memory.
read_input_text() is assuming that input is already zeroed. In true production code this should not be the case (less function interface requirements mean less bugs...) You may try to change it to append a trailing 0 where appropriate (tnx Chux, again, to point this out.)

How to count for lowercase letters? You're doing that manually but it's little bit hard to read because you're using magic numbers, let's try to write a small function:

int count_lowercase_characters(char* text)
{
    int count = 0;

    for (size_t i=0; i < strlen(text); ++i)
    {
        if (text[i] >= 'a' && text[i] <= 'z')
            ++count;
    }

    return count;
}

Using 'a' and 'z' instead of their ASCII values makes code easier to understand (I personally do not remember ASCII codes...) and less error-prone. But, hey...isn't it a very common task? There is a standard function for that, let's use it:

int count_lowercase_characters(const char* text)
{
    int count = 0;

    for (size_t i=0; i < strlen(text); ++i)
    {
        if (islower((unsigned char)text[i])
            ++count;
    }

    return count;
}

Note:

I'm directly using strlen() and loop variable is size_t. Note that it's not mandatory for size_t to be equivalent to int!
I'm using int even if unsigned (or even better size_t) might be more appropriate, don't go into academic discussions about this...
I declare text as const char*, I'm not going to modify the pointed value. Later you may want to declare it as const char* const but no need to go that far, now (also consider to declare it as char const *, it may be easier to pick when beginning).
I'm casting text[i] to unsigned char, if your compiler is aliasing char to unsigned char then you do not need it. See also Do I need to cast to unsigned char before calling toupper?

To write print_count_lowercase_letters() should now be trivial. As you can imagine there is also a similar function isdigit() to determine if a char is a digit (0..9) to use in print_digits().

The last function we have to go through is the one to toggle the case:

if (islower(text[i]))
    text[i] = toupper(text[i]);
else if (isupper(text[i]))
    text[i] = tolower(text[i]);

In this case I'm toggling the original string but you may simply write it to stdout. Note that you're using printf() to print a single character, there is an easier way:

if (islower((unsigned char)text[i]))
    putchar(toupper(text[i]));
else if (isupper((unsigned char)text[i]))
    putchar(tolower(text[i]));
else
    putchar(text[i]);

Notes:

I'm using putchar() to print a single character to stdout. Easier and faster.
I'm using islower() and isupper() to determine the case of the character. If you can't use these library functions then write your own function to reuse.
I'm using tolower() and toupper() to perform case conversion. Again if you can't use them then write your own, you will gain in legibility.
Last else has been greatly simplified, string is user input then it already contains printable characters, everything else which is not a letter should simply go untouched.
I didn't write it but the loop is similar to the previous function for (size_t i=0; i < strlen(text); ++i). See very last paragraph for more info.

In this examples I didn't consider any optimization, you will soon learn that strlen(text) as condition in a for loop is relatively terrible from a performance point of view (because outside very simple cases compiler isn't able to determine that it can be optimized and evaluated just once). The same loop may then be rewritten (few solutions ordered for complexity+speed).

To evaluate strlen(text) just once:

for (size_t i=0, n = strlen(text); i < n; ++i)

To manually stop when encountering string terminator:

for (size_t i=0; text[i] != 0; ++i)

To fully use pointers arithmetic:

for (char *p = text; *p; ++p)


There is absolutely no need to call Math.abs for generator.nextInt() since nextInt will never produce a negative number. Also, your last else-statement is impossible to happen so you can erase that one.

There is also no need to use the modulo (%) operator to fix your direction variable to the correct range when you instead can supply an integer value to the nextInt method. generator.nextInt(4); will give you a value from 0 to 3 (inclusive).

It is a Java coding convention to indent your code properly, after each { the next line should have one more indentation step, like this:

void moveSouth() {
    this.y += 1;
}

The below might be a little bit over your level, but it is a really nice solution and is very useful to learn. When you are dealing with four directions, I would create an enum to help with the different direction possibilities.

public enum Direction4 {
    NORTH(0, -1), EAST(1, 0), SOUTH(0, 1), WEST(-1, 0);

    private final int dx;
    private final int dy;

    private Direction4(int dx, int dy) {
        this.dx = dx;
        this.dy = dy;
    }
    public int getX() { return dx; }
    public int getY() { return dy; }
}

Using this enum, you can simplify several things of your other code. For starters, you can replace your move-methods with one single move method:

void move(Direction4 direction) {
    this.x += direction.getX();
    this.y += direction.getY();
}

And when generating the direction to move at, you can use the Direction4 enum:

// Get an index number and input the "size" of the enum to `nextInt`
int directionIndex = generator.nextInt(Direction4.values().length);

// Get the direction from the index generated above
Direction4 dir = Direction4.values()[directionIndex];

// Make the move:
drunkard.move(dir);

It might be subjective whether four different moveNorth, moveSouth etc. methods are preferable instead of using a single move-method that takes the direction as an argument. I myself find that using an enum redures the amount of code and it makes the code flexible and scalable (if you want to add or modify existing directions you can do so, for example adding MEGA_NORTH that moves 10 steps north just for fun).

If you don't perform the enum approach, then at least use a switch

direction = generator.nextInt(4);
switch (direction) {
    case 0:
        drunkard.moveNorth();
        break;
    case 1:
        drunkard.moveEast();
        break;
    case 2:
        drunkard.moveSouth();
        break;
    case 3:
        drunkard.moveWest();
        break;
}

Although I must say: There's not much that beat a nice little enum :)


Creating cover traffic by calling random urls - Javascript loop to decrement float

The problem JSLint is pointing at is that you usually iterate with an index that is an integer. If you were to have an array, you couldn't use i to access the array elements, because if i is big enough, rounding issues may cause you to skip elements or see elements twice!

What I'd recommend is that you just use i as integer, and then once the for loop is done, check if there is an additional chance to roll for. That way, you don't have to worry about floating point rounding errors accumulating.

Another way you could do it is first roll, and then if you roll high enough, up i by 1. That way you only have one place where you run your code.

So like this:

var chance = i % 1;
if (chance !== 0 && withProbability(chance)){
    i = Math.ceil(i);
} else {
    i = Math.floor(i);
}
//for loop goes here


Any way to optimize or improve this python combinations/subsets functions?

This type of problems lend themselves very well to recursion. A possible implementation, either in list or generator form could be:

def all_subsets(di, i) :
    ret = []
    for j, item in enumerate(di) :
        if i == 1 :
            ret = [(j,) for j in di]
        elif len(di) - j >= i :
            for subset in all_subsets(di[j + 1:], i - 1) :
                ret.append((item,) + subset)
    return ret

def all_subsets_gen(di, i) :
    for j, item in enumerate(di) :
        if i == 1 :
            yield (j,)
        elif len(di) - j >= i :
            for subset in all_subsets(di[j + 1:], i - 1) :
                yield (item,) + subset

>>> all_subsets(range(4), 3)
[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]
>>> list(all_subsets_gen(range(4), 3))
[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]

If you are going to run this on large sets, you may want to memoize intermediate results to speed things up.


Some ideas:

Separate the GUI code from the logic.
If you stay with your current mixed code fail fast. If conn is null there no sense to open the file or ask the user to choose one.
JFileChooser.getSelectedFile() returns a File instance, pass it to FileInputStream directly, don't concatenate strings. File contains the absolute path.
It's a good practice to pass a Charset (or "UTF-8") the the constructor of the InputStreamReader. The default could vary from system to system.
The DataInputStream looks unnecessary. You can pass the FileInputStream to the InputStreamReader directly.
Consider using Guava's readLines.
Maybe you want to report all executed queries, so the if (rc == 0) condition is unnecessary.

Plus it lacks of proper exception/error handling and resource closing as others mentioned in the comments.


Using one function to go from one element to another

The answer depends, for me, on many things. Some are:

is it a prototype or not? Looks like it is
are you in a rush? If so, do whatever works for you IF it's a prototype.
how big will the whole project be?

Here's a list of things that bother me:

Function name: from? Might make sense to you but it's not a very good name. It's too...generic. I'd take swissArmyKnifeFromElement over from any day - easy to remember, hard to confuse. If this method is somehow part of an object (like your Tree), then it might be OK for a private function.
The arguments might mean something else too - start and end suggest a range. It's potentially misleading. end can be many things (two, so far): a rule, like 'node' or 'child_list' or a class name. Again, misleading - it will only bring pain.

function findTreeElements(root, rule, params)
{
  //implementation
}

//you could call it like this
findTreeElements(a,'class',{'name':'someClassName'});
findTreeElements(a,'headline');

The more your project grows, the more complex this function will become - in ways that you cannot foresee :) Maybe that's why your friend was talking about objects and multiple functions. jQuery uses objects everywhere and I think that you should do that too:

define a tree/list object
define a task/node/whatever object
have the tree keep a list of tasks/nodes/etc
define the methods for manipulating the tree/node/whatever inside the associated objects

something like (totally random, possibly related, example):

var list = tree.findNode(someNodeNameOrIndex).tasks();

It's up to Tree object to manage its list of nodes and implement the findNode method (that parses the DOM whatever way you like).

It's up to the Node object (returned by Tree's findNode) to manage the list of tasks inside that node (or something similar) and implement the tasks function which would work in a similar way to your current find(elem, 'child_list').

Look at the code written by 'better' javascript developers and learn from them. There are many good projects out there that can teach you a lot. Look for decent sized projects, not 'plugins' or basic snippets; browser extensions are also good candidates.


Efficient Pandas to MySQL "UPDATE... WHERE"

You have eight conditions to match for every UPDATE.  A typical solution would store timestamps using a DATETIME or TIMESTAMP column, so that there is only one value to match.

For reasonable performance, ensure that the timestamp field is indexed.


Since we are talking about sets, it's probably better to use collection types that represent a set: HashSet<T> and ISet<T>.

Another improvement you can make is to keep track of the boxes you've added to current set at the last iteration (horizon of your expansion), and try to match candidate boxes only with them.

Note that resulting solution doesn't use the knowledge about box matching logic, so it might be a good idea to extract the interface that defines the connection between elements (i.e. a method that checks for the presence of link between nodes).

As a result I've got the following solution:

public interface IConnected<in T>
{
    bool IsConnectedTo(T other);
}

public class Box: IConnected<Box>
{
    ....

    public bool IsConnectedTo(Box other)
    {
        return Overlaps(other);
    }
}

And the FindUnconnectedSets:

public static List<ISet<T>> FindUnconnectedSets<T>(IEnumerable<T> boxes) where T : IConnected<T>
{
    var remainingBoxes = new HashSet<T>(boxes);
    var unconnectedSets = new List<ISet<T>>();

    while (remainingBoxes.Count > 0)
    {
        var newBoxes = new[] { remainingBoxes.First() }; //on each iteration will contain newly added boxes to current set
        var currentSet = new HashSet<T>();
        unconnectedSets.Add(currentSet);

        do
        {
            currentSet.UnionWith(newBoxes);
            remainingBoxes.ExceptWith(newBoxes);
            newBoxes = remainingBoxes
                .Where(remainingBox => newBoxes.Any(setBox => setBox.IsConnectedTo(remainingBox)))
                .ToArray();
        } while (newBoxes.Length > 0);
    }

    return unconnectedSets;
}


Interfacing with instruments using pyvisa

Your code so far looks pretty good - well structured, useful docstrings, well done! You mention exceptions; the one occasion you use it seems fine to me.

Per the style guide, e.g. visaName should be visa_name. Also, rather than commenting pyvisa -- a pyvisa object for the connection, avoid using., it is conventional to prepend the names of attributes that shouldn't be used externally with a single underscore: _pyvisa.

Rather than including @author in your docstring, you could use one of Python's special module attributes:

__author__ = 'Jack Barraclough'

get methods aren't very Pythonic. Instead, I would suggest you use properties, for example:

@property
def R(self):
    """Get R value from the instrument, returns a float"""
    self.write('MAG.')
    return float(self.read())

Now, rather than instrument.get_R(), you can type simply instrument.R.

Going further, there is a lot of duplication - every single one calls self.write then returns the value from self.read. You could factor this out entirely:

class Instrument:

    PROPERTIES = {'R': 'MAG.', ...}

    def __getattr__(self, attr):
        if attr in self.PROPERTIES:
            return self._get(self.PROPERTIES[attr])
        msg = "{!r} object has no attribute {!r}"
        raise AttributeError(msg.format(self.__class__.__name__, attr))

    def __setattr__(self, attr, val):
        if attr in self.PROPERTIES:
            raise AttributeError("can't set attribute")
        return super().__setattr__(attr)

    def _get(self, value):
        self.write(value)
        return float(self.read())

I admit I don't know much about pyvisa, but one option to ensure the resource is released would be to make your class a context manager type. Then a user could do e.g.

with Instrument(whatever) as inst:
    ...

and be certain that everything was dealt with on __exit__.


Yes, I think there is more straightforward ways to implement this:

Compute the length of the largest string.
Create a 2D char[][] matrix with the amount of rows equal to the length of the largest string. The amount of "columns" depends how much space you want between two neighbour columns.
Fill out the matrix with characters.
Create a StringBuilder and fill it with the chars from the matrix.

All in all

I had this in mind:

private static final int DEFAULT_COLUMN_SPACING = 2;

public static String makeVerticalText(List<String> lines) {
    return makeVerticalText(lines, DEFAULT_COLUMN_SPACING);
}

public static String makeVerticalText(List<String> lines,
                                      int columnSpacing) {
    if (lines.isEmpty()) {
        return "";
    }

    int maximumLength = lines.stream()
                             .max(Comparator.comparing(String::length))
                             .get()
                             .length();

    char[][] matrix = new char[maximumLength]
                              [(columnSpacing + 1) * lines.size()
                              - columnSpacing];
    int columnIndex = 0;

    for (String line : lines) {
        int rowIndex = 0;

        for (char c : line.toCharArray()) {
            matrix[rowIndex++][columnIndex] = c;
        }

        columnIndex += 1 + columnSpacing;
    }

    int numberOfColumns = matrix[0].length;
    StringBuilder sb =
            new StringBuilder(maximumLength * (matrix[0].length + 1));

    for (int rowIndex = 0; rowIndex < maximumLength; ++rowIndex) {
        for (columnIndex = 0; columnIndex < numberOfColumns; ++columnIndex) {
            char currentChar = matrix[rowIndex][columnIndex];
            sb.append(currentChar == '\u0000' ? ' ' : currentChar);
        }

        if (rowIndex < maximumLength - 1) {
            sb.append('\n');
        }
    }

    return sb.toString();
}

Hope that helps.


Query performance of a SELECT statement using WHERE and NOT IN

I don't see anything unreasonable about the query itself.

However, if I'm interpreting the output of EXPLAIN correctly, the anti-join with sheet_user_popup_not_adam is being done using a full table scan.  Run

SHOW INDEXES FROM sheet_user_popup_not_adam;

If no index exists on the user_id column, then run

CREATE INDEX sheet_user_popup_not_adam_user_id ON sheet_user_popup_not_adam (user_id);

Maybe that should be CREATE UNIQUE INDEX … instead, if appropriate.  Hopefully the performance should improve after you create the index.


Difference between dates in Months and Days

Last answer deleted (instead of substantially revising).

Notes (see comments in code)

CalendarSpan signed (date1 > date2 => negative span)
Extension overload of DateTime.Add() taking CalendarSpan argument
Unit test approach (see Main() which iterates positive and negative differences, using DateTime functions to check integrity of results)

`

using System;

namespace DateDiff
{
  static class Program
  {
    public readonly struct CalendarSpan
    {
      public CalendarSpan(int months, int days)
      {
        Months = months;
        Days = days;
      }
      public readonly int Months;
      public readonly int Days;
    }

    //  Maintains sign-consistency, i.e. if l > r returned value components are positive and if l < r negative
    public static CalendarSpan MonthDaysDifference(this DateTime l, DateTime r)
    {
      var mDiff = l.Month - r.Month + 12 * (l.Year - r.Year);

      var dDiff = (l - r.AddMonths(mDiff)).Days;
      if (dDiff == 0 //  no day, the span is a whole number of months
          || l > r && dDiff > 0 //  day and month differences ...
          || l < r && dDiff < 0) //  ... have the same sign
        return new CalendarSpan(mDiff, dDiff);
      //  Signs differ
      var dSign = Math.Sign(dDiff);
      var mSign = Math.Sign(mDiff);
      //  It doesn't matter which sign is which, we adjust months in the correct direction
      mDiff += dSign;
      //  and recalculate days
      return new CalendarSpan(mDiff, (l - r.AddMonths(mDiff)).Days);
    }

    public static DateTime Add(this DateTime dt, CalendarSpan span)
    {
      return dt.AddMonths(span.Months).AddDays(span.Days);
    }

    //  Included to suggest how to test
    static void Main(string[] args)
    {
      for (int i = 0; i < 1000; i++)
      {
        var date1 = new DateTime(2017, 12, 25).AddDays(i);
        for (int j = 0; j < 1000; j++)
        {
          var date2 = new DateTime(2019, 01, 01).AddDays(j);
          var dateDiff = date1.MonthDaysDifference(date2);
          //var dateDiff2 = MonthDaysDifference(date1,date2);//just checking
          if (date2.Add(dateDiff) != date1)
          {
            Console.WriteLine($"ERROR: {date1:yyyy-MM-dd} - {date2:yyyy-MM-dd} = {dateDiff.Months} months + {dateDiff.Days} days");
            Console.WriteLine("Any key to exit");
            Console.ReadKey();
            return;
          }
          Console.WriteLine($"{date1:yyyy-MM-dd} - {date2:yyyy-MM-dd} = {dateDiff.Months} months + {dateDiff.Days} days");
        }
      }
    }
  }
}


Its interface might not be obvious enough for junior programmers in a hurry. I suppose there's some assistance in your README. Anyway the code is quite clear given a little experience or effort. It doesn't use exactly the subset of JavaScript that Douglas Crockford recommended in JavaScript: The Good Parts, but that doesn't always matter.

I like this code. It has enough complexity for the real world without taking on responsibilities extraneous to wrapping XmlHttpRequest (or its equivalents). Nice use of closures. I really like that you incorporated a hyperlink to a line of github code that you found helpful.


Here are some small things you could di in order to improve your design:

First of all, you have a typo: you wrote Map::Iiterator begin(); instead of Map::Iterator begin();.
You use KeyType and DataType but do not even declare them.
For client code that uses generic code, it would be great if the name of the functions and subtypes were consistent with the STL. That means that you should be using empty(), iterator, const_iterator, etc...
The STL also defines subtypes like value_type, reference_type, size_type, etc... It would be better if you provided those too :)
Since you are using C++11, you could also provide the member functions cbegin and cend, for the same reason (consistency with standard containers).
You could have used std::size_t for the size() function (or even better, Map<K, V>::size_type), but using such an unsigned type can also lead to some unexpected problems. I wasn't able to find any relevant article, otherwise I would have linked one.
operator[] should take its elements by const&. You probably don't want to copy entire std::string instances when using this function.
Last but not least, I have no idea what your function filter is supposed to do. My guess is that it returns a filtered version of the Map, in which case the name filtered may be more suitable. Otherwise, if it filters the current map in place, it should probably return a Map& instead of a Map. Anyway, you better document it to remove the potential ambiguities. Moreover, we don't know whether the filter function filters the Map on its keys or on its values.

Well, otherwise, I don't think there are obvious errors in the design. There are probably some other things that can be improved, but generally speaking it's not bad :)


If your need is truly

  Add 2 strings representing 2 doubles, return the sum of the 2 doubles in string format.

then it is as easy as

def add_strings(x, y):
    return str(float(x) + float(y))

a = add_strings("2.3", "4.5")

print(a)
print(type(a))

which gives

6.8
<class 'str'>

Note that returning a numerical string is a strange and mostly not required operation in the Python world.
The function should return without the str call, and the conversion to string will either be implicit (like print can do it) or explicit by the user of that function.
If you hand the returned string into a new function that does, say, multiplication, and that function has to convert string to float again... you see the unnecessary chain there.

Other than that, your code can benefit from sticking to the PEP 8 Style Guide.
Most of all, in this case, having all variables in snake_case can save you from hearing "PEP 8"-comments again.
In res = '', you could issue res = "", since those quotes are impossible to mistake.
'' can look like ".


MIN_INT looks pretty arbitrary (are you by any chance on a 16-bit system?). Better initialize max and current_max to array[0] (and start iterating from i = 1).
current_max = current_max + array[i] > array[i] ? current_max + array[i] : array[i]; is extremely hard to read.

Notice that current_max + array[i] > array[i] is a long way to say current_max > 0.
compute_largest_contiguous_sum does a bit more than its name suggests. It parses the input and computes the sum. I recommend to factor the parser out, e.g. int parse_input_line(char *, int * size);. As a side note, 512 is also quite arbitrary.


Return table value based on a primitive "priority queue"

welcome to Code Review.

I don't understand the purpose of your inTable() function. Lua tables already support immediate lookup of entries in them, just by using square brackets. See the Lua documentation for tables.

So your code:

  if inTable(valid, "22") then
    return inTable(valid, "22")
  elseif inTable(valid, "13") then
    return inTable(valid, "13")
  elseif inTable(valid, "25") then
    return inTable(valid, "25)

is really equivalent to:

if valid[22] then
  return valid[22]
elseif valid[13] then
  return valid[13]
elseif valid[25] then
  return valid[25]

Can we do better than this? Sure! Lua has the or operator which returns the first true value. (See documentation)

return valid[22] or valid[13] or valid[25]

Can we do even better? Definitely. Make up another table with the indexes in order, then iterate over it, returning the first true value.

local priority = {22, 13, 25}
local i
for i in priority do
   if valid[i] return valid[i]
end


Finding a string in a text file and reporting full file name and size

Using findstr in PowerShell is superfluous and
not very powershell'ish which is about objects and pipes.

You can directly pipe the raw output of Get-ChildItem to Select-String and parse the resulting object for the information you require.

As the size of the file isn't contained in the properties sls returns:

Context      Property
Filename     Property
IgnoreCase   Property
Line         Property
LineNumber   Property
Matches      Property
Path         Property
Pattern      Property

You've to append it, either with a calculated property

# Grab user options
$ext = Read-Host -Prompt        "Enter extension   "
$huntString = Read-Host -Prompt "Enter hunt string "

Get-ChildItem *.$ext -Recurse | Select-String $huntString -List |
    Select-Object @{Label='Size';Expression={(Get-Item $_.Path).Length}},Path

or iterate the output and build a [PSCustomObject]:

Get-ChildItem *.$ext -Recurse | Select-String $huntString -List |
    ForEach-Object {
        [PSCustomObject]@{
            Path = $_.Path
            Size = (Get-Item $_.path).Length
        }
    }

The objectsoutput will be the very same:

> Q:\Test\2018\12\17\CR_209811.ps1
Enter extension   : ps1
Enter hunt string : ::Now
Size Path
---- ----
 878 Q:\Test\2018\09\18\SO_52381514.ps1
 677 Q:\Test\2018\11\16\SO_53336923.ps1
 770 Q:\Test\2018\11\19\SO_53381881.ps1
1141 Q:\Test\2018\12\17\CR_209811.ps1
1259 Q:\Test\2018\12\17\SU_1385185.ps1


This is decidedly shady:

O& operator*() const {
    if (m_ptr.expired())
        throw ObjectInvalid();

    return m_ptr.lock().operator*();
}

O* operator->() const {
    if (m_ptr.expired())
        throw ObjectInvalid();

    return m_ptr.lock().operator->();
}

In the line:

return m_ptr.lock().operator->();

You create a shared pointer. Get the pointer value from the shared pointer. Destroy the shared pointer then return the pointer that was in the shared pointer.

So now you have a pointer but no guarantee that the object it points at exists anymore (as you destroyed your copy of the shared pointer).

There are a couple of operations on the master pointer that you don't support.

You can't test if it is empty.
So you are playing Russian roulette every time you use it.
You can't use it as part of a conditional (ie no conversion to bool).
You don't have a constructor that takes a nullptr => std::nullptr_t
You have a couple of problems with implicit construction.


Validate input of month/year, otherwise set it to current month/year

You may be over thinking it.  It's actually very simple.

The only ambiguous thing is if the year is two digits.  In most cases a two digit year can be fixed like this.  I believe in your use the month and year will be all be future and nothing from the 1900s.

if (intval($optionsYear) < 100){$optionsYear  = '20' . $optionsYear;}

Then to finish up:

$date = strtotime("$optionsYear-$optionsMonth-13"); // yyyy-mm-dd
if ($date){  // test validity, will be false if invalid
  $month = date('m',$date);  // invalid, use today's month and year.
  $year = date('Y',$date);
}
else{
  $month = date('m');  // valid numbers entered
  $year = date('Y');
}

Because the day of the month is no an issue I used 13.  Not that it would but in dates the month and day can cause problems.  By using a day of 13 it cannot be confused with a month.  If a date were entered as 13/4/2015, it would not be difficult to understand 13 is a day and 4 is a month. Oct, Nov, Dec would still be ambiguous if entered as 10, 11, or 12.


_DateCreated = value;
        _DateCreated = DateTime.SpecifyKind(_DateCreated, DateTimeKind.Utc);//ensure this is set

This creates a race condition: another thread can access _DateCreated in between the two assignments and get a non-UTC value. If you're going to do it at this level it should be

        _DateCreated = DateTime.SpecifyKind(value, DateTimeKind.Utc);

That leaves the question of whether it should be done at this level. You haven't said how you're getting the date from the database. Can that be configured?

  This would have me questioning the use of DateTime in any scenario - and always using DateTimeOffset!?!

Yes. DateTime is one of those mistakes that everyone recognises is a mistake, but is so deeply embedded in so many libraries and tools that it's a pain in the neck to eradicate.


Finding the name of a given constant using reflection

If performance is your concern I would implement getCCName as a lookup in a map that's filled when the class is loaded, e.g. like

private static final Map<Integer, String> _int2string;

static
{
    final Map<Integer, String> int2string = new HashMap<>();

    try
    {
        for (Field field: Arm_const.class.getFields())
        {
            final int mod = field.getModifiers();

            if (!int.class.equals(field.getType()))
                continue;

            if (!Modifier.isStatic(mod) || !Modifier.isPublic(mod))
                continue;

            if (!field.getName().startsWith("ARM_CC_"))
                continue;

            int2string.put(field.getInt(null),
                           field.getName().substring("ARM_CC_".length()));
        }
    }
    catch (IllegalAccessException l_e)
    {
        throw new RuntimeException(l_e); // should not occur
    }

    _int2string = Collections.unmodifiableMap(int2string);
}

public static String getCCName(int cc)
{
    return _int2string.get(cc);
}


Extract data from one column of SQL Server table

Basically, sql is not meant to parse text.  The database design is the issue here and it probably needs to be modified.  Another option is to return the string to the server and do the parsing there and then make another call to sql.

My answer is basically a copy of Andrew White's answer to this stackoverflow question.


In my opinion, your code would benefit considerably from a better naming convention.

In Prolog, a good predicate name makes clear what each argument denotes.

For example, when I see:

prereqs(460, 233).

then I have no idea what the arguments are. I see it is about prerequisites, but in which direction? Is 460 a prerequisite of 233, or is it the other way around? Also, why is this called "prereqs" although each clause only denotes a single prerequisite?

A much more descriptive name for this predicate would be (for example!):

prerequisite_of_course(460, 230).

because this makes clear what is the prerequisite of what. Another very good, descriptive name would be for example:

course_prerequisite(230, 460).

You will find that, if you use more descriptive names, then emitting output yourself will become unnecessary: The predicate name alone will make the situation perfectly clear. Let the toplevel do the printing for you!

The variable names in:

prereq(X, Y) :-
    prereqs(X, Z),
    prereq(Z, Y).

could also be improved considerably by choosing more descriptive names or abbreviations, such as Req, Course etc. For transitive relations between courses, you can for example use:

Course0 → Course1 → ... → Course


Rake task to send users a reminder to post with conditions

Never User.all.each in the real world. That loads your entire table into memory and instantiates ActiveRecord models for every record. You want User.find_each do |user|, which uses find_in_batches to load 1000 records at a time.
Don't do simple filtering in Ruby, do it in the database. This...

if user.reminder == true

should be a simple scope that prevents these records from ever being loaded. Something like this:

class User < ActiveRecord::Base
  scope :with_reminder, -> { where(reminder: true) }
end

Now, your top-level loop can use the scope:

User.with_reminder.find_each do |user|

This filters out a huge number of users who would otherwise be loaded from the database needlessly.
Your if/else aren't actually correct, since your intent is to load all users with reminder = true. You load all users, and then your if looks for user.reminder == true, but your else doesn't. It affects all users with reminder of true or false, and then sets their reminded to false.

  ... which tells me that the user hasn't an ActiveRecord assigned to it? Because the reminder_time column exists and is set (to 16:00).

Err, no, that's not at all what that tells you. Nothing has "an ActiveRecord" assigned to it, that isn't at all how ActiveRecord works. Every record in the database is wrapped in an ActiveRecord object as you read it from the database, it's impossible for some users to "have" ActiveRecords and others not to.

See point 3. Your else currently checks all records, including those with reminder == false, and presumably those records don't have a reminder_time set.
It's really not clear what you're trying to do with Time.current.strftime("%H") == user.reminder_time + 1. What is "1"? You have no unit, so it means "1 second". Your probably never going to hit that.


Finding specific small byte arrays in large binary files

You should be aware, that if you have a search pattern like:

byte[] pattern = { 0x00, 0x01, 0x02, 0x03 };

and a file sequence as

..., 0x00, 0x00, 0x01, 0x02, 0x03,...

Then it won't be found, because the first 0x00 will increment searchPosition to 1, so the second 0x00 will test false in if(latestbyte == searchPattern[searchPosition].

The solution is to reset the searchPosition whenever the latestbyte equals searchPattern[0]:

while(true) //Loop until we reach the end of the file
{
    var latestbyte = stream.ReadByte();
    if(latestbyte == -1) break; //We have reached the end of the file

    if (latestbyte == searchPattern[0])
      searchPosition = 0;

    if(latestbyte == searchPattern[searchPosition]
    {
        searchPosition++;
        if(searchPosition == searchPattern.Length)
        {
            searchResults.Add(stream.Position);
            searchPosition = 0;
        }
    }
}

OBS: This is only working for search patterns with  bytes, that are all different (see Firdas comment).

The position of the found pattern, you add to the result is actually the position of the last byte in the pattern. Maybe the start position is more interesting:

searchResults.Add(stream.Position - searchPattern.Length);

As Sylvain suggests you can improve performance a bit by reading larger chunks of bytes and evaluate them in turn successively:

List<long> GetPatternPositions(string path, byte[] pattern)
{
  using (FileStream stream = new FileStream(path, FileMode.Open))
  {
    List<long> searchResults = new List<long>(); //The results as offsets within the file
    int patternPosition = 0; //Track of how much of the array has been matched
    long filePosition = 0;
    long bufferSize = Math.Min(stream.Length, 100_000);

    byte[] buffer = new byte[bufferSize];
    int readCount = 0;

    while ((readCount = stream.Read(buffer, 0, buffer.Length)) > 0)
    {
      for (int i = 0; i < readCount; i++)
      {
        byte currentByte = buffer[i];

        if (currentByte == pattern[0])
          patternPosition = 0;

        if (currentByte == pattern[patternPosition])
        {
          patternPosition++;
          if (patternPosition == pattern.Length)
          {
            searchResults.Add(filePosition + 1 - pattern.Length);
            patternPosition = 0;
          }
        }
        filePosition++;
      }
    }

    return searchResults;
  }
}

The improvement is not that impressive, but maybe you can experiment with the bufferSize to optimize it?


Remove non-printable characters from string in Python 3

Something that may help performance wise could be itertools.islice.
This will allow you to call str.isprintable() max_width amount of times,
as this is a binary file that may not have many \ns it can save a lot of effort.

output = line.decode(codec, "replace")
if max_width:
    print("".join(itertools.islice((c for c in output if c.isprintable()), max_width)))
else:
    print(output)

This on it's own may not help on files that have a lot of \ns.
The bottle neck in these file would most likely be the overhead incurred by print.
And so it's much faster to build a string to display once.
In these cases you would want to use something like:
(Untested code)

def read_data(path):
    with open(path) as f:
        for line in f:
            output = line.decode(codec, "replace")
            if max_width:
                yield "".join(itertools.islice(
                    (c for c in output if c.isprintable()),
                    max_width))
            else:
                yield output

print('\n'.join(read_data(...)))

However the above is not good on machines with limited memory or extremely large files.
In these cases you would want to use a buffer and print the buffer when a threshold has been reached.

After PEP 3138 your method to remove non-printables seems to be the correct way.


Setting various types of properties on a JCR node

My idea would be to encapsulate the job of casting and converting into some kind of a Strategy pattern.

I would use an enum for that, namely NodeSettingStrategy:

public static enum NodeSettingValueStrategy {
    UNKNOWN(null) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            throw new IllegalArgumentException("Cannot set property to a value of type " + value.getClass());
        }
    },

    DATE(Date.class) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            node.setProperty(propertyName, (Long) value);
        }

    },

    LONG_PRIMITIVE(long.class) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            node.setProperty(propertyName, (long) value);
        }
    },

    LONG(Long.class) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            node.setProperty(propertyName, (Long) value);
        }
    },

    STRING(String.class) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            node.setProperty(propertyName, (String) value);
        }
    },

    NODE(Node.class) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            node.setProperty(propertyName, (Node) value);
        }
    };

    private final Class<?> supportedType;

    private NodeSettingValueStrategy(Class<?> supportedType) {
        this.supportedType = supportedType;
    }

    public static NodeSettingValueStrategy of(Class<?> type) {
        for (NodeSettingValueStrategy strategy : NodeSettingValueStrategy.values()) {
            if (strategy.supportedType == type) {
                return strategy;
            }

        }
        return NodeSettingValueStrategy.UNKNOWN;
    }

    public abstract void set(Node node, String propertyName, Object value);
}

Then I want to hide this NodeSettingStrategy by a thin abstraction, namely NodeSetter:

public static class NodeValueSetter {
    private final NodeSettingValueStrategy strategy;
    private final String propertyName;
    private final Object value;

    private NodeValueSetter(NodeSettingValueStrategy strategy, String propertyName, Object value) {
        this.strategy = strategy;
        this.propertyName = propertyName;
        this.value = value;
    }

    public void setTo(Node node) {
        strategy.set(node, propertyName, value);
    }

    public static NodeValueSetter of(final String propertyName, final Object value) {
        NodeSettingValueStrategy settingStrategy = NodeSettingValueStrategy.of(value.getClass());
        return new NodeValueSetter(settingStrategy, propertyName, value);
    }

}

Combine them together:

@Test
public void should_able_to_set_property() throws Exception {
        Node node = new Node();

        Node givenNode = new Node();
        String someString = "The brown fox jumps over a lazy dog";
        long givenLong = 234234234234L;

        for (NodeValueSetter setter : Arrays.asList(
                NodeValueSetter.of("a-string", someString),
                NodeValueSetter.of("a-number", givenLong),
                NodeValueSetter.of("a-node", givenNode))) {
            setter.setTo(node);
        }

        assertThat(node.getProperty("a-string"), is(someString));
        assertThat(node.getProperty("a-number"), is(givenLong));
        assertThat(node.getProperty("a-node"), is(givenNode));
    }


Your code has many, many stylistic issues. Some of them seem to be idioms you've invented coming from a Java background; some of them may be due to not really understanding how OOP classes work.

using namespace std;

int main(int argc, char * const argv[])
{

    BinaryOptionPricing bop;

You're missing a bunch of #include lines.
Prefer char * const *argv over char * const argv[] because you don't have to understand array-to-pointer decay to read it.
const-qualifying *argv here is incorrect, or at least the compiler is within its rights to reject it. The correct prototype for main is int main(int argc, char **argv) with no consts.
using namespace std; is frowned upon in C++; prefer to write out std::vector and so on, since that's what you'll be doing once you enter the workforce (or wherever you end up coming in contact with other programmers).
BinaryOptionPricing is undefined at this point. You need to provide the definition of this class before you try to use it.

class BinaryOptionPricing
{

private: int red;
private: int black;
private: std::map<std::pair<int, int>, double> Cache;
private: typedef int card;
private: typedef double redValue;
private: typedef double blackValue;
private: typedef double gameValue;

C++ isn't Java; you don't have to write public static void main and so on. In C++, public: and private: (and protected:) act as a kind of "section header" introducing a whole bunch of public or private (or protected) members at once. You should write the above code as

class BinaryOptionPricing
{
  private:
    int red;
    int black;
    std::map<std::pair<int, int>, double> Cache;

    using card = int;
    using redValue = double;
    using blackValue = double;
    using gameValue = double;

Notice that private: is the default inside a class, so you don't even need the line private: there; I just put it so you'd see how you could do it. Also notice that I'm using the C++11 using syntax for type aliases, instead of the old C/C++03 typedef syntax — the latter is still perfectly legal and supported, but the former syntax is becoming the de facto standard because it supports things like dependent type names and alias templates whereas the typedef syntax is basically an evolutionary dead end in those respects.

I would advise against using the typedef name card to refer to an integer count of cards. You could say cards or cardCount or NumberOfCards instead... but really, there's nothing wrong with using int directly. It saves you some typing, and clearly indicates what's going on in the code (namely, an integer count).

private:
    double value(card red, card black)
    {
        // ...
    }

public:
    double get()
    {
        return value(red, black);
    }

Here is where I say you may be fundamentally misunderstanding how classes work. Your class BinaryOptionPricing already has data members ("member variables") named red and black. You wrote a member function get() that grabs the value of those members and passes them as function parameters to another member function value(). Inside value, whenever you refer to red, you're referring to the function parameter red, which shadows the data member red defined in the class itself. Fortunately for you, the function parameter has the same value as the data member that it's shadowing... well, at least on the initial recursive call... but this is a very awkward way to write code! If you don't want access to your class's data members at all, you should make value(int, int) a static member function:

static double value(int red, int black)
{
    // ...
}

double get() const
{
    return value(this->red, this->black);
}

void set(int totalNumberOfCards)
{
    this->red = (totalNumberOfCards/2);
    this->black = (totalNumberOfCards / 2);
}

This looks like you want a constructor.

explicit BinaryOptionPricing(int totalNumberOfCards) :
    red(totalNumberOfCards/2), black(totalNumberOfCards/2)
{}

Even better, you should consider just not using OOP at all for this problem; there's no reason the member variables red and black really need to exist here. You could just write

double value_of_game(int red, int black)
{
    if (red == 0 || black == 0) return black;
    double total = red + black;
    double result = (red / total) * value_of_game(red-1, black)
                  + (black / total) * value_of_game(red, black-1);
    return std::max<double>(result, black - red);
}

and it would work just fine, modulo the lack of memoization making it slow.

Notice that you don't need (and shouldn't put) parentheses around your return expressions; that you're overusing explicit cast notation (frowned upon in C++); and that in C++ it is idiomatic to initialize your local variables and then rarely-if-ever change their initial values, rather than defining them uninitialized at the top of the function and then giving their "real" values farther down in the code.

So let's look at your memoization code.

    auto searchPair = Cache.find(std::make_pair(red, black));
    if (searchPair != Cache.end()) {
        return searchPair->second;
    }

    // ...

    Cache.insert(std::make_pair(make_pair(red, black), maxValue));

Good use of C++11 auto to avoid typing out the name of the iterator type!
Instead of insert, you could use Pythonesque syntax:

    Cache[make_pair(red, black)] = maxValue;

or even

    Cache[{red, black}] = maxValue;

although the latter is a bit tricksy so don't ask me to explain it. :)

Putting that all together, we get something along the lines of

double value_of_game(int red, int black)
{
    static std::map<std::pair<int,int>, double> cache;
    if (red == 0 || black == 0) return black;
    auto it = cache.find({red, black});
    if (it != cache.end()) return it->second;
    double total = red + black;
    double result = (red / total) * value_of_game(red-1, black)
                + (black / total) * value_of_game(red, black-1);
    result = std::max<double>(result, black - red);
    cache[{red, black}] = result;
    return result;
}

And this is where we might want to reintroduce a "noun" (a class) into our program, because maybe we want the ability to call value_of_game(x,y) from two different threads simultaneously and we don't want race conditions on cache. So we could do

class BinaryOptionPricing {
    std::map<std::pair<int,int>, double> cache;

  public:
    double value_of_game(int red, int black)
    {
        if (red == 0 || black == 0) return black;
        auto it = cache.find({red, black});
        if (it != cache.end()) return it->second;
        double total = red + black;
        double result = (red / total) * value_of_game(red-1, black)
                    + (black / total) * value_of_game(red, black-1);
        result = std::max<double>(result, black - red);
        cache[{red, black}] = result;
        return result;
    }
};

Alternatively we could directly expose the memoization mechanism to the caller:

using value_of_game_cache_t = std::map<std::pair<int,int>, double>;

double value_of_game(int red, int black, value_of_game_cache_t& cache)
{
    if (red == 0 || black == 0) return black;
    auto it = cache.find({red, black});
    if (it != cache.end()) return it->second;
    double total = red + black;
    double result = (red / total) * value_of_game(red-1, black, cache)
                + (black / total) * value_of_game(red, black-1, cache);
    result = std::max<double>(result, black - red);
    cache[{red, black}] = result;
    return result;
}

Notice that the second alternative here is just a very thin refactoring of the first alternative: we've merely renamed BinaryOptionPricing to value_of_game_cache_t and passed it as an explicit function parameter instead of an implicit this parameter.

BinaryOptionPricing bop;
printf("EV is %g\n", bop.value_of_game(26, 26));  // first approach

value_of_game_cache_t bop;
printf("EV is %g\n", value_of_game(26, 26, bop));  // second approach

The advantage of the first (class-based) approach, in this context, is that I could write my call as a one-liner and it would be just as fast and just as thread-safe as the alternative: the best of both worlds.

printf("EV is %g\n", BinaryOptionPricing().value_of_game(26, 26));


Pattern.compile("\\(([^)]+)\\)");

The Pattern is always the same so you may just as well make it a private static final constant. This will avoid having to recompile the pattern each time.

Arrays.asList(/*..*/).stream().collect(Collectors.toList());

Why this dance? Arrays.asList returns a List. You only do a stream on the return result.

    final List<String> list = Arrays.asList(matcher.group(1).split(","));
    list.stream().forEach(a ->
    {
        final String[] ar = a.split("->");
        map.put(ar[0], ar[1]);
    });

However a Pattern an return a Stream split according to the pattern directly:

Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");

COMMA_PATTERN.splitAsStream(matcher.group(3)).forEach(a ->
{
    //...
}

You can use a single match of a Pattern to find both the leading values and the string inside the parenthesis:

private static final Pattern FULL_PATTERN = Pattern.compile("^(\\$\\w+)\\s*=>\\s*(\\w+)\\s*\\(([^)]+)\\)$");
private static final Pattern KEY_VALUE_PATTERN = Pattern.compile("(\\w+)\\s*->\\s*([\\$\\w]+)");
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");

public static Macro getMacro(String str) {
    final Macro macro = new Macro();
    final Map<String, String> map = new HashMap<String, String>();
    final Matcher matcher = FULL_PATTERN.matcher(str);
    if(!matcher.matches()) {
        throw new IllegalArgumentException("...");
    }

    COMMA_PATTERN.splitAsStream(matcher.group(3)).forEach(a ->
    {
        final Matcher kvMatcher = KEY_VALUE_PATTERN.matcher(a);
        if(!kvMatcher.matches()){
             throw new IllegalArgumentException("...");
        }

        map.put(kvMatcher.group(1), kvMatcher.group(2));
    });
    macro.setMap(map);
    macro.setKey(matcher.group(1));
    macro.setType(matcher.group(2));
    return macro;

}

You'll note I added \\s* to various points in each pattern, This lets you ignore the whitespace that may surround the operators.

The \\w in a Pattern means a word character. If you only want alphanumeric +undescore then you'llneed to replace each instance of it with [\\p{Alnum}_]


Further Optimizing a Segmented Sieve of Eratosthenes

Python 3.8 adds math.isqrt().  Using this, you can make a much less cryptic perfect square check:
high == math.isqrt(high) ** 2

Memory Optimization (speed too!)
Using a list of Boolean flags:
numbers = [False]*2 + [True]*(n-2)

is very space inefficient.  You are using 28 bytes per flag!  By packing 8 flags into one byte, you’d achieve a 99.5% memory usage reduction.  Doing this packing yourself would be slow and awkward.  Fortunately, there is a package that does this for you: bitarray.
numbers = bitarray.bitarray(n)
numbers.setall(True)
numbers[0:2] = False

Notice that slice assignment from a scalar Boolean?  It gets better when you use it to cross off the multiples of a prime candidate:
if prime_candidate:
    result.append(index)
    numbers[index*index::index] = False

and done!

Integer division
You should really use integer division // in find_first_multiple_odds():
x = p * ((low // p) + (low % p != 0))
...
return (x - low) // 2

PEP-8

use snake_case function names.  UpperCase is for class names
use a space around binary operators


Aside from the performance issues you should make the query more readable by using relevant variable names instead of a, b, c, d, g, and h.  In addition, the ambiguous ListReport class name should be changed to something more specific like PageUsage since it contains information about a page and how many times it has been viewed/used for signup.

(from page in Context.Pages
join visitor in Context.Visitors on page.PageID equals visitor.PageFK
join visit in Context.Visits on visitor.VisitorID equals visit.VisitorFK
join signup in Context.Signups on visit.VisitID equals signup.VisitFK
where
signup.DateOptinUtc.HasValue && page.UserFK == USER_ID
group signup by new { page.PageID, page.DateCreated, page.BaseName, page.Name }
into signupsByPage
select
new PageUsage
 {
     DateCreated = signupsByPage.Key.DateCreated,
     BaseName = signupsByPage.Key.BaseName,
     Id = signupsByPage.Key.PageID,
     Name = signupsByPage.Key.Name,
     Optins = signupsByPage.Count(),
     Views =
         (from subVisit in Context.Visits
          where
              subVisit.Visitors.PageFK == signupsByPage.Key.PageID
          select subVisit).Count()
 }).AsQueryable();


Create another Singleton object from a Singleton class

It has been some time since I last wrote Java, but I have some general suggestions.

Before focusing on specific details of the code I would recommend you to spend some time on indentation. Having consistent indentation helps reduce the cognitive load when reading your code.

Second I would urge you to consider if a singleton is the appropriate solution for this problem. Using a static class makes testing both the implementation and consuming code difficult. The first being your implementation sharing state between test-cases and you therefore have to spend extra time ensuring you reset the state between each test-case. The latter is due to the consuming code hiding its dependencies. You aren't able to test a consuming class in isolation as you would implicitly also test the cache manager, which in turn also involves the third party code. Furthermore imagine that if the third party implementation relies on I/O operations your tests of the consuming code now also relies on I/O operations. Unit tests especially shouldn't be concerned with I/O such as: file operations, network, databases etc.

To remedy this I would recommend looking into creating an interface, which defines only the required methods of your cache manager. From the provided code an example of an interface could be:

interface ICacheManager
{
    <T> T getCacheData(String key);

    <T> void setCacheData(String key, T value);

    void closeCacheConnection();
}

Then have your cache manager class implement this interface and use the inversion of control principle in your consuming code to makes its dependency on the cache manager explicit. This is done by requiring an instance of your interface in its constructor (dependency injection). Now in your test-cases you are able to create mock instances of your cache manager when testing consuming code. Using an interface also allows you to provide alternative cache manager implementation in your consuming code without changing a thing. The only requirement being all cache manager implementations adheres to your ICacheManager interface.

The next thing, which caught my eye was how the getConnection() method requires an instance of CacheConfig in its parameter list. Imagine that every time your consuming code needs access to your cache manager (by calling this method) it would also need to know about your cache configurations and have an instance of this. This breaks the separation of concerns principle. You can fix this easily by using the previously proposed solution by using  the inversion of control principle.

If this isn't an option I would create a factory class, which I would ensure is always seeded with an instance of the appropriate cache configurations when starting the application. Then have the factory call the getConnection() method and return the cache manager instance. You would therefore use the factory in your consuming code. You could also seed the cache manager directly with the appropriate cache configurations, but I find that more people understand the principle of the factory pattern and it would therefore make your code easier to understand.

  Note that this solution still hides the dependency of either the
  factory or the cache manager in consuming code as mentioned previously
  and therefore retains all the mentioned side-effects.

Next I find it enjoyable to see you checking for NULL after entering the synchronized block in the getConnection() method. Not many people remember to do this. Great job!

You should also include a check to see if the connection has already been closed in the closeCacheConnection() method. Have you checked how the third party code behaves if you try to close the connection twice? Your code should not depend on such things.

In the getConnection() method you write the name of the method in the error log message. I would recommend you to not do that. If the method is renamed and the log message isn't updated the log entries wont correspond with code. As you are already providing the exception a stacktrace accompanies the message and the name of the method would therefore already be available to the logging implementation along with line numbers etc.

Now lastly a minor pain-points of mine. In the getCacheData() and setCacheData() methods you name the variables containing the cache entry as e. This name is often associated with an exception and in the setCacheData() method this is actually the case. While this not being a syntax error I find it easier to define unique names for each variable, which is also descriptive. In this case I would recommend renaming the variables to entry as it's the contents.


Using recursion in sort() is fine: n recursive calls to sort() will let you handle an array of length 2n, so you don't have to worry about too much recursion.  However, it would be better if you wrote the recursion in the standard pattern: base case first, then the recursive case otherwise.  The base case should include empty arrays.

Array.slice(start) gives you a slice from start to the end of the array.

function sort(array) {
    if (array.length <= 1) {
        return array;
    }
    var middle = Math.floor(array.length / 2);
    var left = array.slice(0, middle);
    var right = array.slice(middle);
    return merge(sort(left), sort(right));
}

On the other hand, merge() should not be written recursively.  To obtain a merged array of length n, you'll have to make n recursive calls to merge(), and that could easily result in a stack overflow for a long list.  Furthermore, each slice involves copying nearly the entire array, so the algorithm is grossly inefficient.  You would be much better off writing merge() using a while or for loop.

One of the advantages of mergesort over other sorting algorithms is that it can be a stable sort — that is, if the input contains two elements, neither of which is larger than the other, then they can appear in the same relative order in the output.  For numbers, stability doesn't matter: one 42 is indistinguishable from another 42.  However, it would be good practice to write your merge() function so that it is stable anyway.  For that to happen, if you encounter a tie between left[l] and right[r], you must prefer to take left[l] first, so you should change if (left[0] > right[0]) to if (left[0] >= right[0]), and you must keep your left and right straight instead of swapping them carelessly when merge() calls itself.


Using MOQ in unit-testing for a shipping calculator

Your test is testing one thing only which is a very good thing. It is better to have many simple tests instead of one massive and it makes bug finding much easier.

First of all, I would suggest using more descriptive names for both methods and test. Consider calling Calculate() method differently, i.e. CalculateTotalShippingPrice, so that it indicates what it is doing.

Use test names which specify what is being tested, what is the state under test and expected behaviour as in: https://stackoverflow.com/questions/155436/unit-test-naming-best-practices.
Test1 could be called Calculate_WhenShoppingCartNotEmpty_CorrectlyCalculatesTotalShippingPrice

Make sure you take into account different scenarios, it is worth adding another test: Calculate_WhenShoppingCartEmpty_ReturnsZero.


Changes I would make: (but not necessary)

Make sure inputtext has a value, and isn't undefined, so it wouldn't throw an error in your if statement.
Replace the if statement with return instead. (This is mostly to minimize the code a bit, something your minifier won't do for you).

Except for that, it seems ok (I'm not looking into the logic of the regex, since I'm not sure how a zipcode should be parsed).

function zipcode (inputtxt)
{

    if (!inputtxt || !inputtxt.value) return false;
    var zipcode = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;

    return ((inputtxt.value.match(zipcode));
}


This is a good first-cut solution to the functional requirement of stated question. However, when you look at it as production code related to two companies (X and Y) these points arise:

Monolithic: The code should be well demarcated across X and Y company logic. A single analytics function is processing all of the logic with an (admittedly, nice) value control. This has merged the implementation into one piece of code. Say, Y no longer needs the average or, maybe needs something else. Change in code for Y will need to engage with the primary logic of X's code.
Scaling: Imagine a new company Z wants to get not just the average but also the number of data points seen by X (the totalPoints). Changing this monolithic analytics code would engage with all of the existing logic.

These are probably not the only points (and they are also both associated with monolithic and scaling issues). I am just trying to imagine some scaling paths and outline the monolithic-nature of this solution.

To get a fair view of this, consider some changes in the requirements and attempt to modify the code to incorporate them. The complexity required in the edit should be reasonably comparable to the requirement (not higher). Contact of the edit with other parts of the implementation should be minimal.

From a different standpoint, this code would be called a prototype of the logic. The production version would need to handle aspects beyond functionality (like: maintainability, scaling, business-logic separation, readability too).

I wonder if you were asked further questions by the interviewer after reading this program. Were they alluding towards these points.


This is not a review, but an extended comment.

The code cannot be meaningfully optimized. Few notes though.

First, thou shalt not bruteforce. It is almost inevitably wrong.
Next, you must realize that it is a number-theoretical problem. Even the names of the test cases suggest so. Among other things it means that testing the sum against 1e-10 is not right.
Finally, do watch the video referenced in the problem. It is a big spoiler, and it doesn't provide a proof of the claim. The proof is far from trivial; if you are interested in the proof, follow up with this is a fascinating reading (trigger warning: heavy-duty math).


Well, there's no context, so I can't be sure of exactly what you want, so I will assume a general review. In the future, please provide a little intro, even if its only to say, "please review and tell me how I can do better." Just dumping code is rather vague, for instance, this question could just as easily been about a better way to insert, of which I have no idea.

First, your method and variable names could use some work. What is __i()? A little more descriptive please. I can assume, based on the title of this post that this is an insert() method, but without any context this would be very difficult to determine. Additionally, I would avoid using double-spaced method names, those are usually reserved for PHP magic methods, such as __construct(). A single space is good enough, though that usually refers to a private or protected method.

Start your method's body on a newline, rather that the same one that the method was started on. I don't know if this was just a formatting issue with SO, or if its actually like that in your code. And, as above, what is $c? Connection can be inferred, but anyone reading this should not have to guess. $conn is a typical shortening and is widely accepted. Or you could spell it out completely, or use the root word "connect". As long as its somehow logically connected with the intent.

public function __i($table, $arr) {
    $conn = $this->connection;

Why are you using the standard template syntax for your statements and loops? In templates (Views or HTML files with PHP in them) this is fine, but it is quite odd and a little difficult to read in normal class structures. The preferred method is to use normal syntax, like so:

if() {
}
//AND
foreach() {
}

Where did $param1 and $param2 come from? They were not passed in as parameters to the method, which makes their names a little confusing. I would assume these are either globals, which are bad, or just undefined variables, which are also bad. If the later, then on the first iteration of this foreach loop those two variables will produce warnings about not being defined, or, god forbid, should there be globals assigned with those names, then you might just start appending on to them. To prevent this kind of mistake, it is best to define them before trying to use them. Also, any variable with a number after it is typically frowned upon. Use that variable's intent to better name them.

$param1 = '';
//etc...
$param1 .= $name . ",";

I know what these two substr_replace() lines are for, but they might be a little confusing to others. Perhaps a better method would be to use rtrim() to explicitly remove the last comma. This will make it more obvious what you are trying to do, and slightly decrease the size of that line. I don't know if its any faster or slower, but I don't think the difference will matter much here.

$PARAM1 = rtrim( $param1, ',' );

Your $param is not always set. This means that should $val not be an int, string, or double, then it will use the last known value of $param from the previous iteration. This can result in unforeseen results. Instead, you should either set up a default value or use an if/elseif/else structure. Here's a simple example assuming string as a default, you can always extend else in the following example to another elseif and use a final else to throw an error if you don't want to default.

if( is_int( $val ) ) {
    $param = 'i';
} elseif( is_double( $val ) ) {
    $param = 'd';
} else {
    $param = 's';
}
//which can easily be rewritten to use a default as
$param = 's';
if( is_int( $val ) {
    $param = 'i';
} elseif( is_double( $val ) ) {
    $param = 'd';
}

Don't define a variable in an if statement. It is too easy to accidentally do so when you don't mean to and will not always be obvious that you did not mean to perform a comparison instead.

$s = $c->prepare( $query ):
if( $s ) {
    //etc...
}

I'm not really sure how I feel about the call_user_func_array(), It could be a little confusing to someone who's never seen it before, but that's your call.

Finally, you might want to break up this method into multiple smaller methods. Use the Single Responsibility and "Don't Repeat Yourself" (DRY) Principles as a guideline. For example, to help you get started you can move that first foreach loop and those two substr_replace() lines into a new method called getParams() or something more aptly named. This will make it easier to reuse this code should you ever need to and make it easier to read.


Implementing HTTP Strict-Transport-Security via MVC action filter

I would suggest setting the message on ArgumentException to your parameter name

e.g.

throw new ArgumentException("'duration' must be greater than 0");


There are at least three things that may help to make the code more efficient:

switch to lxml instead of html.parser (requires lxml to be installed)
use a SoupStrainer to parse only the relevant part of the document
you can switch to http instead of https. While this would bring the security aspect down, you would avoid overhead of SSL handshaking, encryption etc - I've noticed the execution time difference locally, try it out

Improved code:
import requests
from bs4 import BeautifulSoup, SoupStrainer

page = requests.get('http://www.msn.com/en-sg/money/topstories/10-top-stocks-of-2017/ar-BBGgEyA?li=AA54rX&ocid=spartandhp')

parse_only = SoupStrainer("body")
soup = BeautifulSoup(page.content, 'lxml', parse_only=parse_only)

with open('filename.txt', mode='wt', encoding='utf-8') as file:
    title = soup.find('h1').text.strip()
    file.write(title + ' \n')

    for p_tag in soup.select('p') :
        file.write(p_tag.get_text() + '\n')

Note that I've also removed the unused variables and imports.
Btw, if it weren't for the title, we could've pinpointed SoupStrainer to p elements only - might've improved performance even more.


Using SHA-256 with a salt is not that bad. But PHP has built in functions like password_hash and password_verify to hash passwords. It uses bcrypt, which is currently one of the best methods to hash passwords these days. I would recommend this approach and it is just as easy to use like the function you've written.


Updating my package version using only a Makefile

I think there's an easier way to get this done:

Extract the semver part from the tag (as you already did)
Use conditionals to determine the field to increment
Use a single Awk to increment the selected field

For example:

release:
    $(eval v := $(shell git describe --tags --abbrev=0 | sed -Ee 's/^v|-.*//'))
ifeq ($(bump), major)
    $(eval f := 1)
else ifeq ($(bump), minor)
    $(eval f := 2)
else
    $(eval f := 3)
endif
    @echo $(v) | awk -F. -v OFS=. -v f=$(f) '{ $$f++ } 1'

I would add some validation in case the version doesn't have major, minor, patch components.


If you are just trying to concatenate vector<string> elements, why not use the following approach:

std::string seperator = " ";
std::string vectorElementHolder;

for (const auto& word : vec){

    vectorElementHolder += word + seperator;

}

Simple and effective, assuming you use C++11.
If you want to change the index where you start, you could always declare an iterator as such vector<string>::iterator to point to the index and go from there.