use std::io;

fn main() {
    println!("Enter Temperature as 56f or 98c");

    let mut usr_inpt = String::new();

    io::stdin()
        .read_line(&mut usr_inpt)
        .expect("can not read user input");

I like that you’re using expect here instead of unwrap.
It allows for a much nicer user experience when things go sideways.
If I was nitpicking, I’d remind you to use proper capitalization and punctuation.

    let usr_inpt = usr_inpt.trim_end().to_lowercase();

    if usr_inpt.ends_with("f") || usr_inpt.ends_with("c") {
        // remove the last indication 56f -> 56 or 56c -> 56
        let _temp: String = usr_inpt.chars().take(usr_inpt.len() - 1).collect();

temp is rarely a good name.
If you meant temperature instead of temporary, it would be good to spell it out.

        let num: u32 = match _temp.parse() {
            Ok(num) => num,
            Err(_) => 0,
        };

Is it really the right thing to return zero in the error case?
I would expect the error case here to be caused by invalid user input (or a bug in your previous parsing logic maybe).
It would probably be best to alert the user to this failure instead of the slightly enigmatic result of 0.

        if usr_inpt.ends_with("f") {
            println!("celcius -> {}", (num - 32) * 5 / 9);
        } else if usr_inpt.ends_with("c") {
            println!("farenheit -> {}", num * 9 / 5 + 32);
        }

It smells a little funny that we’re making the same checks again as we did above. If you extracted the parsing logic into a function, you could just call it for each case. I would probably also extract proper fahrenheit_to_celcius and celcius_to_fahrenheit functions.

    } else {
        println!("invalid input");
    }
}

Error messages should be printed to stderr.
Use the eprintln macro instead.

———————

All in all it’s pretty good for a first go.
I would take a look at using some types for Fahrenheit and Celsius though. Your parse method could return a Temperature that contains either a Celsius or Fahrenheit measurement.

I’ve not run this through the compiler, but hopefully it illustrates the idea.

struct Celsius { value: u32 }
impl Celsius {
    fn to_farhenheit(&self) -> Farhenheit {
        Fahrenheit { value: self.value * 9 / 5 + 32 }
    }
}

struct Fahrenheit { value: u32 }
impl Fahrenheit {
    fn to_celsius(&self) -> Celsius {
        Celsius { value: ( self.value  - 32) * 5 / 9 }
    }
}

enum Temperature {
    Fahrenheit(Fahrenheit),
    Celsius(Celsius)
    Err(String)
}

fn parse_input(input: &str) -> Temperature {
    if input.ends_with("f") {
        Fahrenheit { value: parse_num(input) }
    } else if input.ends_with(“c”) {
        Celsius { value: parse_num(input) }
    } else {
        Err(“Input invalid. Must end with ‘c’ or ‘f’.”)
    }
}

fn parse_num(input: &str) -> u32 {
    let temperature: String = usr_inpt.chars().take(usr_inpt.len() - 1).collect();

    match temperature.parse() {
        Ok(num) => num,
        Err(_) => 0,
    };
}

Then we tie it all together in main.

fn main() {
    println!("Enter Temperature as 56f or 98c");

    let mut usr_inpt = String::new();

    io::stdin()
        .read_line(&mut usr_inpt)
        .expect("can not read user input");

    let temperature = parse_input(usr_inpt.trim_end().to_lowercase());

    match temperature {
        Temperature::Celsius { celsius } => println!("celcius -> {}", celcius.to_fahrenheit()),
        Temperature::Fahrenheit { fahrenheit } => println!(“fahrenheit -> {}”, fahrenheit.to_celsius()),
        Err(reason) => eprintln!(reason)
    }
}

While it’s certainly more code, it raises the level of abstraction in your main function quite a bit.

Greet user
Get input
Parse input
Write out results

This also provides the opportunity (left as an exercise for the reader) to propagate errors from parse_num all the way back up to the user, rather than silently returning an invalid result.


Converting UK drams to ounces and pounds in PHP

There are two things that stand out to me in your code. The first is that your integer cast seems a bit premature. When creating a general function like this, you probably do not want to round the answer, since 1.5 oz is a perfectly valid weight. A user of your function can then cast the resulting values if this is required.

The second is that your conversion values are magic numbers. These should be in constants with names that express the meaning of the number.

A class would be perfect to store the logic and constants. A Weight class would probably be a well-suited name. An Weight object can then hold the amount of weight in one specific unit and provide public methods to retrieve the weight in other units.

The Weight class that I have created here provides three static "Builder/Factory" methods to create a Weight object from. The constructor has been made private to support the use of the more expressive static function. The reasoning behind this, is that $weight = Weight::fromDrams(16); is a lot easier to understand than $weight = new Weight(16);.

Furthermore, the class provides the three public methods to retrieve the given weight for a specific unit.

class Weight {
    const POUNDS_TO_OUNZES = 16;
    const OUNZES_TO_DRAMS = 16;

    /**
     * @var float
     */
    private $drams;

    public static function fromPounds ($pounds) {
        return self::fromOunzes($pounds * self::POUNDS_TO_OUNZES);
    }

    public static function fromOunzes ($ounzes) {
        return self::fromDrams($ounzes * self::OUNZES_TO_DRAMS);
    }

    public static function fromDrams ($drams) {
        return new static($drams);
    }

    private function __construct ($drams) {
        $this->drams = $drams;
    }

    public function inPounds () {
        return $this->inOunzes() / self::POUNDS_TO_OUNZES;
    }

    public function inOunzes () {
        return $this->inDrams() / self::OUNZES_TO_DRAMS;
    }

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

If you still require a very specific function that returns an array of 'lbs', 'oz' and 'dr' like your question says, than this Weight class can be used in conjunction with it as such:

function fromDrams ($drams) {
    $weight = Weight::fromDrams($drams));

    return [
        'lbs' => (int) $weight->inPounds(),
        'oz' => (int) $weight->inOunzes(),
        'dr' => (int) $weight->inDrams(),
    ];
}

Here you see the Weight class not performing any rounding itself and letting the user of the class perform these when required.

This Weight class is now much more versatile than your original piece of code and can be used in many other situations. For example a website that provides conversion of an amount of weight for a specific unit to the respective weights for the other three units.

if (!empty($_POST["amount_in_drams"]))
    $weight = Weight::fromDrams($_POST["amount_in_drams"]);

if (!empty($_POST["amount_in_ounzes"]))
    $weight = Weight::fromOunzes($_POST["amount_in_ounzes"]);

if (!empty($_POST["amount_in_pounds"]))
    $weight = Weight::fromPounds($_POST["amount_in_pounds"]);

echo $weight->getPounds() . " pounds, ";
echo $weight->getOunzes() . " ounzes or ";
echo $weight->getDrams() . " drams.";


Selecting elements from the DOM of a page

Don't implicitly create global variables for (i = 0; uses a global i. Always declare variables before using them - in modern times, declare them with let or const, not var (which has too many problems, such as an unintuitive function scope rather than block scope, to be worth using nowadays)
Iterators Or, even better, rather than iterating manually, invoke the NodeList's iterator, and use for..of instead, eg:
for (const b of bs) {
  // do stuff with each <b> element
}

querySelector If you only want to select one element matching a selector, don't use querySelectorAll followed by [0] index lookup - use querySelector instead.
try/catch In predictable, synchronous code, there shouldn't be any need for try/catch. If you aren't sure whether an element exists, just test it first, instead of possibly throwing an error.
textContent Use textContent rather than innerHTML - textContent is faster and more appropriate when you aren't deliberately retrieving HTML markup. Also, .innerHTML gives you difficult HTML entities, as you can see with your Kleinberg &amp; Tardos, instead of Kleinberg & Tardos
Try something like this instead:
const bs = document.querySelectorAll("div.post-body.entry-content div h3 b");
for (const b of bs) {
  const child = b.querySelector('u, a');
  if (child) {
    console.log(child.textContent);
  }
}


Try using a Promise library like bluebird. it will save you from callback hell and allow you to write your code synchronously.

let Promise = require('bluebird'),
    fs = Promise.promisifyAll(require('fs'))

function readAllFilesInDir(pathArr) {
    // assume i get all files path as array here
    let allPromises = pathArr.forEach(function (path) {
        return fs.readFileAsync(path, 'utf8')
    })

    return allPromises
}

function doYourThing() {
    // body...
}
readAllFilesInDir(pathArr)
.then(doYourThing)


Often it is the case that reformatting the data leads to insights. Let's take a look at the test case:

A: 1 2 3 4 5
B: 5 4 3 2 1

Now let's suppose that we subtract the smaller of each pair from both, and take the sum of the smallers:

A: 0 0 0 2 4
B: 4 2 0 0 0

If we can find the maximum tips available in this problem, the real result will be that amount plus 1 + 2 + 3 + 2 + 1.

Can you now see how to solve the problem more easily?

Unfortunately it appears that the tags are misleading; dynamic programming does not buy you much, but a greedy algorithm does.

  Your greedy algorithm works out for that test-case. I'm not sure if it works in general. Could you expand a bit on the intuition?

First off, it should be clear that we can always reduce the problem to one where the columns are of this form where one or both are zero; "subtract the smaller from both" always works.

So the problem now is: we must choose up to X numbers from row A, and up to Y numbers from row B, such that their sum is maximized.

The proposed algorithm is: always take the largest number remaining. Suppose we have:

A: 0 0 2 1 5  -- choose up to 2
B: 4 2 0 0 0  -- choose up to 4

We now have to make assignments, and we do it in order from highest to lowest benefit. Start with the biggest bang:

           A
A: 0 0 2 1 5
B: 4 2 0 0 0

Then the next:

   B       A
A: 0 0 2 1 5
B: 4 2 0 0 0

Now we have a tie, so pick both:

   B B A   A
A: 0 0 2 1 5
B: 4 2 0 0 0

And now we've exhausted A, which leaves

   B B A B A
A: 0 0 2 1 5
B: 4 2 0 0 0

What's the intuition that the greedy algorithm works?  Examine the first choice. If, say, we gave Bob the 5/0 delivery and take the zero tip, what does that get us? It only gives Andy the opportunity to make the lower-valued "1/0" delivery later on, which is not a win; we've given up five to gain one.


Calculating a base price with surcharge conditions

Each condition is a function. It might be that you could write it more concisely, but I think the code is clearer if you do this:

def priceFunction(cond: => Boolean)(mod: Double => Double) = (_: Double) match {
    case x if cond => mod(x)
    case y => y
}

val modRuntime = priceFunction(runtime > 120)(_ + 1.5)
val modWeekend = priceFunction(day == Sat || day == Sun)(_ + 1.5)
val modParquet = priceFunction(!isParquet)(_ + 2.0)
val mod3d = priceFunction(is3D)(_ + 3.0)
val modifiers = List(
    modRuntime,
    modWeekend,
    modParquet,
    mod3d
)
val modifierFunction = modifiers reduceLeft (_ andThen _)

val basePrice = modifierFunction(0.0)

The name of the identifiers here suck, and I could have written val modifiers = modRuntime andThen modWeekend andThen modParquet andThen mod3d without trouble. I choose putting them in a List because it shows how well it can scale.

