Control of empty fields in a form via JavaScript

It's okay to do the validations in the client side for a better user experience, so the user does not have to wait the response of the server or make a request to know if there is any field that he left incomplete. But you have to do the same validations on the server, because if someone makes a direct request to your server with empty fields, that request is not going through the javascript validations, so your application is going to crash.


Check if user selects correct Spanish word article

Message for moderators

As the OP already noticed, there is a strange issue when executing this in the context of the SO snippet:

  uncaught exception: unknown (can't convert to string)

I experienced the same with my totally refactored version, while it works without error in the usual context of my browser.

I can't see a good way to inquire about that, so TIA if one of the SO developers could look at it and explain it!

Now the review

This is properly written, and I see no big flaws.
But the code might be significantly reduced, by merely avoiding useless parts and repetition.

Useless parts consist of preparing data for both "la" and "el" cases, while each execution will only use one of those two articles.
So I suggest to prepare data for the involved one only, as soon as it was chosen.

Repetition appears in the click events handling, where you precisely define what must happen for each button, and in both cases depending it's the right one or not.
There too, we can compact this by acting for the two buttons at once, and evaluating if it's right during the flow.

Here is a working snippet based on yours, where I included these suggestions:

function setWord() {

    // Return random int between min (included) and max (excluded)
    function getRandomInt(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min)) + min;
    }

    const words = [
        ["casa", "comida", "chica"],
        ["perro", "amigo", "muchacho"]
    ];
    const articles = ['la', 'el'];

    var $buttons = $('.btn');
    var elOrLa = Math.round(Math.random());
    var article = articles[elOrLa];
    var $goodBtn = $('#' + article + '-btn');

    var $word = $('#test-word');
    var word = words[elOrLa][getRandomInt(0, words[elOrLa].length)];
    $word.text(word);

    $buttons.click(function() {
        if (this.id == $goodBtn[0].id) {
            location.reload(true);
        } else {
            alert('TOMA NOTA: ' + article + ' ' + word);
            $buttons.not($goodBtn).fadeOut();
            $goodBtn.css({'background': 'limegreen'});
            $word.addClass('bg-danger').removeClass('bg-warning');
        }
    });
}

setWord();

  <button type="button" class="btn btn-primary btn-lg" id="el-btn">EL</button>
  <button type="button" class="btn btn-primary pull-right btn-lg" id="la-btn">LA</button>

Apart from the changes exposed above, you can see that:

I dropped the $(document).ready() wrapper: in most cases (and sure here) it's not needed, as soon as the script appears after the HTML description part
I also moved the getRandomInt() function, which is now the 1st thing encountered in the setWord() function: this is a good habit to take now, since it becomes mandatory if you're using "use strict"; (see this page)


Tampermonkey script to check and replace youtube's subscriptions to show all videos

A short review;

BadDumbYoutubeURL should be lowerCamelCase and perhaps is a bit silly

the ; does not deserve it's on own line

My understanding is that location.search already starts with ? so you probably want to do something about that, like
 const search = window.location.search ? '&' + window.location.search.substring(1) : 0;

Other than looks fine, perfectly maintainable


Finding the biggest number in a list of numbers

The most obvious thing I can see is that you wrote a loop when one was not needed.

largest = max(n)

Also, check your boundary conditions. What happens if no numbers are entered?


Check whether address criteria contain only certain fields or more

I would be compelled to write a helper that accepts a variable number of address fields and and returns true if all of the address fields are not null and not empty.

private boolean isShortAddress(AddressCriteria addressCriteria) {

  return hasFields( addressCriteria.getCity(),
                    addressCriteria.getNumber(),
                    addressCriteria.getState(),
                    addressCriteria.getZipCode() );
}

private boolean hasFields( addressField... args )
{
  for( addressField arg:args)
  {
    if( null == arg || arg.isEmpty() )
      return false;
  }
  return true;
}

I did not test this code, but you should catch the drift.


Function that abbreviates a number (e.g. 1202 => 1.2K)

converting to string just to get the length won't work if there is a decimal or it's large enough that the string conversion uses scientific notation.

var size = floor(log(num)/log(10))+1;

This will give the place of the highest significant digit (1 to 9 results in 1, 10 to 99 results in 2, 100 to 999 results in 3, etc...)


Iter 2: Reusable, robust c++ std::hash for GMP's big integer type

Make functions that should not be exported static
Functions that should only be available locally should be marked static. This applies to pi_size_t() and scramble() in hash_mpz.cpp.
Avoid using std::endl
Use "\n" instead of std::endl, the latter is equivalent to "\n", but also forces a flush of the output. This is rarely necessary, and might hurt performance, especially when writing to a file, or when standard output is redirected to a file.
Consider not using namespace std
It's very good that you are not using namespace std in the header files. But consider not using it at all, since even if only used in .cpp files it can result in namespace conflicts that are hard to debug. If you do find yourself typing std:: a lot and want to avoid it, consider only importing the names that you do use from std::, like so:
using std::cout;
using std::unordered_map;

Final nitpicks

There's still one unnecessary std:: inside the namespace std block in hash_mpz.cpp.
You don't need return 0 at the end of main().


Non-recursively replace all uppercase letters in files within current directory with lowercase letters - without looping

The design constraint of "repeat (some action) without loops" is nonsensical.

Any solution that is not "type every rename command yourself" involves a loop.  The loop may be hidden inside xargs and awk or rename; it's still there.

Anyway, assuming the files are like you say (well-formed, no embedded whitespace, all printable characters), you can have awk generate a shell script and feed that to a shell:

\ls | awk '/[A-Z]/ {print "mv",$1,tolower($1)}' | sh

If you need to deal with spaces and special characters, add quotes and use $0 (whole line) instead of $1 (first field):

\ls | awk '/[A-Z]/ {printf "mv '\''%s'\'\ \''%s'\''\n",$0,tolower($0)}'

If the filenames contain ' then this will fail and you need to work that out.  Your code has the same problem.  I won't get into the solution here because it involves a zillion backslashes and is the wrong way to solve this problem.

The right way to solve this problem is to use a tool built for the task (rename) or a shell loop.  And adding -i is a good idea, in case the new filename already exists.  This will work with any filename:

for f in *[A-Z]* ; do mv -i -- "$f" "${f,,}"; done


Automatically growing label in Python Tkinter (just for fun)

Naming

Nouns are best for class names instead of verbs.
GrowLabel sounds like an action.
GrowingLabel would sound like a label that grows.

Related to this,
having a count method on a GrowingLabel object doesn't sound natural.
The fact that you implement the growing effect using a count should be an internal detail,
and not revealed to users of the class.
The important point is that the label can grow,
not how it does it.
So, renaming the method to grow() would be more natural.

Calling super-class methods

Since you are in Python 3,
it would be better to call the super constructor of GrowLabel like this:

super().__init__(master)

If that doesn't work somehow (I don't have tkinter to try),
then try this instead:

super(GrowLabel, self).__init__(master)

See more details in this related discussion.

Avoid wildcard imports

Don't use wildcard imports like this:

from tkinter import *

Quoting from PEP8:

  Wildcard imports (from  import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools.

I guess you do this because you're using many classes from this module.
A better way would be to do like this:

import tkinter as tk

And then you can prefix the classes you need with tk., like this:

root = tk.Tk()


The value of atof("Volt") is zero.  The corresponding values of atof("Time") and atof("Ampere") are also zero, which gives you the minimum values of zero you observed.

You need to skip the first line of the file.  Adding this before the while loop would work:

myFile.ignore(80, '\n');

Use std::numeric_limits<std::streamsize>::max() instead of 80 for a more correct (but verbose) limit of characters to skip before the new line character.

After you add the skipping of the first line, you no longer need the a, b & c variables and atof() calls;  you can read the values directly:

while (myFile >> time >> volt >> ampere)


OpenMP parallelization of a for loop with function calls

Try to come up with a better function name than func().  You are the one who understands this code the most, so you should know how to give it a relevant name.
Try not to use single-character names, unless they're for a simple for-loop.  It's hard to tell what they're for, especially without comments.  If this ends up making the #pragma line even longer, then you can just split it into separate lines with a \ at the end of each line.
It's a little hard to read lines lacking whitespace:

dx2=(dx<0.5?dx*dx:(1-dx)*(1-dx));

It's difficult to see the entire ternary statement, so add more whitespace:

dx2 = (dx < 0.5 ? dx*dx : (1-dx)*(1-dx));

This concept should be applied everywhere, especially each statement in the loop.

Going back to the ternary, consider using an if/else here instead.  Sure, this is a short ternary, but that doesn't mean it should always be used, especially if it's harder to read carefully.

if (dx < 0.5)
{
    dx2 = dx * dx;
}
else
{
    dx2 = (1-dx) * (1-dx);
}

This formatting is a bit hard to read:

        deltaE += coeff*((dmp+NSPES*part[i].s+part[j].s)->npot>1?
mpot(r,dmp+NSPES*part[i].s+part[j].s,((REAL)rand())/RAND_MAX):
(dmp+NSPES*part[i].s+part[j].s)->pot[0](r,(dmp+NSPES*part[i].s+part[j].s)->dp ) );

At least reformat it to something like this:

deltaE += coeff*((dmp+NSPES*part[i].s+part[j].s)->npot>1
        ? mpot(r,dmp+NSPES*part[i].s+part[j].s,((REAL)rand())/RAND_MAX)
        : (dmp+NSPES*part[i].s+part[j].s)->pot[0](r,(dmp+NSPES*part[i].s+part[j].s)->dp));

However, this may still be too lengthy for a ternary.  You could still use a plain if/else if it would help more with readability.


Count word frequencies, and print them most-frequent first

Mainly this looks fine.

using namespace std; is a bad habit to get into due to potential name collisions. Instead prefer to type std:: where necessary.

counts[word]++;. We don't need an un-incremented copy of the count, so we should use pre-increment here instead: ++counts[word];

sort(ordered.begin(), ordered.end(), [](auto &a, auto &b) we don't alter a or b in the lambda, so these should be const&.

for (auto count : ordered) copies the pairs. Again, we should be using auto const& here.

return 0; we don't need this, as the compiler will add it for us automatically. We might also use a named constant instead of 0, specifically EXIT_SUCCESS from <cstdlib>.


Showing data for a chat with another user

You can break the functionality in to 2 seperate methods to make it more reusable. Here, findChatByUsers could return a collection or null, so the type hint was removed.

public function findChatByUsers(User $user, User $contraUser)
{
    $chat = $this->chatRepository
        ->findByUsers($user, $contraUser)
        ->first();

    return $chat;
}

public function getChat(User $user, User $contraUser) : Collection
{
    $chat = $this->findChatByUsers($user, $contraUser);

    // If chat is not available, create new chat
    if (!$chat) {
        $chat = $this->chatRepository->create();
        $member = $this->chatMemberRepository->create($chat, $user);
        $contraMember = $this->chatMemberRepository->create($chat, $user);
        $chat = $this->chatRepository->find($chat->id);
    }

    return $chat;
}


Accepting a positive integer from either a command-line argument or System.in

user_input can be better renamed as userInput.

If you want to make the prompting 'self-contained', put it inside a method that will re-prompt the user for non-integer values:

private static int getIntegerInput(Scanner scanner) { ... }

I also don't think you need to catch ArrayIndexOutOfBoundsException, instead consider picking up from the command line only if args.length is at least 1:

// calls getIntegerInput(Scanner) with scanner if input is not an integer
private static int parseStringOrPrompt(String input, Scanner scanner) { ... }

Putting it altogether:

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        int num = args.length > 0 ? parseStringOrPrompt(args[0], scanner)
                                    : getIntegerInput(scanner);
        while (num < 0) {
            System.out.print("That's a negative integer.");
            num = getIntegerInput(scanner);
        }
        System.out.println("Yes, '" + num + "' is a positive integer.");
    }
}


I would write this like:

$(function(){

  var header = $('header');
  var threshold = header.offset().top;

  $(document).scroll(function(){
      header.toggleClass('filled', $(this).scrollTop() - 10 > threshold);
  });

});


Recursive function that reverse the words in a string

The program below is just for fun.

Since the program asks for recursion, then in principle, recursion should be the sole iteration technique. Assuming that the requirement is to only implement a single function, and that string is '\0' terminated, the following program illustrates how this is possible.

Basically, the technique is to use the value of count control the mode of the reverse function. There are three modes: initial call, reverse each word, and reverse string.

A positive count signals the initial call, and count represents the length of the string. On initial call, the program follows the algorithm recipe of: first reverse the input string, then reverse each word in the input string.

A count value of zero causes the function to find the beginning and end of the first word in the string, reverse it, and recursively repeat the process beginning after the just reversed word.

A negative count causes the function to reverse the string assuming its length is -(count + 1). The off by one length is used to make sure the string reversal case does not run into the word reversal case. Thus, a -1 count represents an empty string.

void reverse (char *string, int count) {
    if (string == NULL || *string == '\0') return;
    // positive count := initial call
    if (count > 0) {
        reverse(string, -count-1); // reverse the whole string
        reverse(string, 0);        // reverse each word in whole string
        return;
    }
    // zero count := reverse each word in the string
    // skip over whitespace, then find end of word, reverse word, repeat
    if (count == 0) {
        char *p = string;
        int sl = strspn(p, " \t");
        int wl = strcspn(p + sl, " \t");
        reverse(p + sl, -wl-1);    // reverse the found word
        reverse(p + sl + wl, 0);   // reverse each word in rest of string
        return;
    }
    // negative count := reverse string of length -(count + 1)
    // reverse the string by swapping first and last, then shrink
    count = -(count + 1);          // fix-up count value
    if (count < 2) return;
    char t = string[0];
    string[0] = string[count-1];
    string[count-1] = t;
    reverse(++string, ---count);
}

Note the lack of looping structures within the function. All loops are accomplished with recursion or hidden by standard library functions strspn and strcspn.


Mac Bash: how to combine the open and str subtract to one line code?

You can use open with an absolute path, it doesn't have to be a relative path.

That is, you could write the same in one line, with some basic improvements:

openUp() {
  open "$(sed 's@\(.*\)/.*@\1@' <<< "$1")/.."
}

The basic improvements:

Instead of echo "..." | cmd, use here strings: cmd <<< "..."
Double-quote variables used as command line arguments (in your example, of cd, and echo
It's not recommended to use the function keyword, write without

A more important improvement would be to stop using sed to get the name of the base directory. Using a regex is error-prone and not as intuitive as the dirname command:

openUp() {
  open "$(dirname "$1")/.."
}

Notice that the arguments of dirname and open are both double-quoted,
as mentioned earlier.
This is necessary, to protect from word-splitting and globbing.


This may be an incorrect assumption, but it seems like with your proposed approach, you would need to either keep the HTML for each page within the HTML for the main page in the onclick attributes for each link or else have the links contain a key that corresponds to a mapping of keys to HTML for the pages.

There are tools like Vue Router that are built for this scenario. With Vue Router you can have the HTML templates stored in separate files and imported into the router.

One other thing I noticed in your sample VueJS code is that you have a Vue object for the header and a Vue object for the page. Those could be combined into a single object for an element that contains both elements, unless you want the header to be a separate component - then defining that as a component would be useful.

//these template values can come from external files as well
const Page1 = {
  template: '
Page 1
'
}
const Page2 = {
  template: '
Page 2
'
}
const Page3 = {
  template: '
Page 3
'
}
const routes = [{
    path: '/page1',
    component: Page1
  },
  {
    path: '/page2',
    component: Page2
  },
  {
    path: '/page3',
    component: Page3
  }
];
const router = new VueRouter({
  routes: routes
});

const viewApp = new Vue({
  el: "#app",
  router: router,
});
#page {
  margin: 30px 0;
}

    <router-link to="/page1">Page 1</router-link>
    <router-link to="/page2">Page 2</router-link>
    <router-link to="/page3">Page 3</router-link>

    <router-view></router-view>

    Footer


Random permutation of int[] and ArrayList

Use for-each

Use for-each idiom to loop over an array when possible, and you can drop this comment:

//loop for element in array
for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
}

Like this, and without the pointless comment:

for (int item : array) {
    System.out.print(item + " ");
}

Use a different list implementation for unused

In SmartPermutationGenerator,
you're using an ArrayList for the unused numbers,
and randomly remove items from it.
An ArrayList is backed by an array,
and removing items from arrays is an expensive operation:
elements after the removed element must be moved to fill the gap.
You can improve that point by using a LinkedList instead,
where removal of elements is cheap.

public List<Integer> getRandomPermutation() {
    List<Integer> unused = new LinkedList<>();
    for (int i = 0; i < size; i++) {
        unused.add(i + 1);
    }

    List<Integer> permutation = new ArrayList<>();
    for (int k = 0; k < size; k++) {
        int pos = random.nextInt(unused.size());
        permutation.add(unused.get(pos));
        unused.remove(pos);
    }

    return permutation;
}

Use boolean expressions directly without ==

You don't need to write == true when evaluating boolean expressions like this:

if (fill == true) {

This is exactly the same but shorter, simpler, intuitive:

if (fill) {

Remove unused code

These variables are completely unused, remove them:

  int low = 1;
  int high = 10;
  int range = high - low + 1;

Printing arrays

In both implementations, you're using a for loop to print arrays.
There's are easier ways.

The toString method of List implementations gives a nice representation,
so you can print them directly:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
System.out.println(list);
// prints: [1, 2, 3, 4, 5]

To print arrays in the same format, you can use Arrays.toString:

int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));
// prints: [1, 2, 3, 4, 5]

Formatting