One could also make PartialFunction and chain them with orElse, for the cases where you want only the first condition.

You see this kind of thing used in web frameworks, such as BlueEyes, Lift or Unfiltered, for example.


Given a list of words, remove the shorter word of every pair

Asking for forgiveness would be the best policy for dealing with errors that may be beyond your control, such as when opening a file for reading.  Checking beforehand is useless, because too many things could go wrong: the file might not exist, you might not have the right permissions, the disk could fail altogether, etc.  Furthermore, even if you did check beforehand, circumstances could change during the brief period between your check and the real operation.  Therefore, the only reasonable approach would be to just do it, and deal with any errors that come up.

When working with a list of words, however, the outcome is entirely deterministic.  Since it is entirely possible to write your code such that it never triggers an error, that's what you should aim for.  (Well, maybe the program is multithreaded, and some other thread is manipulating the ArrayList behind your back, but that would be your program's fault, and such errors are also preventable with proper engineering.)

Therefore, your first approach is better.  However, the list.size() != 0 check is a superfluous check, and list.size() >> 0 is a pointless shift.

Personally, I find the indexing confusing, because the list is being modified as you traverse it, and the termination condition (list.size() >> 1) - isOdd is a moving target.  Consider working backwards, so that each pair you consider is always in "virgin" territory.

public static void removeShorterStrings(ArrayList<String> list) {
    for (int i = (list.size() & ~1) - 2; i >= 0; i -= 2) {
        String first = list.get(i);
        String second = list.get(i + 1);
        if (first.length() <= second.length()) {
            list.remove(i);
        } else {
            list.remove(i + 1);
        }
    }
}


Towards optimization and restructuring

One of downsides of the initial revrot approach is that all nested functions test, reverse and rotate will be redundantly recreated on each revrot call.Instead - define them as top-level functions with meaningful names.

Next, the program lacks 2 edge cases:

when input string contains one single digit and size of required chunk is also 1 (ex. revrot("3", 1)). It's worth to catch that case immediately and return the unchanged input string
when input string contains non-digit character

The intermediate arr array with for loop and slice calls (to get all chunks) is replaced with convenient String.match call on dynamic regex pattern new RegExp(`.{${size}}`, 'g') (matches substrings of specific length/size)

The final optimized approach:

const testCubes = s => Array.prototype.reduce.call(s, (acc, val) => acc + Number(val) ** 3, 0) % 2 === 0;
const strReverse = s => [...s].reverse().join("");
const rotateLeft = s => s.slice(1) + s.slice(0, 1);

function revrot(str, size) {
    let len = str.length;
    if (size < 1 || !str || size > len) return "";
    if (len === 1 && size === 1) return str;
    if (/\D/.test(str)) {
        throw Error("Invalid numeric string");
    }
    let pat = new RegExp(`.{${size}}`, 'g');
    return str.match(pat).map(x =>
        testCubes(x) ? strReverse(x) : rotateLeft(x)
    ).join("");
}

console.log(revrot("123456987654", 6));
console.log(revrot("123456987653", 6));
console.log(revrot("66443875", 8));
console.log(revrot("563000655734469485", 4));
console.log(revrot("1", 1));
console.log(revrot("6644-d3875", 8));


Firstly I'd simplify your maths:

$$
\text{font_size} = \text{width} * (\frac{\sqrt{\text{length}}}{\text{length}}) ^ {1.6}\\
(\frac{\sqrt{x}}{x})^{1.6} = \frac{1}{x^{0.8}}\\
\text{font_size} = \frac{\text{width}}{\text{length}^{0.8}}
$$

After this we're left with your if, personally I think using min would be better here, min(font_size, height * 0.9).
That way we know the maximum is \$\text{height} * 0.9\$ rather than \$\text{height}\$, and makes the font_size not jump.
This is up to you, but a jump in the font size is ugly in my opinion.

If we look at the affect of not using min and using min:

>>> balanced_text_size_button(1, 89, 100)
89
>>> balanced_text_size_button(1, 91, 100)
91
>>> balanced_text_size_button(1, 100, 100)
100
>>> balanced_text_size_button(1, 101, 100)
90
>>> balanced_text_size_button_min(1, 89, 100)
89
>>> balanced_text_size_button_min(1, 91, 100)
90
>>> balanced_text_size_button_min(1, 100, 100)
90
>>> balanced_text_size_button_min(1, 101, 100)
90

The above makes much more sense.
And so I'd change your function to:

def balanced_text_size_button(length, width, height):
    return int(min(width / math.pow(length, 0.8), height * 0.9))

And if you want to keep your description I'd use comments.
I wouldn't use a doc-string as the implementation details aren't needed by the end user.
I'd either use a heavy comment like you did:

def balanced_text_size_button(length, width, height):
    # Decide the font size by getting a desired with and height font size.
    # For text to not go out of the box, the smallest of the two wanted sizes is taken.
    # The width size is found by dividing the width by an exponential of the text.
    # An exponent is used to have a reduced affect on larger values.
    # The exponent 0.8 seems to give the best results.
    # The height is decided by picking a font size of 90% of it.
    return int(min(width / math.pow(length, 0.8), height * 0.9))

Or as the code is easy to understand, you can just say why you're using a magic variable.

def balanced_text_size_button(length, width, height):
    # The exponent 0.8 seems to give the best results.
    return int(min(width / math.pow(length, 0.8), height * 0.9))


I have had the same thought when implementing localisation in WPF, and came to the conclusion that .resx files are fine. I came to that conclusion because alternatives quickly became more complicated than I could be bothered with, and a RESX-based solution works for me.

So, in my various View.xaml files, I use bindings like this;

<MenuItem Name="Exit" Header="{x:Static Resources:Strings.MENU_HEADER_EXIT}" />