Your code doesn't follow the common formatting used by auto-formatting of editors like Eclipse, IntelliJ, NetBeans. Instead of this:

  do
  {
    fill = true;
    r = rand.nextInt(10) + 1;

     for (int i = 0; i < array.length; i++)//loop for random number between 1 to 10
     {
        if (array[i] == r)
        {
           fill = false;
        }
     }

Following the same style as recommended by these tools,
your code would look like this:

do {
    fill = true;
    r = rand.nextInt(10) + 1;

    for (int item : array) {
        if (item == r) {
            fill = false;
        }
    }


Find k-distinct partitions which contain at least two perfect squares

This is an interesting challenge! Here are some ways you could improve your code.

Globals

None of your variables should be global. It makes it significantly harder to figure out where a variable is changing. Given that you reset sum and perf to 0 every time you enter func(), they should be locally declared within the function. i is only used within func() as well. You should prefer declaring variables as close to their first use as possible to make it easier to find the declaration. For loops, it's often best to declare them in the loop like this:

for (int i = 0 ; i < k; i++) {
    ...
}

This also avoids problems that can occur with re-using loop index variables. Notice that you assign to i at the start of the last loop in func(), but then it is never incremented or checked in that loop. It's entirely superfluous, and confusing to read.

func() should return a count rather than incrementing a global variable. For example you could make a local variable and use it like this:

int func(int index, int val) {
    int numPerfectPartitions = 0;
    if (index == k) {
        ...
        if (sum == n) {
            ...
            if (perf >= 2) {
                numPerfectPartitions++;
            }
        }
    }
    else {
        a[index]=val;
        for (...) {
            numPerfectPartitions += func(index + 1, a [ index ] + 1);
        }
    }
    return numPerfectPartitions;
}

Naming

I feel like your names are too vague. perfect() is OK. I would name it isPerfect() just to be more clear, and since it returns what is essentially a Boolean value.

n and k match the text of the challenge, but are bad variable names. I recommend changing n to desiredSum since that's the target number you're trying to reach. (Or even target.) I would name k numPartitions since that's the number of partitions.

a is probably best called something like addends or summands. This is a case where there's no real-world analog, so the names get a little technical. But a is just too vague.

count is an OK name, but what is it a count of? numFound would be better.

func() tells you literally nothing other than that the function is a function, which anyone who can read C already knows. Since it finds partitions, why not call it findPartitions()?

Performance

I'll admit that I don't know off the top of my head of a significantly better way to do this. I suspect that if you first found the perfect squares between 1 and n, then you could find the partitions more quickly. For example, generate all perfect squares between 1 and n, and then find all combinations of 2 through k of the perfect squares that sum to less than or equal to n. Subtract that sum from n to find a new, smaller sum m, and then generate all combinations of the remaining (non-perfect-square) numbers that sum to m. Since you're summing to a smaller value, you should have fewer permutations to go through.


Generating user ids on a random forum website

Personally, when I need something to be secure and consistently unique is to add a secret to an incrementing ID, which I assume your DB already has.

Your members have ID's and they are incremental, but then you can design a secret phrase or some sort of algorithm to append to that number, and then mcrypt it, or, depending on how secure you need your UID, encrypt in other ways and then concatenate it to your desired length.


VBA code to underline numbers in the header takes significant time and sometimes crashes excel

ActiveSheet.PageSetup.CenterHeader = "" & z & ""

There's no reason to run this instruction at every single iteration as z is still in the process of being concatenated, is there?

Move it out of the loop and assign PageSetup.CenterHeader once, only when you've figured out the entire final string value - this could have a dramatically positive impact on performance :)

The name of the procedure/macro should not have underscores in it; convention is to use PascalCase for procedure/member names.

The procedure is implicitly Public and could use an explicit access modifier.

Reading the name of the procedure I was expecting it to go through page headers and underline whatever numeric values are in there... but that's not what's happening, and the variable names aren't helping much. Take the time to spell them out, and thank yourself later!

That said I'd suggest taking in a Workbook parameter and removing the ActiveWorkbook and ActiveSheet dependencies, which force any VBA code calling this procedure to Select and Activate things, which as you know isn't ideal.

Actually, the procedure has too many responsibilities, that's why its name feels wrong. It should be a function that takes a String argument and returns the formatted string: that's what I would expect a "make numbers underline" procedure to do. Then another procedure can be responsible for knowing what worksheet to interact with, and for setting its PageSetup.CenterHeader:

Dim headerText As String
headerText = UnderlineNumbers(ActiveWorkbook.Name)
ActiveSheet.PageSetup.CenterHeader = headerText

The string-valued Mid$ function should work slightly better than the similar but variant-valued Mid function, and when the current character is being pulled from the string in 3 places, it's time to introduce a local variable ;-)

This should be pretty much instant:

Private Function UnderlineNumbers(ByVal value As String) As String
    Dim result As String
    Dim i As Long
    For i = 1 To Len(value)
        Dim current As String
        current = Mid$(value, i, 1)
        If IsNumeric(current) Then
            result = result & "&U" & current & "&U"
        Else
            result = result & current
        End If
    Next
    UnderlineNumbers = result
End Function


How could I remove repetition from this linq-to-entities query?

Use the let statement and also do the final orderby after the where clause, this will increase efficiency, as less entries will have to be sorted

IQueryable<Article> query = from a in _db.Articles
    let  rev = a.AnswerRevisions.OrderByDescending(r => r.DateCreated).FirstOrDefault()
    where a.AnswerRevisions.Count > 0 &&
          (rev.UpVotes - rev.DownVotes < 0)
    orderby a.DateCreated descending
    select a;


Thread safe logging class in C# to use from DLL

I don't think Log should be public, it is confusing. Me, as a client of your logging API, shouldn't need to create an instance of TextWriter to be able to log something. If I want to do some IO, I'll do it all by myself and won't pass by the logging API.

The naming is a little flawed. tw should be (I think), logTextWriter or something like that. Good variable name is worth more than the space you save by having bad ones. SPath should be GetLoggingPath or something like that.

If I understand your code correctly, if I leave the application running for 30 days, my log file will always be dated of the 1st day I opened the application, because of the static ctor, it may cause confusion.

In the Log method, there is a (very very very) small window for a bug. Instead of doing :

w.WriteLine("{0} {1} {2}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString(), logMessage);

you should do :

DateTime now = DateTime.Now;
w.WriteLine("{0} {1} {2}", now.ToLongTimeString(), now.ToLongDateString(), logMessage);

(If you don't want to consider the millisecond that could make DateTime.Now change, just consider I think it'd also be more readable.)

I'm no threading expert, but I know for a fact that your code is thread-safe, though there might (or not) be concurrency issues I'm not aware of if you have lot of calls on the Log method.

Finally, logging classes are usually interfaced. If you ever want to unit test your classes that uses the logging API, you don't want to be writing in a real file. Your class is static, meaning you can't interface it. This is a good opportunity to use the Singleton pattern :

public interface ILogger
{
    void Write(string logMessage);
}

public class Logger : ILogger
{
    private static readonly object _syncObject = new object();
    private static readonly Lazy<ILogger> instance = new Lazy<ILogger>(() => new Logger(),LazyThreadSafetyMode.ExecutionAndPublication);

    private readonly TextWriter textWriter;

    public static ILogger Instance => instance.Value;

    private Logger()
    {
        const string FMT = "yyyy-MM-dd";
        DateTime now1 = DateTime.Now;
        string strDate = now1.ToString(FMT);

        textWriter = TextWriter.Synchronized(File.AppendText(SPath() + "\\Log " + strDate + ".txt"));
    }

    public void Write(string logMessage)
    {
        try
        {
            Log(logMessage, textWriter);
        }
        catch (IOException e)
        {
            textWriter.Close();
        }
    }

    private void Log(string logMessage, TextWriter w)    {
        lock(_syncObject) {
            DateTime now = DateTime.Now;
            w.WriteLine("{0} {1} {2}", now.ToLongTimeString(), now.ToLongDateString(), logMessage);

            w.Flush();
        }
    }

    private static string GetPath()
    {
        return ConfigManager.GetAppSetting("logPath");
    }
}

Note the usage of Lazy<ILogger> which is a thread safe lazy loader generic utility to make sure the constructor isn't called twice by two different threads.

Using this interface, you can then use the dependancy injection to use your ILogger interface everywhere without caring about the implementation! :)


Guess the computer's number using functions

There is a classic problem in this condition:

while replay_question != 'y' or 'n':

It always evaluates to True since string n is always truthy.

And, here is a set of code style violations I would work on:

guess variable inside the human_guess() function is unused
keep 2 blank lines between the function definition (PEP 8 - Style Guide)
put the main() function call into under the if __name__ == '__main__':
the print("Invalid. Enter a number between 1-100 ") is overly indented with 8 spaces, use 4 spaces
you can use a multi-line string for your intro message:

print("""
Welcome to, Guess My Number!
Simply guess the number between 1-100 that the Computer is 'thinking' of!
""")


Express error if agency not found middleware

I managed to accomplish this by adding the agency to res.locals. Here's the amended code:

// /routes/v1/index.js

const router = require("express-promise-router")()

router.use(["/agencies/:id", "/agencies/:id/*"], agencies.addAgencyToResLocals, agencies.ensureUserIsMember)

router
  .route("/agencies/:id")
  .get(agencies.getById)
  .patch(agencies.ensureUserIsAdmin, agencies.patch)
  .delete(agencies.ensureUserIsAdmin, agencies.delete)

// /controllers/v1/agencies/addAgencyToResLocals.js

import db from "../../../db"
import { AgencyDoesNotExistError } from "../../../errors"

export default async (req, res, next) => {
  const agency = await db.agency.getById(req.params.id)

  if (!agency) throw new AgencyDoesNotExistError()

  res.locals.agency = agency

  next()
}

// /controllers/v1/agencies/ensureUserIsMember.js

import { UnauthorizedError } from "../../../errors"

export default (req, res, next) => {
  const { agency } = res.locals

  const isMember = agency.members.find(member => member.authId === req.user.sub)

  if (!isMember) throw new UnauthorizedError()

  next()
}

// /controllers/v1/agencies/getById.js

export default async (req, res) => res.send(res.locals.agency)

I'm not sure if this is the best solution but it simplifies my code a lot. The one issue I see is that another person working with the code base for the first time would have to have knowledge about the middleware being applied. That being said I feel it's acceptable to say that someone working with express should have knowledge of middleware and how it works IMO.


Python differential analysis of heat loss across a pipe

Globals in Python are not necessarily a bad thing, especially for what you're using them for. However, they can be prevented. There are a couple of major flaws I found so I'm glad you came over to get a review. The point you're most worried about will be handled at the end.

Style

Clean Python code adheres to PEP8, the general style guide for Python. Your code violates this guide in a couple of ways. I'll explain the violations I deem most important and fixed it up for you to show the difference. I do recommend you read PEP8 yourself as well.

To verify whether your code adheres to the guide, you can either use the pep8 tool inside Python itself or pep8online. This will validate your code against most of the guide.

Import

Import statements should be on top of your file for maintainability purposes. This is a common practice in many languages, including C, C++, C# and Java. If I now skim your code, I'll see unexpected functions like plt.xlabel() because I didn't notice the following line:

from matplotlib import pyplot as plt

All imports should be on the top.

Globals

Imports should be followed by your global variables. Often those globals are supposed to be constant (note that Python does not actually enforce them being constant). The naming convention for constants is UPPERCASE_WITH_UNDERSCORES. This makes it clear to anyone reading the code the value should not be changed and is probably defined at module level.

This also means that other variables should not use the same casing. All relevant casing styles are in the PEP8.

Variable naming

Now we're handling variables anyway, please use more descriptive variable names. Single-letter variables and functions make for hard-to-read code. Code should be self descriptive. With good names, many of your comments would become redundant. Functions with names are fun can definitely use something more descriptive.

Whitespace

Give your operators and commas some breathing room. foo, bar(woof + 1), fizz is a lot easier on the eyes than foo,bar(woof+1),fizz.

Indentation is done with spaces, not with tabs. Multiples of 4 are preferred, but multiples of 2 are also common.

import scipy
import numpy as np
from scipy.optimize import minimize
from matplotlib import pyplot as plt

R_w = 0.654  # W/mk water heat loss ocefficient
R_f = 0.042  # W/mk pipe heat loss coefficient
PIPE_RADIUS = 0.2  # m pipe radius
PIPE_LENGTH = 25  # m length of pipe
TEMPERATURE_INITIAL = 50  # C initial temperature
TEMPERATURE_AMBIANT = 20  # C ambiant temperature
dx = 0.0001  # m differential distance

def heat_balance(T_1, T_2):
    heat_in = (T_1-T_2) * scipy.pi * PIPE_RADIUS**2 * R_w
    heat_out = ( (T_1 + T_2) / 2 - TEMPERATURE_AMBIANT ) * 2 * PIPE_RADIUS * scipy.pi * dx * R_f
    return abs(heat_in-heat_out)

def simulation():
    T = [TEMPERATURE_INITIAL]
    X = [0]
    print 'r is ', R_f
    for x in np.arange(dx, PIPE_LENGTH, dx):
        X.append(x)
        fun = lambda s: heat_balance(T[-1], s)
        T.append(float(minimize(fun, T[-1] - dx, method="SLSQP")['x']))
    return([T, X])

typs = ['+', 'x', '|', '_', '*']
cols = ['red', 'blue', 'black', 'purple', 'brown']

for i, rf in enumerate([7, 14, 50, 100, 200]):
    R_f = 1.0/rf
    ans = simulation()
    plt.scatter(ans[1], ans[0], c=cols[i], marker=typs[i], s = 100, label=rf, lw=3)

plt.legend(fontsize=20, title='Pipe Insolation R Value')
plt.xlabel('Distance (m)', fontsize=20)
plt.ylabel('Average Temperature (C)', fontsize=20)
plt.show()

Objective Oriented Programming

This is one of the best solutions against global variables: objective oriented programming.

Did you know you can make classes in Python?

class PipeCalculator:
    self.R_w = 0.654  # W/mk water heat loss ocefficient
    self.R_f = 0.042  # W/mk pipe heat loss coefficient
    self.PIPE_RADIUS = 0.2  # m pipe radius
    self.PIPE_LENGTH = 25  # m length of pipe
    self.TEMPERATURE_INITIAL = 50  # C initial temperature
    self.TEMPERATURE_AMBIANT = 20  # C ambiant temperature
    self.dx = 0.0001  # m differential distance

    def heat_balance(self, T_1, T_2):
        heat_in = (T_1-T_2) * scipy.pi * self.PIPE_RADIUS**2 * R_w
        heat_out = ( (T_1 + T_2) / 2 - self.TEMPERATURE_AMBIANT ) * 2 * self.PIPE_RADIUS * scipy.pi * dx * R_f
        return abs(heat_in-heat_out)

    def simulation(self):
        T = [self.TEMPERATURE_INITIAL]
        X = [0]
        print 'r is ', self.R_f
        for x in np.arange(self.dx, self.PIPE_LENGTH, self.dx):
            X.append(x)
            fun = lambda s: self.heat_balance(T[-1], s)
            T.append(float(minimize(fun, T[-1] - self.dx, method="SLSQP")['x']))
        return([T, X])

    def plot_calculations(self):
        typs = ['+', 'x', '|', '_', '*']
        cols = ['red', 'blue', 'black', 'purple', 'brown']

        for i, rf in enumerate([7, 14, 50, 100, 200]):
            self.R_f = 1.0/rf
            ans = simulation()
            plt.scatter(ans[1], ans[0], c=cols[i], marker=typs[i], s = 100, label=rf, lw=3)

        plt.legend(fontsize=20, title='Pipe Insolation R Value')
        plt.xlabel('Distance (m)', fontsize=20)
        plt.ylabel('Average Temperature (C)', fontsize=20)
        plt.show()

calculator = PipeCalculator()
calculator.plot_calculations()

And poof, all the globals are gone.

Of-course, a straight port from what you have to object oriented still looks ugly. Pass some variables around, use the power of arguments and when in doubt don't hesitate to split up to more functions. But at least you now have a start and it will be easier to re-use this code later on in different projects.

As two final notes:

Your lambda could be re-written to a normal function for improved readability. This may help you figure out how to optimize the calculations.
Pipes usually have an inside and outside diameter. You may want to explicitly state which one you're using.


Naming

Use camelCase for local variable names. And, use a meaningful name if possible.

//var List1 = new List<int>{1,2,3,4,5,6,7,8,9};
var validNumbers = new List<int>{1,2,3,4,5,6,7,8,9};

Use pluralized noun for variable of collection type.

//var combo = ... /*combo contains all possible combinations, not just one*/
var combos

Code

You don't need to enumerate the numbers 1 to 9. A Enumerable.Range will do the job.
The chain of !exceptions.Contains(x) is rather inefficient and redundant. You can avoid them by removing the exceptions from the start with IEnumerable.Except.
You can reuse the same list in your LINQ.
You can reuse the same name for your lambdas given they are not within the same parentheses.  (Not really a big problem)

Result :

var validNumbers = Enumerable.Range(1, 9).Except(exceptions);
var combos = (from a in validNumbers
              from b in validNumbers
              from b in validNumbers       // Cartesian product
              where a > b && b > c &&      // exclude duplicates
                    a + b + c == target    // add up to the target
              select new List<int>{ a, b , c})
             .OrderByDescending(x => x[0])
             .ThenByDescending(x => x[1])
             .ThenByDescending(x => x[2]);

In the last 2 blocks of the code, Console.Write was repeatedly called within the for loop. You can join them together with String.Join before printing it to the console.

Results :

foreach(var item in combos)
    Console.WriteLine(string.Join("", item));

Console.Write("excluding " + string.Join(" ", exceptions));

Final Code

This can be directly copied to LinqPad and ran.

void Main()
{
    string buffer;
    int target, elementCount;

    //get target
    Console.WriteLine(">> Target is ..?");

    while(!int.TryParse(buffer = Console.ReadLine(), out target))
        Console.WriteLine("\tInvalid input : {0}", buffer);
    Console.WriteLine(target);

    //get elementCount
    Console.WriteLine(">> Number of elements is ..?");

    while(!int.TryParse(buffer = Console.ReadLine(), out elementCount) ||
          1 > elementCount || elementCount > 6)
        Console.WriteLine("\tInvalid input : {0}", buffer);
    Console.WriteLine(elementCount);
    Console.WriteLine(/*Empty Line*/);

    //get exceptions
    var validNumbers = Enumerable.Range(1, 9);
    IEnumerable<int?> exceptions;
    Console.WriteLine(">> Exceptions are ..? (separated with comma like : 1,2,3)");

    while(!TryParseExceptions(buffer = Console.ReadLine(), out exceptions))
        Console.WriteLine("\tInvalid input : {0}", buffer);
    Console.WriteLine(string.Join(" ", exceptions.OrderBy(x => x)));

    Console.WriteLine(/*Empty Line*/);
    CalculateCombinations(target, elementCount, exceptions.Select(e => e.Value).Distinct());
}

int? ToNullableInt(string value)
{
    int number;
    return int.TryParse(value.Trim(), out number) ? (int?)number : null;
}
bool TryParseExceptions(string value, out IEnumerable<int?> exceptions)
{
    //const int MinValue = 1, MaxValue = 9;
    exceptions = value == ""
        ? Enumerable.Empty<int?>()
        : value.Split(',').Select(ToNullableInt);

    return exceptions.All(e => e.HasValue && (1 <= e.Value && e.Value <= 9)); //less verbose but magical...
    //return exceptions.All(e => e.HasValue && (MinValue <= e.Value && e.Value <= MaxValue));
}

// Define other methods and classes here
void CalculateCombinations(int target, int elementCount, IEnumerable<int> exceptions)
{
    var validNumbers = Enumerable.Range(1, 9).Except(exceptions);

    // Make a Cartesian join of the three lists
    // Filter out the stuff that we want
    // Sort the result from highest to lowest
    var combos = validNumbers.CartesianProduct(elementCount)     // Cartesian product
                            .Where(x => x.GreaterThanNext() &&   // exclude duplicates
                                        x.Sum(y => y) == target) // add up to the target
                            .OrderByDescending(x => x.First());  // sort from the 1st number to...

    for(int i = 1; i < elementCount; i++)
    {
                    ///i would be incremented when the ienumerable unfolds
        var index = i;
        combos = combos.ThenByDescending(x => x.ElementAt(index));   // ... the [n]th
    }

    Console.WriteLine(string.Format("{0}/{1}", target, elementCount));

    foreach(var item in combos)
        Console.WriteLine(string.Join("", item));

    Console.Write("excluding : " + string.Join(" ", exceptions.OrderBy(x => x)));
}

//credit : http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/
//slightly altered to reuse the same sequence

public static class Extensions
{
    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<T> sequence, int repeat)
    {
        IEnumerable<IEnumerable<T>> result =  new[] { Enumerable.Empty<T>() };

        for(int i = 0; i < repeat; i++)
        {
            // don't close over the loop variable (fixed in C# 5 BTW)
            var s = sequence;
            // recursive case: use SelectMany to build
            // the new product out of the old one
            result = from seq in result
                    from item in s
                    select seq.Concat(new[] {item});
        }

        return result;
    }

    public static bool GreaterThanNext(this IEnumerable<int> sequence)
    {
        if (sequence.Count() < 2) return true;

        var previous = int.MaxValue;
        foreach(var item in sequence)
            if(previous <= item)
                return false;
            else previous = item;

        return true;
    }
}

Example of result :

>> Target is ..?
25
>> Number of elements is ..?
4

>> Exceptions are ..? (separated with comma like : 1,2,3)
1

25/4
9862
9853
9763
9754
8764
excluding : 1


Set + Queue + a get method backed by a Map

Bug in retainAll

The method retainAll does not respect its contract. It is supposed to remove from this set all the elements that are not contained in the given set. However, the following code:

Set<String> set = new QueuedSetWithGetImpl<>();
set.add("foo");
set.add("bar");
set.retainAll(Arrays.asList("foo"));
System.out.println(set.size()); // prints 2!

does not remove the "bar" element from the set (the size is still 2).

The issue with the current code is that it doesn't loop over the elements of the set to find the ones not contained in the given collection. To implement it correctly, you can use an Iterator and call remove():

@Override
public boolean retainAll(Collection<?> paramCollection) {
    boolean mapChanged = false;
    Iterator<E> it = iterator();
    while (it.hasNext()) {
        if (!paramCollection.contains(it.next())) {
            mapChanged = true;
            it.remove();
        }
    }
    return mapChanged;
}

Access control

LinkedHashMap<E, E> map = new LinkedHashMap<E, E>();

This map needs to be private. It is the backing map of your implementation and is not intended to be used by other classes.

Possible simplification

boolean notAlreadyPresent = !map.containsKey(paramE);
if (notAlreadyPresent) {
    map.put(paramE, paramE);
}
return notAlreadyPresent;

This can be simplified a bit by using the result of put, which is either the previous value or null if there was no mapping. As such, you can have:

return map.put(paramE, paramE) == null;

Note that will replace the old value with the given new value, but it won't break the contract of the Set which defines equality in terms of equals and not ==. To not replace, you could use putIfAbsent on Java 8, but since you're using Java 7, you could keep what you have.


The following will shorten your code considerably:

Public Function GrainSubtraction(ByVal numberOne As Double, ByVal numberTwo As Double) As Double
    Dim Dec1 As Integer = CInt(Int(numberOne / 10.0))
    Dim Oct1 As Integer = CInt(numberOne - (Dec1 * 10))
    Dim Dec2 As Integer = CInt(Int(numberTwo / 10))
    Dim Oct2 As Integer = CInt(numberTwo - (Dec2 * 10))
    Dim ResultDec, ResultOct As Integer
    If Oct1 < Oct2 Then
        Dec1 -= 1
        ResultOct = CInt(7 - (Oct2 - Oct1))
    Else
        ResultOct = CInt(Oct1 - Oct2)
    End If
    ResultDec = CInt(Dec1 - Dec2)
    Return CDbl((Math.Abs(ResultDec * 10) + ResultOct) * Math.Sign(ResultDec))
End Function

This does simple octal subtraction on the last digits of the numbers supplied and decimal subtraction on the rest.  I left the parameters and the return type as doubles but it would make more sense to have them as integers, since that's what they basically are.


Op's code has a possible race condition between the lock and compare.

"lock xadd %[lock], %[gate]\n"
"cmp %[lock], %[open]\n"

OP identified: lock is not certainly made a shared variable.


I'm not familiar with log4net, so I will focus on the code itself.

Here is a list of what could be improved:

--- Style ---
ErrorHandler should be a static class to prevent newing up an instance of it
Lack of using namespace: Generally, you should declare all of them, unless:

there is an conflic in which case you can alias it: using A = Some.Namespace.A
a namespace is particularly noisy and is polluting the intellisense

Lack of var: Using the type name or the full name can make the code difficult to scan through. It is more difficult to locate a variable when they are not aligned. For the most part, the right hand side assignment should give enough of hint.

System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(1);
System.Reflection.MethodBase caller = sf.GetMethod();
string currentProcedure = (caller.Name).Trim();
// --- for comparison
var sf = new System.Diagnostics.StackFrame(1);
var caller = sf.GetMethod();
var currentProcedure = (caller.Name).Trim();

Lack of "spacing": Nobody likes reading a wall of text, and a wall of code is no better. You can divide the logical blocks of your code with some empty lines: (Think of them as paragraphs)

// gather context
var sf = new System.Diagnostics.StackFrame(1);
var caller = sf.GetMethod();

// format message
var currentProcedure = (caller.Name).Trim();
var errorMessageDescription = ex.ToString();
errorMessageDescription = System.Text.RegularExpressions.Regex.Replace(errorMessageDescription, @"\r\n+", " "); //the carriage returns were messing up my log file
var msg = "Contact your system administrator. A record has been created in the log file." + Environment.NewLine;
msg += "Procedure: " + currentProcedure + Environment.NewLine;
msg += "Description: " + ex.ToString() + Environment.NewLine;

// handle exception
log.Error("[PROCEDURE]=|" + currentProcedure + "|[USER NAME]=|" + Environment.UserName + "|[MACHINE NAME]=|" + Environment.MachineName + "|[DESCRIPTION]=|" + errorMessageDescription);
MessageBox.Show(msg, "Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

Use of unnecessary parenthesis that doesn't highlight order of operation:

string currentProcedure = (caller.Name).Trim();
string[] comboList = valueList.Split((delimiter).ToCharArray());

--- code ---

string[] comboList = valueList.Split((delimiter).ToCharArray());
return comboList.GetUpperBound(0) + 1;

You can simply return comboList.Length here.

 /// <param name="delimiter">Represents the list delimiter </param>
 string[] comboList = valueList.Split((delimiter).ToCharArray());

You are using it as multiple delimiters, and not just one. The name should reflect that.

 /// <returns>the number of values in a delimited string</returns>

The return of value 0 in error handling should be documented in the <returns> or <remarks> tag.

public static class ErrorHandler
{
    public static void DisplayMessage(Exception ex)
    {
        var sf = new System.Diagnostics.StackFrame(1);
        var caller = sf.GetMethod();
        var currentProcedure = caller.Name.Trim();

        var logMessage = string.Concat(new Dictionary<string, string>
        {
            ["PROCEDURE"] = currentProcedure,
            ["USER NAME"] = Environment.UserName,
            ["MACHINE NAME"] = Environment.MachineName,
            ["DESCRIPTION"] = ex.ToString().Replace("\r\n", " "), // the carriage returns were messing up my log file
        }.Select(x => $"[{x.Key}]=|{x.Value}|"));
        log.Error(logMessage);

        // pick one:
        var userMessage = new StringBuilder()
            .AppendLine("Contact your system administrator. A record has been created in the log file.")
            .AppendLine("Procedure: " + currentProcedure)
            .AppendLine("Description: " + ex.ToString())
            .ToString();
        var userMessage = string.Join(Environment.NewLine,
            "Contact your system administrator. A record has been created in the log file.",
            "Procedure: " + currentProcedure,
            "Description: " + ex.ToString(),
        ) + Environment.NewLine;
        MessageBox.Show(userMessage, "Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}


As @LokiAstari says, hard-coding these escape strings into your program is a bad idea, as the escape sequences vary according to the type of terminal.  There are libraries such as ncurses and terminfo that do just that.

These macros only work when their arguments are string literals, which may be surprising to callers.

There is also a lot of repetition, much of it caused by lack of orthogonality.

If you wanted to "keep it simple" and do this anyway, you would be better off with

#define COLOR_RESET  "\033[0m"
#define BOLD         "\033[1m"
#define BLACK_TEXT   "\033[30;1m"
#define RED_TEXT     "\033[31;1m"
#define GREEN_TEXT   "\033[32;1m"
#define YELLOW_TEXT  "\033[33;1m"
#define BLUE_TEXT    "\033[34;1m"
#define MAGENTA_TEXT "\033[35;1m"
#define CYAN_TEXT    "\033[36;1m"
#define WHITE_TEXT   "\033[37;1m"

… to be used like

fprintf(stdout, "Recognized text: %s\n", text ? text : (RED_TEXT "No text recognized." COLOR_RESET));

For colour reset use "\033[0;m" instead of "\033[0,"


Matching a pattern in many lines of text

You should probably be using find() instead of matches() (source).

I would recommend using regexpal to test out your pattern, just in case.

Whether or not the Regex solution is faster, you'd have to run some tests, but I suspect it's MUCH faster.


How can I make my solution for Chef and Digits run faster?

Issues with your code

You didn't put any effort into choosing good names. Given a code challenge, either stick to the variable names used in the problem statement (n, m, ...) or, preferably, choose explicit and descriptive names such as steps, digits and indices rather than z, y, etc.

Why should you bother with this? Because good names reveal intent, and knowing what the code is supposed to do makes it possible for you and others to understand and improve it easily.

Your algorithm uses a naive, brute-force approach. This is fine as a starting point!
But when you get a time limit exceeded message, you need to think about smarter solutions.

Rene's answer gives you some good advice: He suggests that you employ caching, separate I/O from the calculation, and add up all the absolute values of by, thus skipping the calculation of B1 and B2. This is a good start but you can go much further.
Janne's answer tells you the essence of what's wrong with your algorithm: you need to avoid looping over the previous digits for every step. Why? Because there will be up to 105 (one hundred thousand) digits and up to 105 steps. However, it is unnecessary to make a sorted copy of the indices — see below.

How?

Start by separating your concerns.  Python has functions, so use them to group relevant parts of your code together, while keeping different levels of abstraction separate. Start at the most general level:

def main():
    print(*solve(sys.stdin), sep='\n')

We are saying: print each line of the result of solving the problem with the input from sys.stdin.
Our next concern is to parse the input:

def solve(lines):
    _, digits, *indices = lines
    return calculate_answer(as_ints(digits.rstrip()), as_ints(indices))

We discard the first line _ because we can deduce the length of the digits and the number of steps from the rest of the input, so there is no need to waste cycles parsing them.  We then store the digits which are given in the second line, as well as the indices from the following lines.

To get rid of the redundancies in your integer-conversion code, we extract a function:

def as_ints(iterable):
    return [int(x) for x in iterable]

We can pass the digits (stripping the newline character at the end) and the indices to this function to obtain usable values which we can use to calculate_answer(digits, indices). Since we have already parsed the input, this function can be focused on our algorithm to solve the problem.

def calculate_answer(digits, indices):

Store the indices in a dictionary, which allows them to be looked up in constant time.

result = dict.fromkeys(indices)

Set up another dictionary to count the number of occurrences of each unique digit, which will help us avoid iterating over all previous digits on every step.

counts = defaultdict(int)

Iterate over the digits and keep track of each digit's index, starting with 1

for index, digit in enumerate(digits, start=1):

If the current index is in result and we have not calculated a value for it yet:
Assign to the current index the sum of all the absolute values of the differences between the current digit and each unique previous digit d multiplied by its occurrences n.

    if index in result and result[index] is None:
        result[index] = sum(n * abs(digit - d) for d, n in counts.items())

Increment the number of occurrences of the digit we just encountered:

    counts[digit] += 1

In the order of the given indices, retrieve each calculated value from  result.

return (result[i] for i in indices)

Result

The end result is fast enough to be accepted by CodeChef. As you didn't specify a language version, this is in Python 3, which you should use as well. If you insist on sticking with Python 2.x, you will need to make the necessary adjustments.

import sys
from collections import defaultdict

def main():
    print(*solve(sys.stdin), sep='\n')

def solve(lines):
    _, digits, *indices = lines
    return calculate_answer(as_ints(digits.rstrip()), as_ints(indices))

def calculate_answer(digits, indices):
    result = dict.fromkeys(indices)
    counts = defaultdict(int)
    for index, digit in enumerate(digits, start=1):
        if index in result and result[index] is None:
            result[index] = sum(n * abs(digit - d) for d, n in counts.items())
        counts[digit] += 1
    return (result[i] for i in indices)

def as_ints(iterable):
    return [int(x) for x in iterable]

if __name__ == '__main__':
    main()


In terms of algorithm, I think it is best to focus on the answer you are after.  In This case you want the sum, but I notice your result returns the path and the sum.

If you want to focus on the sum think about starting from the bottom, and accessing the best path in terms of the bottom two rows and merging the results up.

Here is an example:

5
12, 3
2, 4, 9
1, 9, 12, 7

merge last 2 lines (lines 3 and 4)

2 + 9, 4 + 12, 9 + 12

merge the next line (line 2 and the merged result of 3 and 4)

12 + (4 + 12), 3 + (9 + 12)

merge the fist line (line 1 and the merged result of the 2, 3, and 4)

5 + (12 + (4 + 12))

some specific observations about your code

If you are going to access an element by index, use an indexed collection like Vector
Consider using fold or reduce instead of recursion with an accumulator
Props for using immutable variables and data structures

here is a link to my solution to the problem:
https://gist.github.com/dholbrook/6244448#file-euler18-scala


Header-only variadic console output and runtime input validation in C++ using templates

Comment

First question is why I would use this instead of the standard operator<< that we are all very familiar with?

Code Review

Reserved Identifiers

Identifiers with a prefix underscore and an initial capital letter are reserved in all contexts for the implementations. i.e. You are not allowed to use them.

So _INPUT_VALIDATION_HPP is an illegal identifier (for you).

The rules on leading underscore are complex. Even if you know the rules, most people don't, so avoid at all costs.

If you must, then make it a trailing underscore.

Manipulator support.

You have not provided support for stream manipulators (std::hex etc..).

std::endl or '\n'

Prefer '\n' over std::endl;. The difference is that std::endl also forces a flush. Manually forcing a flush is 99.99% of the time incorrect as the stream will automatically flush at the optimal times; doing it manually like this will severely degrade performance.

Recursive over iterative templates.

You use a recursive template design. Personally I prefer the iterative approach as it is more compact (and in my opinion readable).

// You recursive approach.
template <typename T>
void print(const T& input)
{
    std::cout << input << ' ';
}

template <typename T, typename... Types>
void print(const T& firstArg, const Types&... arguments)
{
    std::cout << firstArg << ' ';
    print(arguments...);
}

The alternative:

// The iterative approach.
template <typename T, typename... Types>
void print(Types const&... arguments)
{
    auto unused = {0, (std::cout << arguments << ' ', 0)...};
}

Get only half-checks.

In the get() function if it fails you drop the rest of the line and try again. This implies that the input is line based. BUT on success you don't check that the input is a whole line; you just check the line prefix.

// SO my code is.
int val = IO::get<int>();

// I type
10Ton

Then the above function accepts the input as good. But in my opinion that input should be considered to be incorrect as Ton is being ignored.


Counting primes in a range whose digits are all prime

Please read PEP8 and apply its advice; this will make your code look like Python code to others. Mainly, avoid code blocks on the same line as their conditions, and avoid cramming too many assignments on the same line.

You can also make your predicate function return a single value, as the first element of the returned tuple can be computed from the second (mainly p[0] is p[1] is None). You could also use the more common values -1, 0 and 1 and add an else clause in your xbinsearch loop to raise an exception. This would have caught the case where val == b in your usage.

Lastly, bisect should be the module to reach for when dealing with binary search in Python. In fact, having your list of primes ready, the code should be:

def get_total_primes(a, b):
    low = bisect.bisect_left(primes, a)
    high = bisect.bisect_left(primes, b)
    return high - low

And if you ever want to include the upper bound, you can:

def get_total_primes_inclusive(a, b):
    low = bisect.bisect_left(primes, a)
    high = bisect.bisect_right(primes, b)
    return high - low


Creating a script to automate implicit remoting

I wish I had more to offer but I wanted to add some pointers about the code I do see.

Code Repetition

If you find yourself repeating the same code over and over again you should be asking if there is another way.

Another function

You could easily wrap the block

  # Import first module
  Write-Verbose -Message 'Importing First module'
  Invoke-command { import-module 'Amodule.ps1' } -session $ServerPS
  Export-PSSession -Session $Server -OutputModule 'Amodule' -Force -AllowClobber

into its own function. That way if you need to make some changes they will be more centralized.

function Export-SessionModule{
    param(
        $session,
        $moduleName
    )
    # Import named module
    Write-Verbose -Message "Importing $moduleName module"
    Invoke-command { import-module "$moduleName.ps1" } -session $session
    Export-PSSession -Session $session -OutputModule $moduleName -Force -AllowClobber
}

Splatting

Note that this is meant to be a simple example. Things like parameter typing might be advisable but were omitted for brevity. If functions are overkill for this little script of yours something else to consider would be splatting your parameters that are the same across cmdlet calls.

$exportPSSessionParams = @{
    Session = $session
    Force = $true
    AllowClobber = $true
}

# .....
Export-PSSession -OutputModule 'Amodule' @exportPSSessionParams
# .....
Export-PSSession -OutputModule 'Bmodule' @exportPSSessionParams
# .....
Export-PSSession -OutputModule 'Cmodule' @exportPSSessionParams

Variable Names

You follow the verb-noun convention for your functions which is good.

Your session variable name is a little misleading. You call it $server. I usually see that representing a string with a server name. Since it is a session object it would be clearer if it was named as such. $session at a minimum or even $serverSession if you prefer. This could clash with your $sessionPS which is more reason to make them clear.

Function Declaration

You are supposed to declare your functions before you use them. That being said, you would typically find functions at the beginning of scripts. While the order you have things declared will not be a problem (since it is working) I wanted to be sure that was understood.

If you were to call go after your created the alias it would fail.

Your Problem

Like I said I don't have much to offer here. I would like to point out that I think you scrubbed your code incorrectly since the code in your error does not match your code block.

Have you checked on SO for that message already? There are a few different causes although I didn't find an exact match. Admittingly I do not work with modules much.
I would debug this by seeing if it is the same module and if perhaps how it is being called is causing some problems. Perhaps being run more than once in a session? (AllowClobber should have fixed that though)


Make multiple conditions in if expression more readable

Given the little context you have provided in the question, there isn't much to recommend, other than whitespace changes.

if  @tool_cvt_video_info_test.save and
    check_and_update_firmware_model_and_version(params["camera_ip"]) and
    save_uploaded(params[:videos])
  format.html {
    redirect_to @tool_cvt_video_info_test,
    notice: 'Video info test was successfully created.'
  }
  format.json {
    render action: 'show',
    status: :created,
    location: @tool_cvt_video_info_test
  }
else
  format.html { render action: 'new' }
  format.json {
    render json: @tool_cvt_video_info_test.errors,
    status: :unprocessable_entity
  }
end

I am a bit suspicious of this code, though.  It's saving some information about a video test, possibly updating the camera's firmware, and saving an uploaded video?  That's a lot of functionality to put in one if-condition, and if anything goes wrong, the user probably won't get sufficient feedback as to exactly what failed.


Array find min value with user-defined comparison compare function

This should be O(n)* where n is count($board_id).

$mapped = array_map(function ($id) use ($boardkey_to_values) {
    return array($boardkey_to_values[$id], $id);
}, $board_id);
asort($mapped);
list($min_value, $id) = reset($mapped);
$min_ids = array($id);
while (list($value, $id) = next($mapped)) {
    if ($value == $min_value) {
        $min_ids[] = $id;
    }
    else {
        break;
    }
}

* ignoring the call to asort which is probably O(n log n).


Checking the neighbor of the current cell

return Math.abs(c.getRow   () - getRow   ()) +
       Math.abs(c.getColumn() - getColumn()) == 1;

You want to be in the same row and one column apart, or in the same column and one row apart. Computing the absolute value of the difference in row and column numbers tells you how far apart the cells are irrespective of orientation. For horizontal and vertical neighbors these must add up to 1; that is, one of them must be 1 and the other must be 0.


Just some random things I noticed while looking over your code:

The way you're handling additions is a little odd to me. You seem to be continually maintaining an "empty node" at the end of the list, then when you add, you iterate to that node, replace its content then give it a new, empty node. Why not just have nextNode remain None, then iterate while currentNode.hasNextNode() to find the last node? Something like:

def getLastNode(self):
    currentNode = self.startNode
    while currentNode.hasNextNode():
        currentNode = currentNode.nextNode
    return currentNode

def insert(self, obj):
    newNode = Node()
    newNode.object = obj

    lastNode = self.getLastNode()
    lastNode.nextNode = newNode

From my experience, this is a far more typical set up. This also has the miniscule benefit of using slightly less memory, since you're no longer keeping one more node than needed in memory at all times. This also does away with the need for the hasObject method.

The definition of getNumberOfElements is completely impractical for most applications. You can assume for most, if not all data structures (besides maybe lazy lists), that a size method will run in O(1) time. Iterating the entire list every time you want to get the size has the opportunity to bring your application to a crawl; especially if the user of the class isn't aware that getNumberOfElements is O(n).

Just give your class a n_nodes field, and increment/decrement it in the appropriate methods:

def insert(self, obj):
    newNode = Node()
    newNode.object = obj

    lastNode = self.getLastNode()
    lastNode.nextNode = newNode

    self.n_nodes += 1 # Here

Then change getNumberOfElements to something like:

def size(self):
    return self.n_nodes

You can now get the size of the list nearly instantly instead of requiring a full iteration. The only drawback is you need to take care to properly manage n_nodes in all the methods that can change the size of the list.

Python isn't my main language, but I'm pretty sure snake_case is idiomatic Python. Coming from Java, you're probably more used to camelCase, but adhering to conventions is important for allowing other people to read your code easier. One thing you need to adjust to when writing in multiple languages is remembering what conventions the language you're writing uses. Clojure, my main language, uses dash-case; but this isn't even valid in many languages (like Python). I've gotten yelled at many times on Stack Overflow when answering questions in languages I don't use often because I forgot to adjust my naming conventions, and end up using either unidiomatic, or outright illegal names.

It would likely simplify your life if you gave the Node constructor the ability to directly set nextNode and object fields:

def __init__(self, newObject = None, newNextNode = None):
    self.object = newObject
    self.nextNode = newNextNode

That will save you a couple lines in the few places by just directly passing the object:

def insert(self, obj):
    newNode = Node(obj)

    # No longer needed!
    # newNode.object = obj

    lastNode = self.getLastNode()
    lastNode.nextNode = newNode

    self.n_nodes += 1

The "start node" of a linked list is more typically referred to as the "root".

def delete(self, index):
    if index == 0:
        startNode = self.getNodeByIndex(1)
...

Could probably be written more cleanly as simply

def delete(self, index):
    if index == 0:
        startNode = startNode.nextNode
...

For efficiency, you might also want to maintain a lastNode field. Right now, to get to the last node, you're needing to iterate the entire list, which is quite expensive. If you just keep a reference to the last node when you do an insertion, you can just use that reference instead of needing to iterate.

if index == (self.getNumberOfElements) - 1:

Is broken. You need to call the method.


You are correct. Math.random is indeed pseudo-random. However, its algorithm is actually quite good. In this SO post, a concern is brought up that the randomly generated numbers tend to all have the same number of digits. While this was statistically proven to make sense, you won't run into a similar problem since you are only dealing with single digit numbers.

Math.random should be random enough for your purposes. However, if you want to get truly random numbers to be absolutely fair, check out RANDOM.ORG. This, however, would obviously be a lot more unwieldy than just using Math.random.


Combine and minimize all .js files in parent folder

This snippet at the end...

if (compilingRequired())
{
    if (file_exists($cache_path)){
        unlink($cache_path);
        unlink($index_path);
    }

    $scripts_in_directory = getScriptsInDirectory();
    $file_handler = fopen($cache_path, 'w+');
    $cache_handler = fopen($index_path, 'w+');

    foreach ($scripts_in_directory as $name)
    {
        if (strlen(file_get_contents($cache_path)) > 0){
            fwrite($file_handler, str_repeat(PHP_EOL, 2));
        }

        fwrite($file_handler, '/**** ' . $name . ' ****/' . str_repeat(PHP_EOL, 2));
        fwrite($file_handler, compressScript(file_get_contents($name)));
        fwrite($cache_handler, $name . PHP_EOL);
    }

    echo file_get_contents($cache_path);
}
else
{
    echo file_get_contents($cache_path);
}

If they both end the same, there's really no need for an else case, you can just put the statement after the if statement.

if (compilingRequired())
{
    if (file_exists($cache_path)){
        unlink($cache_path);
        unlink($index_path);
    }

    $scripts_in_directory = getScriptsInDirectory();
    $file_handler = fopen($cache_path, 'w+');
    $cache_handler = fopen($index_path, 'w+');

    foreach ($scripts_in_directory as $name)
    {
        if (strlen(file_get_contents($cache_path)) > 0){
            fwrite($file_handler, str_repeat(PHP_EOL, 2));
        }

        fwrite($file_handler, '/**** ' . $name . ' ****/' . str_repeat(PHP_EOL, 2));
        fwrite($file_handler, compressScript(file_get_contents($name)));
        fwrite($cache_handler, $name . PHP_EOL);
    }
}
echo file_get_contents($cache_path);

Ideally, though, it'd read something like

if (compilingRequired())
{
    compile();
}
printCompressedFiles();

Because you want to program on the same level of abstraction - high level code is in "programmer english", describing the actions that need to be done (basically that list of 6 steps of yours, maybe compressed a bit). Low level code is pretty much regular code - code actually doing the work.


Great, glad you got rid of that loop: some more things I'd like to point out. As this is essentially another question now I'll add another answer

I don't think a function should call sys.exit(). I'd rather you raised an exception instead and call sys.exit() in __main__

I.e. instead of:

try:
    repo = git.Repo(args.path)
except:
    sys.exit("no such repo")

I would prefer:

from git import Repo, InvalidGitRepositoryError
#...

try:
    repo = git.Repo(args.path)
except InvalidGitRepositoryError, e:
    raise InvalidGitRepositoryError("%s is not a git repository" % (str(e)))

This enables other Python classes to use your main function (which is a terrible name) in a more predictable way (Python doesn't close calling your function).
I would also rather you check for the branch than assume if rev-list gives an error that the branch doesn't exist. There may be some other case that causes it to throw an exception.

class InvalidBranchError(Exception):
    pass

if args.branch not in repo.branches:
   raise InvalidBranchError("Branch does not exist: %s" % (args.branch))

Instead of main taking an arguments parser, I would prefer you used regular arguments (again so other python modules can use your code more readily):

def main(path=".", branch="master"):
   pass

main(path=args.path, branch=args.branch)


Multithreaded search for solutions to an inequality

You are asynchronously calculating intermediate results that are not worth parallelizing. Instead of calculating \$2^k\$ and \$3^k\$ sequentially, you do those calculations in parallel. But then you have to wait for both of them to complete before proceeding. I would expect that the overhead of setting up the async calls would negate any performance benefit.

Suppose you had a dozen friends helping you. Would you ask one of them to go off and calculate \$2^6\$, the second friend to calculate \$3^6\$, and report the results back to you so that you can check whether 6 is a solution? No, that would be crazy. You would be better off asking the first friend to check whether 6 is a solution, the second friend to check 7, the third friend to try 8, etc.  Then each of them has a chance to do some substantial work independently instead of waiting for each other's results.

Moreover, calculating \$3^k\$ would be a trivial multiplication if you already knew \$3^{k-1}\$. You should be able to avoid calling pow() altogether if you are trying increasing \$k\$.


Starting a database session
You are starting a dabatase session with the following code:
try{
$conn = new PDO($dsn,$username,$password,$options);
} catch (PDOException $e){
echo "Error!".$e->getMessage();
}

It is unclear to me why you let the request live on. If the application needs the database connection, letting the request live on produces all kinds of behaviour from code that assumes the connection is there. Consider killing the request right there and then.
Besides this, don't print the error message to the user. It is not useful to the average user, and might give an adversary additional information to find weaknesses in your site.
Keep in mind that if you include a php file, the variables inside it are available even outside that file. If an adversary can trick any other file that includes connection.php to display the contents of the $password variable, they can obtain the password this way. Arguably, the chance of this happening, but the adversary not being able to execute arbitrary code, is very small. You could defend yourself against it by unsetting the variable, or define those variables only in a function.
Storage of password
You are storing an unsalted MD5 hash from the password. MD5 has not been crytographically secure for a long time now, and any password can easily be brute-forced in it. Since your password is unsalted, cracking the passwords is as simple as looking it up in multiple already existing Rainbow tables. For example, the MD5 hash for your account is "Mohamed" (http://md5decoder.org/bc2ab28e4cda984ca76646874371e864).
I recommend to use bcrypt instead as hash function. It is designed to be slow, and the algorithm can not easily be sped up by implementing it on a GPU. See this question on security.SE for more information.
You should always add a per-user salt. By using an unique salt for each user, brute-forcing the password of one user will not yield any useful results for any other user. If no such salt were to be implemented, we could build a rainbow table for each password that we tried, and simply look up in the table for other users. A salt should be reasonably random, and sufficiently long. See this question on Stackoverflow for more information.
Checking of password
There are a few things I want to say about the following code.
if($query->rowCount() >= 1) {

->rowCount() is not guaranteed to return the number of rows in the result for select statements as per the documentation, quoted below. A possible safer alternative is count($query->fetch_all()).

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

I do not understand why you check for >= 1 in this code. Only one user/password should ever match. If this is not the case, something very bad happened. Either rowCount returns something that has nothing to do with this select statement, someone tries to get the query to return more information or your data is corrupt somehow. In either case, you want to know about this, not silently log in someone when more than one row is returned.
Misc
Use consistent indentation in your code. Inside your try block you don't indent. Similarly, your nested if-statements are not indented nicely.


Looping through cells and deleting column

This version is about 33 times faster:

Dim oUnion As Range
Dim oCell As Range
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
For Each oCell In Range("D4:DS4")
    If oCell.Value = 0 Then
        If oUnion Is Nothing Then
        Set oUnion = oCell
        Else
        Set oUnion = Union(oCell, oUnion)
        End If
    End If
Next
If Not oUnion Is Nothing Then
    oUnion.EntireColumn.Delete
End If
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

Why is this faster?

Minimize the number of interactions with Excel.

This procedure first gathers a set of all cells that comply with the condition (=0). Then it deletes those cells (columns) in one command, rather than deleting them one at the time. The routine could be made even faster by first reading all values into an array and testing the values of the array in the loop.

For Each loops are faster when you are traversing objects

If you are running through all objects in a collection, a for each loop is generally faster than a counted loop.

Time, time and time again.

If you are optimising code for performance never just assume. Time your code. And time it multiple times too, as other programs (Windows!) might affect your results. It is a good idea to time variants A and B of your routine multiple times in random order. Suspect the result? Time again.


Powershell function to get hash value of a file

I think your code is okay. Some notes:

PowerShell 4 has a Get-FileHash command. Granted, most people don't have PS4 yet.
Why reinvent the wheel when other people have already done it better? E.g.: Boe Prox's Get-FileHash.
I believe the PowerShell Community Extensions also have a file hash command.
The dependency on certutil is not ideal. Do we know that the output format from all versions of certutil will be same everywhere and for all time?
You don't need the echo in the last line. The last line can consist of just $hashstring by itself. Since that value is not being consumed, it will be placed in the pipeline. (It's important, by the way, to understand how the pipeline works to use PowerShell.)


I would suggest using the built-in CursorAdapter together with a SQLiteCursor. You should be able to construct even your more complex query using the SQLiteQueryBuilder.


Public Function to remove empty or "" elements from a single dimension array

Option Explicit

Always nice to see.

Public Function RemoveBlanksFromArray(ByVal TheArray As Variant) As Variant

The usual convention for parameters is camelCase - i.e. theArray. Otherwise looks fine, maybe I'd call it inputArray so it's obvious to the rest of your code what it contains (more on naming).

One thing to watch out for when passing arrays byVal. Arrays are a bit like objects in VBA -you never pass actual objects around, just addresses. Similarly, byVal doesn't make a copy of the actual data in TheArray, just a copy of the pointer to the array's location in memory. With primitive types when you write something like this:

Sub Foo(ByVal bar As Long)

... only a copy of bar is passed, meaning Foo cannot do anything to alter the original variable. However in your code, you could accidentally modify the values in TheArray.

This is one reason why I'd suggest strongly typing the array - as these can only be passed ByRef; in your comparisons you treat the elements like strings:

If myElement <> "" Then

So why not explicitly declare the array as such?

Public Function RemoveBlanksFromStringArray(ByRef theArray() As String) As String()

Now the ByRef is clear, and you'll get a minor performance boost because you don't have to cast to and from Variant

Dim temp As Variant
'[...]
RemoveBlanksFromArray = temp

I tend to name variables that get assigned to the return value of a function result, just personal preference.

ReDim temp(LBound(TheArray) To LBound(TheArray))

Glad to see you've explicitly referenced both bounds, avoiding Option Base 1 or any convention (hint, there isn't one)

Dim myCount As Long

I think this name is misleading. It's not a count really is it, because depending on LBound(TheArray) it might start at 0 or 1 or 7 for all we know. You could name it something like indexOfTempArray, but I think a count is actually more useful and intuitive, so we'll make it one, but maybe more explicit:

Dim countOfNonBlanks As Long

For Each myElement In TheArray

Now there's a small optimisation to be made here; it's marginally quicker to loop over an array by index than with For-Each, so this becomes

Dim index As Long
For index = LBound(TheArray) to UBound(TheArray)
    If TheArray(index) <> "" Then
        '...

Oh and while we're here, prefer vbNullString to "" because the latter could be a non printable character or might have a space in there if you squint etc. vbNullString is unequivocal (Rubberduck would've told you that)

That all brings us to the bottle-neck of your code (I think):

ReDim Preserve temp(LBound(temp) To myCount)
temp(myCount) = myElement
myCount = myCount + 1

Your hunch is right, there's a better way. Arrays in VBA are stored as a continuous pre-allocated bit of memory. (This is why array lookups are so fast, because all you do is look up the address of the first item of the array, and offset by a fixed distance - 1 lookup operation. Collections store the address of every element of the array, so to find an element in memory, you first lookup the address associated with it, then look at that address in memory - 2 lookup operations).

However with VBA Arrays what you gain in speed you lose in flexibility. Because the memory is pre-allocated, you can't just add another element on the end, that memory may be in use for something else. So ReDim Preserve actually copies the entire array to a new (bigger) location in memory. That's slow! Here's where someone told me all that.

Anyway, what this boils down to is; imagine the largest size your temp array could ever be (i.e no blanks found, so the same size as your input array), fill it up partially, then ReDim Preserve it once back down to the actual size it has to be.

Putting all that together we get:

Public Function RemoveBlanksFromStringArray(ByRef inputArray() As String) As String()

    Dim base As Long
    base = LBound(inputArray)

    Dim result() As String
    ReDim result(base To UBound(inputArray))

    Dim countOfNonBlanks As Long
    Dim i As Long
    Dim myElement As String

    For i = base To UBound(inputArray)
        myElement = inputArray(i)
        If myElement <> vbNullString Then
            result(base + countOfNonBlanks) = myElement
            countOfNonBlanks = countOfNonBlanks + 1
        End If
    Next i
    If countOfNonBlanks = 0 Then
        ReDim result(base To base)
    Else
        ReDim Preserve result(base To base + countOfNonBlanks - 1)
    End If

    RemoveBlanksFromStringArray = result

End Function

On a test of 500,000 items

original code took 1.1481±0.0001 s,
refactored code took 0.1157±0.0001 s

or ~ 10 times faster

Addendum

Now I think about it, the original code with copying memory boils down to an \$\mathcal O (n^2)\$ algorithm, the refactored code is \$\mathcal O (n)\$ (here \$ n\$ is the size of the array, \$\mathcal O (n^a)\$ basically means you loop over the array \$ a\$ times). Using Timer for some rough results, you can see this trend:

10,000 elements
  Old 0
  New 0
100,000 elements
  Old 0.046875 (same order of magnitude as each other)
  New 0.015625
1,000,000 elements
  Old 3.171875 (1 order of magnitude slower relative to New)
  New 0.125
10,000,000 elements
  Old 321.46875 (2 orders of magnitude slower)
  New 1.3125

I.e. When you do 10x more elements, OP's O(n^2) code gets 10^2 = 100 times slower, the refactored O(n) gets 10^1 = 10 times slower. Therefore relative to the new code, the old code gets 10x slower.

Interestingly, because both algorithms are doing essentially the same operation (writing to memory), which is an O(1) operation (i.e. independent of the rest of the code), once you operate on large enough arrays, optimising the rest of the code becomes inconsequential (Early vs Late binding, For Each vs Index, re-using LBound vs re-measuring). So once you get the algorithm down to the lowest complexity possible (assuming performance is an issue), then pick whichever method is most readable and maintainable.


Without sample inputs I can't run your whole code.  And I prefer not to guess.

The use of np.matrix suggests it was translated from MATLAB/Octave code.  That array subclass, in numpy, is always 2d, which makes it behave more like MATLAB matrices, especially old versions.  Transpose always has effect; row and column indexing returns 2d matrices; and * is matrix multiplication (as opposed to element wise, the .* of MATLAB).

I'll focus on the scaling function.  I don't see it being used, but it's simple and typical of the other functions.

import numpy as np
<your code>

X = np.arange(12).reshape(3,4)
print(X)
Xm = np.matrix(X)
print(scaling(Xm))

produces:

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[-0.5 -0.5 -0.5 -0.5]
 [ 0.   0.   0.   0. ]
 [ 0.5  0.5  0.5  0.5]]

scaling doesn't work with X an array, because x = X[:, k] would be 1d, which conflicts with the x[:, 0] use.

But I can perform this same operation without row iteration.

def ascaling(X, n=0):
    # array scaling
    ctr = X.mean(axis=n, keepdims=True)
    rge = X.max(axis=n, keepdims=True)-X.min(axis=n, keepdims=True)
    return (X - ctr)/rge
print(ascaling(X,0))
print(ascaling(X,1))

producing

[[-0.5 -0.5 -0.5 -0.5]
 [ 0.   0.   0.   0. ]
 [ 0.5  0.5  0.5  0.5]]
[[-0.5        -0.16666667  0.16666667  0.5       ]
 [-0.5        -0.16666667  0.16666667  0.5       ]
 [-0.5        -0.16666667  0.16666667  0.5       ]]

In this case, the equivalent code, assumng X is np.matrix is simpler

def mscaling(X, n=0):
    # matrix scaling
    ctr = X.mean(axis=n)
    rge = X.max(axis=n)-X.min(axis=n)
    return (X - ctr)/rge

print(mscaling(Xm,0))
print(mscaling(Xm,1))

Maybe this example will make these operations clear:

Make a small 2d array:

In [861]: X=np.arange(6).reshape(2,3)
In [862]: X
Out[862]:
array([[0, 1, 2],
       [3, 4, 5]])

Sum rows, resulting in a 1d array of length 3 (the columns)

In [863]: X.sum(axis=0)
Out[863]: array([3, 5, 7])

Sum columns - again a 1d result

In [864]: X.sum(axis=1)
Out[864]: array([ 3, 12])

But if I add keepdims, the result is 2d, (2,1) shape:

In [866]: X.sum(axis=1,keepdims=True)
Out[866]:
array([[ 3],
       [12]])

sum applied to matrix does the same thing.

In [867]: np.matrix(X).sum(axis=1)
Out[867]:
matrix([[ 3],
        [12]])

The nice thing about keeping dims is that I can do math like

In [868]: X-X.sum(axis=1,keepdims=True)
Out[868]:
array([[-3, -2, -1],
       [-9, -8, -7]])

Without keepdims I'd have to do X-X.sum(axis=1)[:,None].

Your frequent use of transpose suggests that the mix of dimensions haven't been fully thought out.  MATLAB code does use x' or x.' quite a bit.  On the other hand beginner numpy coders try to apply transpose to 1d arrays, and wonder why nothing happens.


Implementing ShowDialog() style functionality without disabling any other windows

Using ManualResetEvent this way means that you're blocking a thread unnecessarily while the dialog is shown. Instead, you should use TaskCompletionSource, which allows you to create a Task that completes when you want it to.

Encapsulated into a method, the code could look something like this:

public static Task<bool> ShowAsync()
{
    var tcs = new TaskCompletionSource<bool>();
    var dialog = new DialogWindow(tcs.SetResult);
    dialog.Show();
    return tcs.Task;
}


I suggest to check around TSync as it inherits from TInterfacedObject, which is reference counted, a typical source of memory leak.


Strange loop initialization

Hm, what's up with this loop initialization?

  for (int i = i; i < 12000028; i++) {

i is not even defined at this point. Write it the non-confusing way:

  for (int i = 0; i < 12000028; i++) {

Magic number 12000028

The number 12000028 and 12000028 + 1 and 12000028 + 15 appears in multiple places in the code. It would be better to #define and reuse.

#define BMP_SIZE 12000028

char bmp[BMP_SIZE]; // Need 12000028 bits, 1 pixel is 3
// ...

int main() {

    // ...

    for (int i = 26; i < BMP_SIZE; i++) {
        bmp[i] = fgetc(fp);
    }

    // ...

    for (int i = 0; i < BMP_SIZE; i++) {
        fputc(bmp[i], fp);
    }

    // ...
}

Error checking

You checked nicely the result of opening the input file file.wav.
But then, why didn't you do the same for the output file file.bmp?

Use puts instead of printf when possible

When you print plain text ending with newline and you don't need to print variables, then puts is better than printf.
So instead of:

printf("Error opening 'file.wav'\n");

This is slightly better:

puts("Error opening 'file.wav'");

Usability

The input and output filenames are hardcoded.
That makes this difficult to use.
It would be great to take them as command line arguments

Suggested implementation

Applying the above suggestions:

#include <stdio.h>
#define BMP_SIZE 12000028

char bmp[BMP_SIZE]; // Need 12000028 bytes, 1 pixel is 3
// bits and table is 28 (1500^2 * 3 + 28)

int main(int argc, char ** argv) {

    bmp[0]  = 0x42;   // Bitmap signature
    bmp[1]  = 0x4D;   // 'BM'

    bmp[2]  = 0x1C;   //
    bmp[3]  = 0x1B;   // Size of bitmap
    bmp[4]  = 0xB7;   // in bytes
    bmp[5]  = 0x00;   //

    bmp[10] = 0x1A;   // Image data location

    bmp[14] = 0x0C;   // Size of header

    bmp[18] = 0xDC;   //
    bmp[19] = 0x05;   // Dimensions of image
    bmp[20] = 0xDC;   // 1500 * 1500
    bmp[21] = 0x05;   //

    bmp[22] = 0x01;   // Something
    bmp[24] = 0x18;   // standard (?)

    if (argc != 3) {
        printf("usage: %s input.wav output.bmp\n", argv[0]);
        return 2;
    }
    char * input = argv[1];
    char * output = argv[2];

    FILE *fp;
    fp = fopen(input, "rb");
    if (fp == NULL) {
        printf("Error opening %s for reading", input);
        return 1;
    }
    for (int i = 26; i < BMP_SIZE; i++) {
        bmp[i] = fgetc(fp);
    }
    fclose(fp);

    fp = fopen(output, "w+");
    if (fp == NULL) {
        printf("Error opening %s for writing", output);
        return 1;
    }
    for (int i = 0; i < BMP_SIZE; i++) {
        fputc(bmp[i], fp);
    }
    fclose(fp);

    return 0;
}


Review

No need for all these intermediate temp variables

You loop over a and b to append to the result which is unnecessary.

Only afterwards you create the products but this can be done before.
The sort is not needed if you keep a running minimum
Use a if __name__ == '__main__'
Consider adding Docstring and Testcases, (or both in the form of doctests) to make the solution more understandable/testable
Read PEP8 the python style guide

Functions and variables should be snake_case for instance

Revised Code

def optimal_shipping(a, b, target):
    """
    Finds the optimal shipping by compairing pairwise lists to the target sum

    >>> optimal_shipping([[1,2000],[2,4000],[3,6000]], [[1,2000]], 6000)
    [[2, 1]]
    >>> optimal_shipping([[1,8],[2,7],[3,14]], [[1,5],[2,10],[3,14]], 20)
    [[2, 3]]
    >>> optimal_shipping([[1,3000],[2,5000],[3,7000],[4,10000]], [[1,2000],[2,3000],[3,4000],[4,5000]], 10000)
    [[2, 4], [3, 2]]
    """
    best = 0
    for i, x in a:
        for j, y in b:
            if abs(x + y - target) < abs(target - best):
                best = x + y
                res = [[i, j]]
            elif x + y == best:
                res += [[i, j]]
    return res

if __name__ == '__main__':
    import doctest
    doctest.testmod()

Note
If those lists prices are in ascending order, maybe something with a bisect search could work.