Changing languages is simply a matter of creating language-specific versions of the RESX entries. (http://msdn.microsoft.com/en-us/library/vstudio/aa992030%28v=vs.100%29.aspx).

Now in regards to your actual question; I do not think this sort of data belongs in a ViewModel. There is no 'modelling' going on with these strings; they are just label text, and as such are view-only data. If we follow your above suggestion to an overzealous conclusion, we might as well add ViewModel properties (and Bindings) like;

Font InterferingProcessesFont { get { return FontFamily.Arial; }
Color InterferingProcessesFontColor { get { return Color.Black; }
FontStyle InterferingProcessesFontStyle { get { return FontStyle.Normal; }
.
etc.
.

For my mind, localised labels like this are fixed display settings that will not change for the life of an application, and in most cases, will never change for a particular user. Why clutter a ViewModel with static text?


Use consistent indentation.
You switch from extremely verbose all lower case variable names like numoftrainingdata to single letter capitalized variable names like A. Make your variable names descriptive and no longer than necessary, and be consistent.
Use consistent white space between operators.
knn() doesn't need the second column of test_data, and the calling function doesn't need the first column of test_data.

Rather than calling the function like this:

test_data = knn(test_data,tr_data,k);

Call it like this:

test_data(:,2) = knn(test_data(1,:),tr_data,k);

Do you want to handle certain error conditions like 0 >= k or k > size(tr_data,1)?
Rather than squaring the distance, you can use abs().
Remove the ascend parameter from sort(), that is the default mode.
knearestdistances is unused.
You call mode() a second time rather than using M.

Simplify:

[dist position] = sort(euclideandistance,'ascend');
knearestneighbors = position(1:k);
knearestdistances = dist(1:k);
for i=1:k
    A(i) = tr_data(knearestneighbors(i),2);
end
M = mode(A);
if (M~=1)
    test_data(sample,2) = mode(A);
else
    test_data(sample,2) = tr_data(knearestneighbors(1),2);
end

to

[~,position] = sort(euclideandistance);
A = tr_data(position(1:k),2);
M = mode(A);
if (M~=1)
    test_data(sample,2) = M;
else
    test_data(sample,2) = tr_data(position(1),2);
end

After applying the above suggestions and vectorizing the function you could write it as:

function out_data = knn(test_data,tr_data,k)
    test_data_n = size(test_data,1);
    tr_data_n = size(tr_data,1);

    % absolute distance between all test and training data
    dist = abs(repmat(test_data,1,tr_data_n) - repmat(tr_data(:,1)',test_data_n,1));

    % indicies of nearest neighbors
    [~,nearest] = sort(dist,2);
    % k nearest
    nearest = nearest(:,1:k);

    % mode of k nearest
    val = reshape(tr_data(nearest,2),[],k);
    out_data = mode(val,2);
    % if mode is 1, output nearest instead
    out_data(out_data==1) = val(out_data==1,1);
end

Edit

Regarding correctness, i'm not sure why you check to see if the mode is 1. There is nothing unique about a mode of 1 in general.


Bug because of subshell

You are losing the value of ret_val in a subshell here:

... || (echo "ERROR: Missing required ${each_func}"; ret_val=1)

Variable assignments in a subshell are local to the subshell, so the variable in your function won't change. Instead of a subshell, you just want to group these commands using { ...; } like this:

... || { echo "ERROR: Missing required ${each_func}"; ret_val=1; }

Unnecessary variable

You don't need the req_func variable. The top of your function could have been written simpler like this:

autoload_functions()
{
    local ret_val=0

    ## check first parameter. If it's a directory, then
    ## it is where functions should be loaded from
    local new_libdir=$1
    [[ -d $new_libdir ]] && {
      shift
      LIB_DIR=$new_libdir
    }

    ## iterate through all arguments, set $ret_val to 1
    ## if any required function cannot be autoloaded
    for each_func; do
        # ...

Prefer $(...)

The `...` form for command substitution is deprecated, use $(...) instead:

func_name=$(basename $each_func)

Quoting variables with paths

This line will not work if LIB_DIR contains spaces:

type $func_name &> /dev/null || source $LIB_DIR/${each_func}.bash.inc

This would be safer:

type $func_name &> /dev/null || source "$LIB_DIR"/${each_func}.bash.inc

Though this is probably a bit paranoid.

The same goes for $func_name and ${each_func} too,
but that would seem even more paranoid.
(Who in his right mind would create bash scripts with spaces in the name?)

Naming

The names you chose for some variables are not great. I'd recommend these alternatives:

Instead of each_func: func_path or func_relpath (as in relative path from LIB_DIR)
Instead of ret_val: exit_code, because you may exit with this


Your implementation is taking .then(a, b) and mapping it to .then(a).catch(b) which is not exactly the same thing.  An exception or return of a rejected promise in a in your implementation will hit the .catch(b), but in .then(a, b), it will not hit b, so I think your .spread() is not correctly imitating the .then() behavior in some circumstances.

Here's my implementation that should more closely mimic .then(a, b):

Promise.prototype.spread = function(a, b) {

    function doSpread(fn) {
        return function(args) {
            if (typeof fn === "function") {
                if (Array.isArray(args)) {
                    return fn.apply(null, args);
                } else {
                    return fn(args);
                }
            } else {
                return args;
            }
        }
    }
    if (typeof b !== "undefined") {
        // there is a reject handler
        return this.then(doSpread(a), doSpread(b));
    } else {
        // no reject handler
        return this.then(doSpread(a));
    }
}

// Array.isArray polyfill
if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

Working demo and tests: https://jsfiddle.net/jfriend00/nqc0h10y/

And, here's a version that makes the change to wait on any promises that are returned in the array of values per our discussion in comments. I also changed it so that if you don't pass a function to .spread(), it will reject:

Promise.prototype.spread = function(a, b) {

    function doSpread(fn) {
        return function(args) {
            if (typeof fn === "function") {
                if (Array.isArray(args)) {
                    // in cases where there could be promises in the array, wait on those
                    return Promise.all(args).then(function(returnArgs) {
                        // split the array of results into separately passed arguments
                        return fn.apply(null, returnArgs);
                    });
                } else {
                    return fn(args);
                }
            } else {
                throw new Error("Must pass a function to .spread()");
            }
        }
    }
    if (typeof b !== "undefined") {
        // there is a reject handler
        return this.then(doSpread(a), doSpread(b));
    } else {
        // no reject handler
        return this.then(doSpread(a));
    }
}

// Array.isArray polyfill
if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

Working demo: https://jsfiddle.net/jfriend00/om5auzs0/


Script for saving top wallpapers from wallbase.cc into a directory

Your code is nice, well documented, properly formatted and easy to understand so I won't have to much to say.

You can have a read at PEP 8 as your code is not exactly perfect for details like spacing (you should have whitespaces after : in your dicts, you shouldn't have trailing whitespaces at the end of the line, etc). You'll find cool tools to check stuff for you automatically : pep8, pylint, pyflakes, pychecker.
In save_pic, there is no way to_save != "" can be false. Indeed, because of the way you build to_save, I know for sure that it will contain a "." making it a non-empty string. If you want to be sure that the property keeps being True, you can use assert like this : assert to_save != "". Otherwise, you can just get rid of the test.
The fact that you are calling str() on file_ext in save_pic is a bit confusing : if this wasn't to behave like a string in the first place, I assume to_save = (save_path + hs + "." + file_ext) would fail.
save_pic as a function probably shouldn't rely on sys.argv[1] : I think it would be much better if this information was to be provided as a parameter. Also, to join filename, you can use os.path.join().
in save_pic (again), I think you should store the value of hs + "." + file_ext in a variable instead of repeating this in 3 different places. Also, you do not need parenthesis when assigning to to_save.
in get_pic, you could use list comprehension to define page_urls : page_urls = [r['href'] for r in soup.findAll("a") if "http://wallbase.cc/wallpaper/" in r['href']].


How can I improve this Node.js file's routing?

Whether you wanna implement a static server?
If so, you can just use connect and its built-in static middlewave. With it, you just need to write the following code to implement a static server:

var connect = require("connect");

connect(
    connect.static(__dirname)
).listen(3000);

That's it.


overload c++ enum class operators and enable check value set

A few things that might be improved:

Use static_cast<type>(value) instead of (type)(value).
I'm missing an bool operator!(const x lhs).
You could also define operator&& and operator||.
You can make enum_value const.


Could the fold approach have worked? If so, how?

intersperse' i = foldr (\x ys -> x : if null ys then [] else i : ys) []

In the fold, we cannot access the rest of the input, only the rest of the output. However, if and only if the input was empty, the output will be empty. So null ys happens to works here.

Interesting aspects:

I changed the argument order to match the standard intersperse. This happens to work better with the foldr-based definition. More importantely, I feel that intersperse is more often partially applied with an element than with a list, so the element should go first.
I use foldr instead of foldl to increase laziness and avoid the accumulator construction. Note how I don't need acc ++ [x] because I only add elements to the front of lists.
I make sure that intersperse' produces the first (:) cell before the null check.


There is just one thing wrong with your code.
Don't ever call std::swap using a qualified name. Doing so cuts out user-defined functions which might be better, or actually viable. Use using std::swap; swap(*pa, *pb); or maybe std::iter_swap(pa, pb);.
Next, there's on thing sub-optimal. You are passing the range, as well as start and end. Knowing where in the overall range the part you are currently processing is does not help, so you can eliminate an argument.
Work on genericity by following C++ conventions.
Useing half-open iterator-ranges allows wider application, you only need mutable forward-iterators.
Finally, Don't use <= for comparing the elements. All the standard algorithms only use <, and there's no compelling reason to break with that convention.

template <class ForwardIter>
void quicksort(const ForwardIter begin, const ForwardIter end) {
    if (begin == end) return;
    auto cur = begin;
    if (++cur == end) return;
    auto mid = begin;
    for (; cur != end; ++cur)
        if (*cur < *begin)
            std::iter_swap(cur, ++mid);
    std::iter_swap(begin, mid);
    quicksort(begin, mid);
    quicksort(++mid, end);
}


Implement a function to check if a tree is balanced

First off, I would use something other than a LinkedList to hold the children of an n-ary tree. A LinkedList requires you to enumerate the list in order to get the reference to any child other than the leftmost, which is going to slow you down.

Second, your code is basically returning false in any situation where the Node's parent has one child that itself doesn't have any children. In your example tree, that's the exact case (you have two children of the root, one of which has another child) but the tree is balanced according to the rules, so I would expect this algorithm to return a lot of false positives (and negatives).

Finding the depth of an n-ary tree is a linear-bound operation; you traverse each branch of the tree recursively, finding the depth at each leaf node. You can find both the maximum and minimum depth in one traversal; at each level, ask each branch for its maximum and minimum depth, passing the depth of the current node. The base case is that of a leaf node (no children); the min and max is the depth of that leaf. You can store this result in a Tuple or in a more specialized MinMax struct, as you please. With those results returned to the calling level, scan them to find the lowest Min and the greatest Max, and return that to the caller.

Here's a basic implementation:

public class MinMax<T>
{
    private T minVal;
    private T maxVal;

    public MinMax(T min, T max)
    {
       minVal = min;
       maxVal = max;
    }

    public T min() {return minVal;}
    public T max() {return maxVal;}
}

private MinMax<Integer> GetMinMaxDepth(Node node, int currDepth)
{
    //base case; no children. Max and min depth at this leaf is currDepth.
    if(node.children == null || node.children.size() == 0)
       return new MinMax<Integer>(currDepth, currDepth);

    //determine the maximum and minimum depth of all child branches,
    //and track the absolute max and min across all of them.
    int min = Integer.MAX_VALUE, max = -1;
    for(Node nextNode : node.children)
    {
        MinMax<Integer> childDepth = GetMinMaxDepth(nextNode, currDepth+1);
        if(childDepth.min() < min) min = childDepth.min();
        if(childDepth.max() > max) max = childDepth.max();
    }

    return new MinMax<Integer>(min, max);
}

boolean isBalanced()
{
    //easy cases; a tree with 0 or 1 elements.
    if(treeRoot == null || treeRoot.children == null || treeRoot.children.size() == 0)
       return true;
    //traverse the tree and find the minimum and maximum depth.
    MinMax<Integer> minMaxDepth = GetMinMaxDepth(treeRoot, 0);

    return minMaxDepth.max() - minMaxDepth.min() > 1;
}

This could probably be optimized in our case to return early if we discover that any node's child depths differ by more than 1. We could hack it by throwing an Exception, but the proper strategy is almost as easy to implement:

private MinMax<Integer> GetMinMaxDepth(Node node, int currDepth)
{
    //base case; no children. max and min depth at this leaf is currDepth.
    if(node.children == null || node.children.size() == 0)
       return new MinMax<Integer>(currDepth, currDepth);

    //determine the maximum and minimum depth of all child branches,
    //and track the absolute max and absolute minimum.
    int min = Integer.MIN_VALUE, max = -1;
    for(Node nextNode : node.children)
    {
        MinMax<Integer> childDepth = GetMinMaxDepth(nextNode, currDepth+1);
        //Exit now if child is unbalanced
        if(childDepth.max() - childDepth.min() > 1) return childDepth;
        if(childDepth.min() < min) min = childDepth.min();
        if(childDepth.max() > max) max = childDepth.max();
        //Exit now if current node is unbalanced
        if(max-min > 1) break;
    }

    return new MinMax<Integer>(min, max);
}

The upside is that we quit as soon as we know the answer to the question (is the tree unbalanced?), which will increase the average performance (but not the worst-case performance on a tree that is balanced or is unbalanced at its furthest extremities). The downside is that we no longer know how unbalanced the tree is; the MaxMin returned to the top level will always have a Max and Min that differ by the first detected difference greater than the threshold (probably 2), not the absolute difference in depth of leaf nodes in the tree.

The one case that is difficult to determine in an n-ary tree is that of a tree that never forks. This algorithm will find a depth difference between any two or more branches, but when there is only one branch, the maximum and minimum depths of the tree are the same and there's nothing to use for comparison. Technically, it would have only one "leaf" node (usually defined as a node with no children) and so by the given definition all (one) of the leaves are the same distance from the root, however if you looked at the map of an N-ary tree that was more like a linked list (or even a V or Y shape) and went deeper than two levels, you wouldn't call it balanced.

Perhaps a change in definition may be required; a node is a "leaf" node if it does not have N child nodes (where N is the order of the N-ary tree). So, in a quaternary tree (4 children per node), if any node has fewer than 4 children, then the depth of the current node is considered as a "minimum" depth and will almost certainly be the minimum depth at that level. That's another easy change:

private MinMax<Integer> GetMinMaxDepth(Node node, int currDepth)
{
    //base case; no children. max and min depth at this leaf is currDepth.
    if(node.children == null || node.children.size() == 0)
       return new MinMax<Integer>(currDepth, currDepth);

    //determine the maximum and minimum depth of all child branches,
    //and track the absolute max and absolute minimum.
    //Exit as soon as we know that this or any child node is unbalanced.
    int min = Integer.MIN_VALUE, max = -1;

    //If this node isn't "full", its depth is the minimum depth for this branch
    if(node.children.size < max_children) min = currDepth;

    for(Node nextNode : node.children)
    {
        MinMax<Integer> childDepth = GetMinMaxDepth(nextNode, currDepth+1);
        //check if child is already unbalanced
        if(childDepth.max() - childDepth.min() > 1) return childDepth;
        if(childDepth.min() < min) min = childDepth.min();
        if(childDepth.max() > max) max = childDepth.max();
        //check if current node is unbalanced
        if(max-min > 1) break;
    }

    return new MinMax<Integer>(min, max);
}


A generic IEnumerator to enumerate COM collections

Your ComWrapperEnumerator is generic in two types without needing to.
You don't really care about TComCollection aside that it must be an IEnumerable,
thus that generic type can disappear from your class and you will end up with a constructor method that receives an IEnumerable.

public ComWrapperEnumerator(IEnumerable items)
{
    _internal = items.GetEnumerator();
}

Normally the non generic version calls the generic version of the method, removing your code repetition:

IEnumerator IEnumerable.GetEnumerator()
{
    //call the generic GetEnumerator
    return GetEnumerator();
}

In this particular case I think there isn't any other way to improve the instantion of ComWrapperEnumerator.
However one way that normally is used to avoid specifying types on constructors is to specify a static method to instantiate the type.
If you look for example to Tuple.Create this is exactly what they do.

The hack could work with code like this:

public static ComWrapperEnumerator<T> Create<T>(T t, IEnumerable value){
    return new ComWrapperEnumerator<T>(value);
}

//usage
ComWrapperEnumerator.Create(default(CodePane), ComObject);

You can always provide methods for all types that you care about:

public static ComWrapperEnumerator<CodePane> CreateCodePane(IEnumerable value){
    return new ComWrapperEnumerator<CodePane>(value);
}

But anyway, now that you have one less generic type maybe you are no longer concerned about that.

  I don't like the way I'm assuming the constructor only has a single T
  parameter (where T is the COM type being wrapped by TWrapperItem), is
  there a better way?

Yes there is. Not only there is but would also remove the need of that pesky Activator.CreateInstace. The most straightforward approach that I can think of is to pass a Func that would receive the COM object and return an instance of the type you want. This would be a parameter of the constructor.

private readonly Func<object, TWrapperItem> _createItem;
public ComWrapperEnumerator(IEnumerable items, Func<object, TWrapperItem> createItem)
{
    _internal = items.GetEnumerator();
    _createItem = createItem;
}

public TWrapperItem Current
{
    get { return _createItem(_internal.Current); }
}

object IEnumerator.Current
{
    get { return Current; }
}

Obviously you can always fallback to Activator:

private TWrapperItem CreateItem(object value){
   return (TWrapperItem )Activator.CreateInstance(typeof(TWrapperItem), value);
}

public ComWrapperEnumerator(IEnumerable items, Func<object, TWrapperItem> createItem = null)
{
    _internal = items.GetEnumerator();
    _createItem = createItem ?? CreateItem;
}

Note that if you go with this approach you may consider to come back to having two generic types on your class, so you could have a typesafe _createItem.


Try this approach. It uses CSS Grid layout. It requires less code and is easier to maintain.

.circle {
  display: grid;
  place-content: center;
  border: 0.3em solid black;
  border-radius: 50%;
  width: 6em;
  height: 6em;
}

.initials {
  font-size: 300%;
}

DC


I really like your code.

Use of 'use strict';
No comments, but the code is written so that they are not needed anywhere
Good naming, good size of functions, things are in their logical place

The only thing is that I would not put uid/pwd in the source code, but use environment variables:

Mongoose.connect('mongodb://xxxx:xxxx@proximus.modulusmongo.net:xxxx/xxxx');


Finding the largest mirror image of a subset/set of integers present in an array of integers

Readibility

Whitespaces are free and make things easier to read. Also, you do not need that many parenthesis.

Also, indentation seems a bit weird. After fixing this, here is what I have :

public class MaxMirror {

    public static int maxMirror(int[] nums) {
        final int len = nums.length;
        if (len == 0)
            return 0;
        int maxCount = 1;
        boolean flag = false;

        for (int i = 0; i<len; i++)
        {
            int tempCount = 1;
            int count = i;

            for (int j = len-1; j>= 0 && (count<len); j--)
            {
                if (nums[count] == nums[j] && !flag)
                {
                    flag = true;
                    count++;
                    continue;
                }
                if (nums[count] == nums[j] && flag)
                {
                    tempCount++;
                    count++;
                    maxCount = (tempCount>maxCount)?tempCount:maxCount;
                    continue;
                }
                if (nums[i] != nums[j] && flag)
                {
                    flag = false;
                    count = i;
                    tempCount = 1;
                    continue;
                }
                if (j == count || (j-count)==1)
                {
                    flag = false;
                    break;
                }

            }
        }
        return maxCount;
    }

    public static void main(String[] args) {
        System.out.println("Hello, world!");
        int[] num = {1, 2, 3, 8, 9, 3, 2, 1};
        System.out.println(maxMirror(num));
        int[] num2 = {1, 2, 1, 4};
        System.out.println(maxMirror(num2));
        int[] num3 = {7, 1, 2, 9, 7, 2, 1};
        System.out.println(maxMirror(num3));
    }
}

Re-writting the logic

Instead of using continue, you could just use else between your conditions.

Also, if you have to consider A && B and then A && !B, you should probably consider A and then, as a subcase, the validity of B.

Then, you can remove common code from the then block and the else block.

You can use max instead of checking which value is bigger.

You could move your check count < len to the only place where count could become bigger than len.

You can rewrite (j-count)==1 to make it look like the previous expression : j == (count+1) seems slightly better.

This being done, your code looks like :

public static int maxMirror(int[] nums) {
    final int len = nums.length;
    if (len == 0)
        return 0;
    int maxCount = 1;
    boolean flag = false;

    for (int i = 0; i<len; i++)
    {
        int tempCount = 1;
        int count = i;

        for (int j = len-1; j>= 0; j--)
        {
            if (nums[count] == nums[j])
            {
                if (flag)
                {
                    tempCount++;
                    maxCount = Math.max(tempCount, maxCount);
                }
                flag = true;
                count++;
                if (count>=len)
                    break;
            }
            else if (nums[i] != nums[j] && flag)
            {
                flag = false;
                count = i;
                tempCount = 1;
            }
            else if (j == count || j == (count+1))
            {
                flag = false;
                break;
            }
        }
    }
    return maxCount;
}

Algorithm

Your algorithm seems to be working. However, I find it hard to understand. I guess a bit of documentation would be useful.

Edit : bug found ?

On int[] num5 = {7, 7, 7, 7, 6, 7, 7};, the function returns 6 and I do not see why.

Edit 2

I originally posted this as a different answer because it is not related to the beginning of this message in any way but this doesn't seem to be much appreciated. As it can be relevant to you, I'm posting this here.

As your code doesn't really work and I got quite interested by this problem : I took mjolka's precious comments into account.

Re-adapting code from the link in his comment, here what I got :

public class MirrorString {
    /* Returns length of longest common substring of X and Y */
    public static int LCSubStr(int[] X /* WAS , int[] Y*/)
    {
        int m = X.length;
        int n = m; // WAS int n = Y.length;

        // Create a table to store lengths of longest common suffixes of
        // substrings.   Notethat LCSuff[i][j] contains length of longest
        // common suffix of X and Y. The first row and
        // first column entries have no logical meaning, they are used only
        // for simplicity of program
        int[][] LCSuff = new int[m+1][n+1];
        int result = 0;  // To store length of the longest common substring

        /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */
        for (int i=0; i<=m; i++)
        {
            for (int j=0; j<=n; j++)
            {
                if (i == 0 || j == 0)
                    LCSuff[i][j] = 0;
                else if (X[i-1] == X[n-j]) // WAS else if (X[i-1] == Y[j-1])
                {
                    LCSuff[i][j] = LCSuff[i-1][j-1] + 1;
                    result = Math.max(result, LCSuff[i][j]);
                }
                else LCSuff[i][j] = 0;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println("Hello, world!");
        System.out.println(LCSubStr(new int[] {7, 7, 7, 5, 6, 7, 7})); // 3
        System.out.println(LCSubStr(new int[] {7, 7, 7, 7, 6, 7, 7})); // 5
        System.out.println(LCSubStr(new int[] {})); // 0
        System.out.println(LCSubStr(new int[] {1})); // 1
        System.out.println(LCSubStr(new int[] {1, 1})); // 2
        System.out.println(LCSubStr(new int[] {1, 1, 1})); // 3
        System.out.println(LCSubStr(new int[] {1, 2, 3, 2, 1})); // 5
        System.out.println(LCSubStr(new int[] {1, 2, 3, 8, 9, 3, 2, 1})); // 3
        System.out.println(LCSubStr(new int[] {1, 2, 1, 4})); // 3
        System.out.println(LCSubStr(new int[] {7, 1, 2, 9, 7, 2, 1})); // 2
    }
}

I have adapted the code a bit. Then, the only places where the algorithm has been changed are marked with WAS :

only one argument is required now
instead of accessing the j-1th element from J, we access the n-jth element from X (simulating a backward traversal).

Please note that things could be done in an even more efficient way using a different data structure as per the wikipedia page about Longest Common Substring problem.


import fnmatch
import os
import pyexiv2

matches = []
dict1 = {}

dict1 isn't a great name because its hard to guess what it might be for.

# The aim of this script is to recursively search across a directory for all
# JPEG files. Each time a JPEG image is detected, the script used the PYEXIV2
# module to extract all EXIF, IPTC and XMP data from the image. Once extracted
# the key (ie. "camera make" is generated and it's respective value
# (ie. Canon) is then added as the value in a dictionary.
for root, dirnames, filenames in os.walk('C:\Users\Amy\Desktop'):

Your code will be a bit faster if you put stuff into a function rather than at the module level.

  for filename in fnmatch.filter(filenames, '*.jpg'):
      matches.append(os.path.join(root, filename))
      for entry in matches:

ok, you add each file you find to the matches. But then each time you go over all the matches. I doubt you meant to do that. As its stand, you are going to look at the same file over and over again

          metadata = pyexiv2.ImageMetadata(entry)
          metadata.read()
          x = metadata.exif_keys
          y = metadata.iptc_keys
          z = metadata.xmp_keys

x y and z aren't great variable names. But its seems you aren't really interested in them seperately, just in all the keys. In that case do

keys = metadata.exif_keys + metadata.iptc_keys + metadata.xmp_keys

to combine them all into one list. (I'm guessing as to what exactly these keys are but, I think I it'll work.)

          for key in x:
              value = metadata[key]
              dict1[key] = value.raw_value

I'd combine the two lines

dict1[key] = metadata[key].raw_value

          for key in y:
              value = metadata[key]
              dict1[key] = value.raw_value
          for key in z:
              value = metadata[key]
              dict1[key] = value.raw_value
              print dict1

If you put combine x,y,z as above, you'll only need the one loop


Reinderien has covered the PEP-8 style issues, so here's some input on the logic.

Running the program (with the half of your question that isn't the code as an input) gives the following result:

This program is being run by itself
100 -|
     |
     |
     |
     |      ***   ***
     -|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|-
      0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15
main function took 0.185 ms

So two obvious issues are that the X-axis should be one character further right and the numbers lose alignment.

Per the specification you should be printing a table, not a histogram.

Also, when adjacent columns are both filled it could get a bit confusing, perhaps a single-width column would be better?

100 -|
     |
     |
     |
     |       *     *
      -|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|-
       0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15

Short texts don't appear on the chart at all, and long texts could have more than 100 words of a given length - consider normalising your counts to the proportion of the input.

You are replicating functionality that already exists in Python: collections.Counter would save you a lot of work. Keys that don't have counts will automatically return zero, for example, and you don't need insert_Dict:

out = read_string.translate(None, punc)
length_dict = Counter(map(len, out.split(" ")))

Note that explicitly splitting on a single space means you don't have to handle the single punctuation characters separately:

>>> "foo & ba'r".translate(None, punc).split(" ")
['foo', '', 'bar']

Your main should look more like:

def main():
    with open(sys.argv[1]) as f:
        data = f.read()
    counts = create_counter(data)
    proportions = normalise_counts(counts) # if required
    draw_histogram(proportions)

Splitting the other functionality out into separate functions.

Your histogram-drawing code uses a lot of explicit string concatenation. It is better to .format and .join strings (see string methods), for example:

print '       {0}'.format("".join(map("{0:<3}".format, range(16))))

Which produces:

       0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15


For this:

try
{
    readerWriterLock.EnterWriteLock();
    //do stream stuff here
}
finally
{
    readerWriterLock.ExitWriteLock();
}

EnterWriteLock should be before the try statement.

  Suppose the EnterWriteLock() fails. For whatever reason.
  Then the one thing you shouldn't do is to Exit a lock you never Entered.

Source: C# - Lock question using EnterWriteLock
Please note that singleton nowadays is rather an antipattern. They make testing harder and often hide dependencies which leads to spaghetti code which is really hard to work with. What is so bad about singletons?


Splitting a list of numbers into multiple lists

Pretty minor but you don't need the  if (row_id == 0)

if (row_id++ > list_size) // Add the sublist to the result
{
    result.Add(route_list);
    row_id = 0;
    route_list = new List<long>();
}

Also it seem like you should also test for

if (route_list.Count > 0 )

Why not just put where route_source_id is not null in the query?

Connection, Command, and Reader behave the same with many DB so this is pretty portable.

I think you can use

conn.CreateCommand()

Long is not required for row_id or list_size

Why bump row_id++ if there is no value?

In summary

    using (var reader = cmd.ExecuteReader())
    {
        const int list_size = 100;
        List<long> route_list = new List<long>(list_size);

        while (reader.Read())
        {
           if (route_list.Count >= list_size) // Add the sublist to the result
           {
               result.Add(route_list);
               route_list = new List<long>(list_size);
           }
           route_list.Add(reader.GetInt64(0));
        }

        if (route_list.Count > 0 ) // add the last sublist
        {
           result.Add(route_list);
        }
    }


Project Euler 25 - x-digit Fibonacci Number

I feel like a class is not a good way to approach this problem.

C# forces you to write classes, but using static methods will allow you to ignore this.

The only method you should keep non-static is the on calculating the n-th fibonacci, as the memoization requires state, and a class is a way to keep state.

Getting the number of digits of a number is instead something without atate that depends only on the input number, so:

public static digitsLength(BigInteger n) {
    return number == 1 ? 1 : (int) Math.Floor(BigInteger.Log10(number) + 1);
}

Minor remarks are:

Naming: You used get in the name, but in OO get has a precise meaning that is inappropriate here.
Ternary: When the condition is simple, like here, using a ternary increases compactness and readability.

Now main is simply:

for (var i upto infinity) {
    if DigitsLength( Fibonacci(i) ) == REQUIRED_DIGITS {
        print( Fibonacci(i) )
    }
}

PS: Note that the above is pseudo-code, it is just to give you an idea.


Simulating data generating process correctly

The first thing that jumps out from the definition is that, if you have X, A, B and epsilon, you can compute y deterministically. This means you can readily test your implementation. You should always strive to find ways to define pure functions in your R code, and try to use vectorisation instead of for loops.

Based on your existing code, I'll assume for a given model that X is a matrix (n_sample, 100), A and B are vectors of length 100 and epsilon is a vector of length n_sample.

Based on your implementation, the function would look something like

compute_y <- function(X, A, B, epsilon) {
  n_sample <- nrow(X)
  # note that your f_[1|2] stored `double`s not `integers`
  f_1 <- numeric(n_sample)
  f_2 <- numeric(n_sample)

  for (d in seq(100)){
    part1 <- 1 + (-1)^d*A[d]*X[,d] + B[d]*sin(6*X[,d])
    f_1 <- f_1 + part1
  }
  for (d in seq(50)){
    part2 <- 1 + X[,d]/50
    f_2 <- f_2 + part2
  }

  f_1 * f_2 + epsilon
}

But that's a bit scruffy.

The easiest bit to clean up is the bit that defines f_2:

f_2 <- numeric(n_sample)
for (d in seq(50)) {
    part2 <- 1 + X[,d]/50
    f_2 <- f_2 + part2
}

Here you're only using the first 50 columns of X. You could rewrite it as:

f_2 <- numeric(n_sample)
W <- 1 + X[, 1:50]/50
for (d in seq(50)) {
    f_2 <- f_2 + W[,d]
}

But in the latter, you're summing along the rows of W. So you could ditch the for loop altogether:

W <- 1 + X[, 1:50] / 50
f_2 <- rowSums(W)

This gives us:

compute_y <- function(X, A, B, epsilon) {
  n_sample <- nrow(X)

  f_1 <- numeric(n_sample)

  for (d in seq(100)){
    part1 <- 1 + (-1)^d*A[d]*X[,d] + B[d]*sin(6*X[,d])
    f_1 <- f_1 + part1
  }

  f_2 <- rowSums(1 + X[, 1:50] / 50)

  f_1 * f_2 + epsilon
}

There is a way to replace the for-loop that computes f_1.

First note you're adding 1 to f_1 one hundred times, so you might as well start with f_1 storing the value 100

f_1 <- rep(100, n_sample)

for (d in seq(100)){
  part1 <- (-1)^d*A[d]*X[,d] + B[d]*sin(6*X[,d])
  f_1 <- f_1 + part1
}

For speed, I'll just show you how to do it:

tX <- t(X)
a <- colSums(c(-1, 1) * A * tX)
b <- colSums(B * sin(6 * tX))
f_1 <- 100 + a + b

That code would be a bit faster, but I don't think it looks as clean as your definition of f_1.

If you want you can move the code that defines X, A, B, and epsilon into a model-definition function.


Conditional merge with Ruby to include a parameter if it hasn't been included

You want to merge params with one or more default values. How about, well, #merge?

{"published" => false}.merge(params[:template].permit!)

Only trick, if you can call it a trick, is that the default hash must use string keys, not symbols, despite the params object accepting either. The resulting hash will also be keyed with strings only.

Alternatively, you can use HashWithIndifferentAccess to get around this:

defaults = HashWithIndifferentAccess.new({ published: false })
filtered = defaults.merge(params[:template].permit!)

And filtered will be a HashWithIndifferentAccess much like params produces.

All that said, the better way to handle all this is to send the right parameters in the first place. With the code above you're always assuming that published should be set to false unless told otherwise. But there could be all sort of reasons for why only a subset of parameters are sent; if published is intentionally left out, it'll suddenly be filled in - perhaps wrongly - by the controller.

Relatedly, if the parameter is required, raise an exception if it's missing and tell the client. It's not the controller's job to fill in the blanks when faced with incomplete information. Conversely, it's the client's job to send the parameters that are necessary or required.

As I said in a comment, if you use Rails' regular checkbox helpers, they'll produce a hidden input with the checkbox's "unchecked" value, in addition to the checkbox input itself. If the checkbox is checked, it'll override the former, unchecked value. This is the typical (and better) way to solve this.

So in short, if you want to merge to hashes, use #merge. But in this case, you probably don't want to do that.


for loop

Use a for loop when iterating over a collection:

    for (x, y) in current_positions:
        moves.append((x, y))

for has less power than while (theoretically) and its simplicity makes it a better choice over while.

Avoid premature optimization

Just multiply by two:

n *= 2

Some tests:

>>> import timeit
>>> timeit.timeit("10 << 1")
0.029866752000089036
>>> timeit.timeit("10 * 2")
0.03209113599950797
>>> 0.029866752000089036 / 0.03209113599950797
0.9306854079751793

<< is just 7% faster than *2

And the majority of your time is spent branching if x + step <= a: and playing with lists moves.append((x, y)), so the final improvement would be tiny, not worth the loss in readability.

Optimizing the algorithm

Your algorithm has exponential time complexity:

print(step, len(current_positions))

Gives:

1 2
2 4
4 8
8 16
16 32
32 64
64 74
128 0

At each iteration, the number of current_positions is doubling, and this can get out of hand really quickly.

Arguments name

a and b are not acceptable argument names. I suggest width and height.

Some plotting always gives ideas

Following @ErikR suggestion, I made a graph of the reachable points and noticed a serious regularity, still doing graphs is a nice skill to have, so I encourage you to reproduce this graph by yourself.


How can I avoid unchecked cast warning in my generic recursive Iterator?

I don't think you can do anything about this. You have to cast here, and in the process you lose all information about the type parameter: The compiler can't know that if you have a RecursiveElement, it's always a RecursiveElement<T>, and "thanks" to type erasure it can't check the runtime type.


Code compilation issues

The code didn't compile cleanly for me.

There was a missing right paren on this line:

    memcpy(&dest[dest_offset], &bitmapS[nBitmap][src_offset], sizeof(pixel);

I got a warning that memset was used without a prototype.  I added #include <string.h> to fix that.
The code was missing the BMP and DIB structures.  I substituted 14 for sizeof(BMP) and 40 for sizeof(DIB) to compensate.

Code style/formatting

Keeping in mind that style and formatting are somewhat subjective, here are some issues I spotted:

I didn't like the use of a nested for loop at the same indentation.  It confused me a little bit:

for(i = 0; i < src_width; i++)
for(j = 0; j < src_height; j++)

I didn't like the "Windows-ization" of the types.  Personally, I don't like seeing ddword, dword, and word because I really don't have any idea what those are.  I prefer to just #include <stdint.h> and use uint64_t, uint32_t, and uint15_t.  Plus, the stdint types are safer to use.  Your dword type, for example, is presumably supposed to be 32 bits wide, but you typedef'd it to unsigned long.  On a 64-bit machine, unsigned long is likely to be 64 bits wide.
Currently, bmp_rotate() takes an index as an argument, and then indexes into a global array of bitmaps.  The code would be more reusable if the function took one bitmap as an argument, like this:

buffer bmp_rotate(const buffer bitmap, float angle);

Then it could be used from anywhere without being entangled with the global variable.
There is dead code in the inner loop.  This code doesn't do anything:

    deltaX = i + midX;
    deltaY = j + midY;

Bugs in the code

The rotation is wrong.  For example, if you pass in 0 for the angle, you should wind up with the same bitmap.  Instead, you get a bitmap that is rotated 90 degrees to the right and mirror imaged.  To fix it, I changed your rotation computation to this:

rotX = (dword)(midX + deltaX * cos(angle) + deltaY * sin(angle));
rotY = (dword)(midY - deltaX * sin(angle) + deltaY * cos(angle));

There are uninitialized pixels in the rotated bitmap.  The destination bitmap is created like this:

buffer dest = malloc( src_pixels + src_nraw );
memcpy(dest, bitmapS[nBitmap], src_pixels);

This allocates a bitmap of the same size of the original and copies the header information from the original to the new bitmap.  However, the pixels in the new bitmap are all uninitialized.  Later, when doing the rotation, not all pixels in the new bitmap are set (because some are not mapped to any original pixel).  So those pixels end up with a random value.  You can fix this by simply using calloc() to allocate the new bitmap.
The offset of the pixels may not be right.  Currently, the offset from the start of the bmp data to the first pixel is calculated like this:

const dword offset = sizeof(BMP) + sizeof(DIB);

I'm not an expert on bmp files, but I believe that the DIB part is a variable length part.  So to get the right offset, you should be using the value you call src_pixels as your offset instead.

Speed issues covered up by the compiler

There are a couple of things that I spotted that you could have done better speedwise, but that the compiler (gcc -O4) seemed to fix for you.

Instead of using sin(angle) and cos(angle) in your inner loop, you could compute those once at the start of the function, and then use the precomputed versions later on:

float sin_angle = sin(angle);
float cos_angle = cos(angle);
...
rotX = (dword)(midX + deltaX * cos_angle + deltaY * sin_angle);
rotY = (dword)(midY - deltaX * sin_angle + deltaY * cos_angle);

Apparently, gcc is smart enough to know that sin() and cos() are pure functions, so it was able to optimize away the calls in the inner loop.  Still, it's good practice to do this kind of optimization yourself.  If instead of sin() and cos() you were calling your own function, then the compiler might not know the optimization was possible.
In bmp_find_xy(), all of the lines up to the computation of pixAddress are the same for a given sized bitmap.  So you could do an optimization where you compute offset, rowsize, and single just once, and then use those precomputed values in the inner loop.  Just as with #1, gcc was smart enough to do all that already.

Speed issues not covered by the compiler

The way that you order your nested loop, on every iteration, you move from one destination pixel to the one below it.  If you swapped the two loops, you would instead move from one pixel to the one to its right.  This is a better ordering, because it is more cache friendly.  In fact, when I swapped the two loops, I was able to get a 5% speedup on a 45 degree rotation.
Oftentimes with loops, you can often simplify the calculation within an inner loop if you compute an initial value and then increment the value instead of recomputing the whole thing.  For example, let's look at a sample loop:

for (i=0;i<n;i++) {
    offset = i * ROW_WIDTH + startOffset;
    do_something(offset);
}

You can simplify this to:

offset = 0 * ROW_WIDTH + startOffset;
for (i=0;i<n;i++) {
    do_something(offset);
    offset += ROW_WIDTH;
}

Using this technique, I simplified your main loop to this:

for(j = 0; j < src_height; j++) {
    ddword dest_offset = src_pixels + j * rowsize;
    float  deltaY = j - midY;
    float  deltaX = 0 - midX;
    float  x = midX + deltaX * cos_angle + deltaY * sin_angle;
    float  y = midY - deltaX * sin_angle + deltaY * cos_angle;
    for(i = 0; i < src_width; i++) {
        dword rotX = x;
        dword rotY = y;
        if(rotX >= 0 && rotX < src_width && rotY >= 0 && rotY < src_height)
        {
            ddword src_offset = src_pixels + rotY * rowsize + rotX * single;

            memcpy(&dest[dest_offset], &bitmap[src_offset], sizeof(pixel));
        }
        x += cos_angle;
        y -= sin_angle;
        dest_offset += single;
    }
}

Notice how the inner loop has replaced three complicated expressions with three simple additions.  This change resulted in a 140% speedup (it was 2.4x faster)!
Memcpy isn't so great for only 3 bytes.  I replaced your call to memcpy with some inlined code:

    // Old code:
    // memcpy(&dest[dest_offset], &bitmap[src_offset], sizeof(pixel));
    // New code:
    dest[dest_offset+0] = bitmap[src_offset+0];
    dest[dest_offset+1] = bitmap[src_offset+1];
    dest[dest_offset+2] = bitmap[src_offset+2];

This resulted in a 9% speedup.


Accessing a certain I/O controller using memory-mapped I/O

You should make a small driver layer, so that the main doesn't know about the low level details of what is going on - and here in that .c file that you have implemented the driver in, the constants goes as well.

Then you call your driver and all is good :)


public SharedDisposable(object[] ctorArgs = null)
{
  if (ctorArgs == null)
      ctorArgs = new object[] { };

  var ctor = typeof(SharedDisposable<T>).GetConstructor(ctorArgs.Select(a => a.GetType()).ToArray());
  Item = (T)ctor.Invoke(ctorArgs);
  instances[Item] = new List<SharedDisposable<T>>() { this };
}

This constructor is not a very good idea because the use needs to exactly know the signature of the constructor in order to create T.

A much better way would be to let him specify a factory lambda. Then all it will be left is:

public SharedDisposable(Func<T> create)
{
    Item = create();
    instances[Item] = new List<SharedDisposable<T>>() { this };
}

so now he can call it in a much easier fashion like:

Port = new SharedDisposable<SerialPort>(() => new SerialPort("COM5", 9600));

The other constructor using KeyValuePairs is now obsolete.

public SharedDisposable(object[] ctorArgs = null)
{
  if (ctorArgs == null)
      ctorArgs = new object[] { };
  ...
}

Btw. you can make this look cleaner with the coalesce operator: ??

ctorArgs = ctorArgs ?? new object[] { };

Objects like this one usully use the name Value for what you chose Item.

Its usage might be easier in certain scenarios if you added an implicit cast operator to T:

public static implicit operator T(SharedDisposable<T> share) => share.Value;

If you replaced the List by a HashSet the Dispose method could be simplified to:

public void Dispose()
{
    if (instances[Value].Remove(this) && instances[Value].Count == 0)
    {
        instances.Remove(Value);
        Value.Dispose();
    }
}


JavaScript parameters - best practices for settings object/callback

I would prefer a setting object for each function you want to call instead of merging them together into one, because then it is clear who needs this parameters. Otherwise this information gets lost. And who knows what jquery will do with this options in future releases? Maybe something useful, maybe not.

I think it is okay to add functions to objects but you can it make a little nicer when you define these not directly in the options object, instead only referencing.

(function (window, document, $, undefined) {

    function successHandler
    ...

    function myFunction(settings, sc, ec) {
    ...

      {
         success: successHandler
      }

Also I would prefer real names and no two character abbrevations. That makes the code more readable for you and the rest of the world.


Best Practices

Ideally you should separate your logic from your HTML as much as possible.
Building a string with += is less efficient than using a buffer. In other words, push each part of the string into an array and then join() the array. When you use += you're loading the entire string into memory every time you add to the string. Here's a re-write of your listPastTimes function.

function listPastTimes() {
  pastTimesDisplay.innerHTML =
    '

' +
    pastTimes.join('

') +
    '

';
}

Stuff that's just my opinion

I personally would not use the curlies for your if if you're only calling a function. I would put the function on the same line and lose the curlies. Some people are religious about the curlies and it's ok if you are, but in my opinion it's just adding unnecessary lines to the code. I'll defend that to the death. The Apple SSL bug is not a valid argument for curlies because that developer did not put the code on the same line as the if.
This is only gonna work on relatively new browsers (maybe that was inended) - I would have used more widely supported methods.
I've really don't like the idea of assigning booleans in an if/else. To me, this feels redundant. I would have done triggerStartStop like this:

function triggerStartStop() {
  intervalId = timeRunning ?
    clearInterval(intervalId) :
    setInterval(increment, 10) ;
  timeRunning = !timeRunning;
}

function increment() {
  currentTime += 10; // Increment
  currentTimeDisplay.textContent = // Write
    (currentTime / 1000).toFixed(2);
}


Singleton holding and notifying registered listeners

(Disclaimer: I posted this as a comment first but feel like it should also be an answer)

You should consider to use enum as a singleton as proposed by Joshua Blochs in Effective Java. This will protect you from both serialization attacks and reflection attacks on your singleton instance.

Here is a post which discusses it a lot more in-depth.
https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java/71399#71399


It can be done several ways.  Instead of explicitly using recursion we can, as @alxndr suggested, make use of the recursion capabilities of the Enum module.  I am going to use Enum.map_reduce simply because I find it useful when troubleshooting to key the items and the accumulator in that form.

In general the solution is the same as yours.

  def sum(list) do
    list |> Enum.map_reduce([],
      fn({key, val}, acc) ->
        {{key, val}, Keyword.update(acc, key, val, &(&1 + val))}
      end
    ) |> elem(1)
  end

The anonmous function in map_reduce accepts and item and an accumulator.  Since the item is a keyword list, it has the form {key,val} so I match that  in the function definition.  The return from this function must be a tuple with the accumulator as the second value.  For testing purposes I returned the same {key, val} as the first item.  The Keyword.update function is the accumulator.  A form of this same routine that helps the intermediate values be visible is:

def sum(list) do
  list |> Enum.map_reduce([],
    fn({key, val}, acc) ->
      x = Keyword.update(acc, key, val, &(&1 + val))}
      IO.inspect(x)
      {{key, val}, x}
    end
  ) |> elem(1)
end

In the case of the input you provided, the IO.inspect helps me understand how the routine collected the desired result, as seen below.

[a: 1]
[a: 1, b: 2]
[a: 1, b: 2, c: 3]
[a: 3, b: 2, c: 3]
[a: 3, b: 3, c: 3]
[a: 3, b: 3, c: 3]
[a: 3, b: 3, c: 3]

I found this a fun exercise -- thanks for posting.


Generating a PANDAS DataFrame of simulated coin tosses

You are in for a treat, first of all a style review of existing code, followed by a code review of your current code, followed by a code refactoring, and topped of with a performance review of current solutions. All a part of the experience here at Code Review for free! Sit back, and enjoy. :-)

Style review

Actually it seems like you've done some coding before, and so most of the style is quite good. There are however some issues, and they are all related to naming:

Class names is suggested to be CamelCase – And neither coin or trial is good class names. When looking at the function they provide better names could possibly be CoinFlip and RepeatedCoinFlip
Don't use abbreviations in any names – What is it with v_rand or C_RAND_IDX and most other variable names? When you have to guess what the variable is, then it is a bad choice of variable name
Don't let a function name contain the parameter  – It is quite clear that both the flip10 and flip1000 are named after something which should be a parameter. This is not dynamic, and doesn't easily extend. What if you wanted the flip10 to flip it a hundred times?
Bonus point for using xrange in Python 2.7

Code review

There are several code smells related to your code, sadly enough, which affects both readability as well as efficiency of your code. Lets address these:

Letting the __init__ do all the work – When you can't do anything with the class except what is done through the initialisation of the class, you should reconsider whether you are on the right path or not. In most cases this should be written as a simple function. If insisting on using class, you should strip down the initialisation, and let methods do the actual work
Initialisation of C_RAND_IDX should most likely be in __init__ – I'm guessing, but I'm assuming that this should change for every instantation of the trial class. In this case, it should not be a constant, or it should be set within the __init__ method
Hardcoding of parameters – Having methods like flip10 and flip1000 is going against what we have methods for. They should really have a parameter allowing for this number to change. You could have a default parameter, but it should be possible to change it
Calculating coin frequency using arrays and float calculation is waste of memory and calculation power – In your current code there is no reason to store every coin toss in an array when you all you need is the sum of all coin tosses (which represent the tail coin tosses). You could easily sum it directly. (Taking it all the way, you could even do a random.randit(0, coin.FLIP_TIMES) instead of the sum :) )
Simplify coin toss – To rebuild the choices = [coin.HEADS, coin.TAILS] and use random.choice() seems like waisted energy. Why not simply use random.randint(0, 2) which will give the same result?
Why use classes, when methods suffice? – As already touched upon, your scenario doesn't seem to be a good case for classes as they only provide one single return in both cases. This could most likely be better handled in methods directly.
Avoid extensive float calculations, if possible – Aritmethic with floats are more expensive then int arithmetic. Int comparision is also cheaper than float comparison. In other words, why compute the frequency as a float when the integer is just as good. You can always return the frequency as a float in the return statement. Which would reduce from 100 000 times * 1000 * 10 float operations, to 100 000 * 3 float operations. In total that is 333 333 less float division operations (and comparison and so on). That should be noticeable.

Code refactor

Lets give a pure methods implementation (before comparing some of these methods).

import random

def coin_flip(flip_count):
    """Returns how mains tails, 1, out flip_count coin flips"""
    return sum(random.randint(0, 2) for _ in xrange(flip_count))

def fake_coin_flip(flip_count):
    """Returns a random tails count"""
    return random.randint(0, flip_count+1)

def repeated_coin_flip(repetitions=1000,
                       flip_count=10,
                       coin_flip_function=coin_flip):
    """Repeat some frequencies from a large repetition of coin flip sequences.

    Repeat <repetitions> of <flip_count> coin flips. Out of these return three
    frequencies, namely the first, the minimum and a random frequency.
    """

    minimum_count = repetitions + 1
    random_index = random.randint(0, repetitions)

    for i in xrange(repetitions):
        count_of_tails = coin_flip_function(flip_count)
        #print('coin_flip: {}'.format(count_of_tails))
        if count_of_tails < minimum_count:
            minimum_count = count_of_tails

        if i == random_index:
            random_count = count_of_tails

        if i == 0:
            first_count = count_of_tails

    flip_count_as_float = float(flip_count)
    return {'rand': random_count / flip_count_as_float,
            'first': first_count / flip_count_as_float,
            'min': minimum_count / flip_count_as_float }

Performance review

I've timed four solution based on answers so far: Original solution by compguy24, solution by SuperBiasedMan, and two variations of mine solution. In order to time them I've done a few adaptations, and only focus on the build of the data list. Here is the interesting part of the performance setup:

# Helper function to simulate the need of the full data set
# Could print out the first two, and last two elements
def print_some_data(data):
    """Print the two first and two last data elements"""
    for start_element in data[:2]:
        print('    first: {:,.4f},   min: {:,.4f},   rand: {:,.4f}'.format(
              start_element['first'], start_element['min'], start_element['rand']))

    print('    ... skipping loads of items ...')

    for end_element in data[-2:]:
        print('    first: {:,.4f},   min: {:,.4f},   rand: {:,.4f}'.format(
              end_element['first'], end_element['min'], end_element['rand']))

# After renaming classes to Coin & Trial
def compguy24_solution(datasize=1000, print_data = True):
    print('    Generating {} elements'.format(datasize))
    data = [Trial().results for i in xrange(datasize)]
    if print_data:
        print_some_data(data)

def SuperBiasedMan_solution(datasize=1000, print_data=True):
    print('    Generating {} elements'.format(datasize))
    data = [trial() for _ in xrange(datasize)]
    if print_data:
        print_some_data(data)

def holroy_solution(datasize=1000, print_data=True):
    print('    Generating {} elements'.format(datasize))
    data = [repeated_coin_flip(1000, 10) for _ in xrange(datasize)]
    if print_data:
        print_some_data(data)

# Same as previous, but faking the coin_flip :-D
def holroy_solution_v2(datasize=1000, print_data=True):
    print('    Generating {} elements'.format(datasize))
    data = [repeated_coin_flip(1000, 10, fake_coin_flip) for _ in xrange(datasize)]
    if print_data:
        print_some_data(data)

def main():
    test_case = "from {0} import {1}; {1}({2}, False)"

    for test_function in ('compguy24_solution',
                          'SuperBiasedMan_solution',
                          'holroy_solution',
                          'holroy_solution_v2',):

        print ('\nTesting {}'.format(test_function))

        datasize = 1000
        print('    execution time: {:,.4f} seconds'.format(
              timeit.timeit(test_case.format(__name__, test_function, datasize),
                                             number=1)))

if __name__ == '__main__':
   main()

Updated: I did a few test runs to compare the different solutions, before doing a final test run of 100 000 times (which I let run over night). With a 1000 samples I found the following: Original code (58.6 seconds) and the version by SuperBiasedMan (56.5 seconds) runs in around a minute, whilst my version using int comparison and simpler random function runs in only 2.8 seconds (about 20 times faster). ( And if faking the coin flip, it only takes 0.5 seconds to complete it. :-) )

But here are the ultimate test for a 100 000 times run on my computer:

Testing compguy24_solution
    Generating 100000 elements
    execution time: 5,600.1455 seconds

Testing SuperBiasedMan_solution
    Generating 100000 elements
    execution time: 5,565.2747 seconds

Testing holroy_solution
    Generating 100000 elements
    execution time: 277.3780 seconds

Testing holroy_solution_v2
    Generating 100000 elements
    execution time: 43.8776 seconds

That is the original and the solution by SuperBiasedMan took around 1.5 hours to complete, whilst my solution took 4.5 minutes. (The fake coin_flip variant under a minute). I think it is somewhat clear which solution I would prefer! Sorry guys! :-D


Generate a list of the last 100 modified folders

A couple of general things (in addition to what Vogel said about using explicit references):

Consider avoiding the "On Error" statements and using a short/reusable "sheetExists" function instead. Something like this:

Function sheetExists(wb As Workbook, wsName As String) As Boolean
    Dim tempBool As Boolean
    tempBool = False
    Dim ws As Worksheet
    For Each ws In wb.Sheets
        If ws.Name = wsName Then
            tempBool = True
            Exit For
        End If
    Next
    sheetExists = tempBool
End Function

Avoid select statements, which slow down your code and make it less readable. For example:

'This section...
folder_sheet.Select
Range("A1").Select
Columns(1).ColumnWidth = 10
Columns(2).ColumnWidth = 18
'...could be rewritten as:
With folder_sheet
    .Columns(1).ColumnWidth = 10
    .Columns(2).ColumnWidth = 18
End With

Read the folder information into an array and write it to the workbook all at once, instead of writing one value at a time. This will greatly improve performance, especially once you start getting into the thousands of folders.

'Old version
Set fs_folder = fso.GetFolder(results_dir)
Dim counter As Integer
counter = 0

For Each Folder In fs_folder.SubFolders
    counter = counter + 1
    Cells(counter, 1).Value = Folder.Name
    Cells(counter, 2).Value = Folder.DateLastModified
Next

'New version
Set fs_folder = fso.GetFolder(results_dir)
ReDim subFolderArr(1 To fs_folder.SubFolders.Count, 1 To 2) As Variant

Dim counter As Long
counter = 0
For Each Folder In fs_folder.SubFolders
    counter = counter + 1
    subFolderArr(counter, 1) = Folder.Name
    subFolderArr(counter, 2) = Folder.DateLastModified
Next

With folder_sheet
    .Range(.Cells(1, 1),.Cells(counter, 2)) = subFolderArr
End With

Overall, here's what the finished product would look like (it took 36.5 seconds to complete in a directory with 100k test subfolders):

Sub Create_Sorted_Folder_List(results_dir As String)

    'Create/clear data from results sheet
    Dim folder_sheet As Worksheet
    If sheetExists(ThisWorkbook, "Folders") Then
        Set folder_sheet = ThisWorkbook.Sheets("Folders")
        folder_sheet.Cells.Clear
    Else
        Set folder_sheet = ThisWorkbook.Worksheets.Add
        folder_sheet.Name = "Folders"
    End If

    'Get subfolder list, add data to sheet, and create table
    Dim fileArr As Variant
    fileArr = getSubfolderList(results_dir)

    With folder_sheet
        .Range("A1") = "File Name"
        .Range("B1") = "Date Modified"
        .Range(.Cells(2, 1), .Cells(UBound(fileArr, 1) + 1, 2)) = fileArr
        .ListObjects.Add(xlSrcRange, .Range(.Cells(1, 1), _
                                            .Cells(UBound(fileArr, 1) + 1, 2)), , xlYes).Name = "ResultsTable"
    End With

    Dim resultsTbl As ListObject
    Set resultsTbl = folder_sheet.ListObjects("ResultsTable")

    'Sort and format table
    With resultsTbl
        .Sort.SortFields.Clear
        .Sort.SortFields.Add Key:=.ListColumns("Date Modified").Range, _
                        SortOn:=xlSortOnValues, _
                        Order:=xlDescending, _
                        DataOption:=xlSortNormal
        .Sort.Apply
        'Set column widths manually...
        .ListColumns("File Name").Range.ColumnWidth = 10
        .ListColumns("Date Modified").Range.ColumnWidth = 18
        '...or just autofit instead
        '.Range.Columns.Autofit
    End With

End Sub
Function getSubfolderList(sourcePath As String) As Variant
'Creates array of subfolders in the first level of a directory (sourcePath)
'Stores name/date modified of each subfolder

    Dim fso As Object
    Set fso = CreateObject("Scripting.Filesystemobject")

    ReDim subfolderArr(1 To fso.GetFolder(sourcePath).Subfolders.Count, 1 To 2) As Variant
    Dim i As Long
    i = 0
    Dim subF As Object
    For Each subF In fso.GetFolder(sourcePath).Subfolders
        i = i + 1
        subfolderArr(i, 1) = subF.Name
        subfolderArr(i, 2) = subF.DateLastModified
    Next

    getSubfolderList = subfolderArr

End Function
Function sheetExists(wb As Workbook, wsName As String) As Boolean
'Determines whether a sheet with a given name (wsName) exists in a workbook (wb)

    Dim ws As Worksheet
    Dim tempBool As Boolean
    tempBool = False
    For Each ws In wb.Sheets
        If ws.Name = wsName Then
            tempBool = True
            Exit For
        End If
    Next
    sheetExists = tempBool

End Function


Don't use a class
There is no need to create a class just to hold a collection of static functions. Instead, just declare the functions in the global namespace. If you want to avoid polluting the global namespace, consider putting them in a namespace instead, like so:
namespace TextManipulation {

std::string replace(...) {
    ...
};

...
}

Don't write unnecessary trivial wrapper functions
There is no need to create TextManipulator::replace(), when all it does is call std::regex_replace with almost exactly the same arguments. Why not call std::regex_replace() directly instead?
The name replace() also hides the fact that pattern is a regular expression.
Consider renaming toLowerCase() to tolower()
It's a bit annoying to have different naming conventions in one program, and since you already have tolower() for single characters, it would be very convenient to reuse that for whole strings as well. So:
std::string tolower(const std::string &str) {
    ...
}

Note: you forget to add const to the function parameter here, as well as for the first parameter of replace(), but you did it correctly for the other string parameters.


Honestly, I'd recommend against creating a class. You may want classical inheritance in the future, but right now it's not necessary. Premature optimization rarely benefits anyone. Besides, if you do want classical inheritance later, it's pretty trivial to convert the code.

I'd just write it as simply as possible for now, and see what I'll actually need later:

do -> # wrap in an IIFE
  # simple local variables
  isOpen      = false
  modalElem   = null
  overlayElem = null
  modal       = angular.module 'modal'

  angular.element(document).ready ->
    modalElem   = document.getElementById 'modal'
    overlayElem = document.getElementById 'overlay'

  open = (attrs) ->
    return if isOpen # return early
    isOpen = true

    options =
      opacity:    1
      ease:       Back.easeOut
      height:     attrs.height
      width:      attrs.width
      marginTop:  attrs.height / -2
      marginLeft: attrs.width / -2

    modalElem.style.width  = 0
    modalElem.style.height = 0
    overlayElem.style.display = 'block'
    TweenLite.to modalElem, 0.75, options

  close = ->
    return unless isOpen # return early
    TweenLite.to modalElem, 0.33,
      width:      0
      height:     0
      marginTop:  0
      marginLeft: 0
      opacity:    0
      ease:       Back.easeOut
      onComplete: ->
        overlayElem.style.display = 'none'
        isOpen = false # moved this here, so it flips when the modal's fully closed

  modal.directive 'openmodal', ->
    (scope, element, attrs) ->
      element.bind 'click', -> open attrs

  modal.directive 'closemodal', ->
    (scope, element, attrs) ->
      element.bind 'click', -> close()

If you're compiling this as a single file with CoffeeScript's default IIFE wrapper, you can skip the do -> and indentation; it'll be added automatically.

If you don't want to take the approach above, here are some tips for your current code:

Using explicit return is only necessary if you want something other than the last evaluated expression to be returned. In you open/close functions, it'd be beneficial to simply return early (like I do in the code above) instead of having a big if branch.

Also, a neat trick:

getWindowDim : ->
  return dim =
    height : window.innerWidth or document.documentElement.clientWidth
    width  : window.innerHeight or document.documentElement.clientHeight

can be written as

getWindowDim : ->
  height : window.innerWidth or document.documentElement.clientWidth
  width  : window.innerHeight or document.documentElement.clientHeight

The return is implicit, there's no need for a variable assignment, and CoffeeScript will automatically make an object.


Finding the number of pairs in an integer Array

Overall it's very readable and fast already. Good job.

I have some suggestions for possible improvements:

As n must be equal to ar.size, you could drop that parameter from the method and use ar.size in place of n within the method body.
This method is a pure function except for the side effect of printing the result. Being a "pure function" is often a good thing so you can move the printing of the result to outside the method. Printing something is also quite time-consuming.
Your method could easily support more than Int, it doesn't have to be restricted by a specific type. You could check for duplicates of any type so we can make this method generic.
As you are iterating over elements you could use for (e in ar) instead of iterating over the indexes with for (i in 0 until n). This would make it more efficient for data structures that doesn't have a \$O(1)\$ lookup-time, for example LinkedList.
The method HashSet.add returns false if the value already exists, so you don't need the call to .contains.
There is a typo in the name enteries, it should be called entries.
ar could be called input to make it more readable.

After applying all of the above, this is what you would end up with:

fun <T> getNumberOfPairs(input: Array<T>): Int {
    val entries = HashSet<T>()
    var pairs = 0

    for (e in input) {
        if (!entries.add(e)) {
            pairs++
            entries.remove(e)
        }
    }
    return pairs
}


I'd first create an interface that your FizzBuzzConverter class can implement:

public interface IConverter
{
    string Convert(int value);
}

public class FizzBuzzConverter : IConverter
{
    // ...
}

Then the PseudoBrain can have any implementation of the interface injected into it:

public class PseudoBrain
{
    private readonly IConverter _converter;

    public PseudoBrain(IConverter converter)
    {
        _converter = converter;
    }

    // ...
}

This will allow for easier unit testing via mocking or writing and using new Converters.

Lastly, I have a bit of a squicky feeling when I see random number generators created over and over (as Think() will be called repeatedly). So I put that at the class level:

public class PseudoBrain
{
    private readonly Random _random = new Random();
    private readonly IConverter _converter;

    public PseudoBrain(IConverter converter)
    {
        _converter = converter;
    }

    public virtual string Think(string lastResult, int value)
    {
        var ai = _random.Next(0, 99);

        // ...
    }

    // ...
}


timing

Put the code to time the run time of the function outside of the function

augmented assignment

value = (value // i) can be expressed as value //= i

divisors

Why do you need to keep a list of divisors. They only as for the largest one. The largest one will always be the last one, so you just need to remember this

pep-8

your variable names are clear and in the correct format, apart from i. I would rename that to divisor or prime
The spacing around the operators and ( is inconsistent
the if i >= 3: i += 2 on one line is advised against

increments

    if i >= 3: i += 2 #when i is bigger than 3, search divisors among odd numbers( this reduces the search field)
    else: i += 1

can be simplified to i += (2 if i >= 3 else 1) or even i += 1 + (i >= 3), using the fact that int(True) is 1. But here you don't use the fact that your divisors are all primes. A quicker process would be to get the next possible divisor from a prime generator, instead of incrementing by 2 manually

while loop

You can integrate the if i == 1 : break into the condition for the while loop: while value % prime == 0 and value != 1:

def largest_prime_divisor(value):
    largest_divisor = 1
    for prime in prime_generator():
        while value % prime == 0 and value != 1:
            value //= prime
            largest_divisor = prime
    return largest_divisor

Possible implementations of prime_generator can be found in dozens of SO and Code review posts

shortcut

If the divisor is larger than the square root of the value, you know the next divisor will be the value itself, so you can shortcut when the divisor exceeds this

def largest_prime_divisor(value):
    largest_divisor = 1
    for prime in prime_generator():
        while value % prime == 0:
            value //= prime
            largest_divisor = prime
        if prime ** 2 > value:
            return max(largest_divisor, value)
    return largest_divisor


You can use .apply() which takes an array of arguments and those arguments will then be passed to the actual function as a series of normal arguments:

function funcoesOrcamento( funcao, args ){
  if(args)
    args = args.split("\!|");
  else
    args = [];

  return FuncoesOrcamentoV2[ funcao ].apply(this, args);
}

You can read more about .apply() here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply


Add a set of querystring params to a URL

Your code is very spaced out. It doesn't need to be.
Consider using industry-standard style by using Egyptian braces for control structures like if and foreach.
Get rid of the $http_host variable; you never use it.
Consider generalising your function to accept any URL instead of pulling REQUEST_URI.
You're kind of reinventing the wheel; PHP has the built-in functions parse_str and http_build_query that you can use.
Do you intend to replace existing variables, or just to append them to the request?

Here's an example that takes advantage of the built-in functions, and intelligently merges in conflicts. (ideone)

/**
 *  Like array_merge, but will recursively merge array values.
 *
 *  @param array $a1
 *      The array to be merged into.
 *  @param array $a2
 *      The array to merge in. Overwrites $a1, when string keys conflict.
 *      Numeric keys will just be appended.
 *  @return array
 *      The array, post-merge.
 */
function merge_query_var_arrays($a1, $a2) {
    foreach ($a2 as $k2 => $v2)
        if (is_string($k2))
            $a1[$k2] = isset($a1[$k2]) && is_array($v2) ? merge_query_var_arrays($a1[$k2], $v2) : $v2;
        else
            $a1[] = $v2;
    return $a1;
}

/**
 *  @param string $query_string
 *      The URL or query string to add to.
 *  @param string|array $vars_to_add
 *      Either a string in var=val&[...] format, or an array.
 *  @return string
 *      The new query string. Duplicate vars are overwritten.
 */
function add_query_vars($query_string, $vars_to_add) {
    if (is_string($vars_to_add))
        parse_str($vars_to_add, $vars_to_add);
    if (preg_match('/.*\?/', $query_string, $match))
        $query_string = preg_replace('/.*\?/', '', $query_string);
    parse_str($query_string, $query_vars);

    $query_vars = merge_query_var_arrays($query_vars, $vars_to_add);
    return @$match[0] . http_build_query($query_vars);
}


<script type="text/javascript">
$(function () {
    var $lastSelected = $([]);
    $('tr').click(function () { //tr tag is always inside a table
        $lastSelected.removeClass('selected'); //by caching this variable in the closure we don't need to traverse for it again
        $lastSelected = $(this).addClass('selected');
    });

    $('.image_bar a').click(function (e) {
        var url = $(this).attr('href').split('var'), //both checks if var is there and prepares for the replacement
            name;
        if ($lastSelected.length === 0) {
            return url.length==1; //any urls that do not have var in them will still work
        }

        name = $lastSelected.children().eq(2).html();
        window.location = url.join(name);
    });
});
</script>

Here I am assuming your toolbar is outside of your table.
About the changes:

$(function () { lets you move this script tag elsewhere in your document (perhaps to an external script)
By caching $lastSelected, fewer DOM traversals need to happen.
Knowing $lastSelected enables moving the $.fn.each call out of the tr click event by setting name inside of it.
Since the .each call is no longer in the click event, it can be a click event of its own (no more need to iterate over it).
Instead of modifying the a tags we can just set window.location since we are now in the event where the user has clicked.
Finally, if a row is not selected up front, the $lastSelected variable will not provide a valid name. Thus we shouldn't allow the link to be clicked if it contains var (done by the return statement).


Array even and odd indexes sorting and printing its values

It's a good idea to become familiar with all the methods on Array and Enumerable. It just so happens that Enumerable has a method called partition that has a purpose of dividing an array into .two parts (e.g. even and odd). It'll help tidy up your code.

So let's use partition on the array of chars and partition based on index.

parts = s.chars.partition.with_index{|_,i| i.even?}

Note since we are only using the index, the actual character is unimportant so I used _ instead of a variable name in the partition block.
Now you have two arrays of characters--let's join each array so that you have a single array with two strings:

strings = parts.map(&:join)

If you don't know about &:join it is a shortcut for {|a| a.join} (using Symbol#to_proc if you want to read up on it).

Then, finally print it. Note that in your code, you intermingle printing with manipulation. This is best avoided if you can; print only once you have things in final form.

print strings.join(' ')

The above could all be put together in one line if you'd rather:

print s.chars.partition.with_index{|_,i| i.even?}.map(&:join).join(' ')


PHP array with array value into multiple arrays with same key

Assuming you have the same number of items for each key, here are two alternative approaches:
Foreach:
<?php
$setParams = [
    'repeat_delay' => [23, 1],
    'repeat_type'  => ['Hour', 'Day'],
];

$i = 0;
foreach($setParams['repeat_delay'] as $k => $v) {
    $result[$i]['repeat_delay'] = $v;
    $result[$i]['repeat_type']  = $setParams['repeat_type'][$k];
    $i++;
}

Array map:
$result = array_map(null, ...array_values($setParams));
$keys   = array_keys($setParams);
$result = array_map(function($v) use ($keys) { return array_combine($keys, $v);}, $result);

Both result in $result holding the following:
array (
  0 =>
  array (
    'repeat_delay' => 23,
    'repeat_type' => 'Hour',
  ),
  1 =>
  array (
    'repeat_delay' => 1,
    'repeat_type' => 'Day',
  ),
)

You could rewrite the last array_map with the array_combine to:
$result = array_map(fn($v) => array_combine($keys, $v), $result);

Using a short arrow function for brevity.