DRY up ivar assignment in Rails new and create controller actions

Simplest thing would be to add a protected method to the controller and a matching before_filter/before_action callback:

Your actions become:

class ProjectsController < ApplicationController
  before_filter :load_select_options, only: [:new, :create]

  def new
    @project = Project.new
  end

  def create
    @project = Project.new(project_params)
    if @project.save
      flash[:success] = "#{@project.name} has been created."
      redirect_to @project
    else
      render :new
    end
  end

  protected

  def load_select_options
    @companies = Company.as_select_options
    @project_varieties = ProjectVariety.as_select_options
    @prices = Price.as_select_options
    @users = User.as_select_options
  end
end

If you have an edit action, add that to the before-filter's list too.

However, since you (presumably) only need to load all that stuff in create if you have to render the new template, you can skip the before filter, and instead do something more targeted:

class ProjectsController < ApplicationController
  def new
    @project = Project.new
    load_select_options
  end

  def create
    @project = Project.new(project_params)
    if @project.save
      flash[:success] = "#{@project.name} has been created."
      redirect_to @project
    else
      load_select_options
      render :new
    end
  end

  protected

  def load_select_options
    @companies = Company.as_select_options
    @project_varieties = ProjectVariety.as_select_options
    @prices = Price.as_select_options
    @users = User.as_select_options
  end
end


Conway's Game of Life Java Implementation

Bug 1

Your neighbor counting loops are only iterating twice instead of three times, so you aren't counting neighbors to the right or below.

Bug 2

If you were to correct Bug 1, your program would infinite loop in checkNeighbors because you modify your loop variables inside the loop when they wrap around.  So for example, if col is the rightmost column, you will set j to 0 inside the loop which will cause the j loop to never terminate.

Bug 3

You sometimes set your array elements to 2 or 3.  But in Life, each array element should be 0 or 1 only.  Your modifyElement function is incorrect.

Dead code

These two blocks of code are identical, so the second is useless:

                    if(i==row){
                        if(j==col){
                            continue;
                        }
                    }
                    if(j==col){
                        if(i==row){
                            continue;
                        }
                    }

Unused arguments

The changeState function has two unused arguments: row and col.


You should stick to variable names according to the python style guide, PEP8. This means using lower_case for variables and functions.

You could also use more descriptive names, for example roman instead of s.

The complicated checking you do with having 2-tuples and deciding on that can be circumvented by iterating over zip(numbers, numbers[1:]) to have both the number and the following number available at the same time. Still, we need to manually add the last digit at the end. Similar to the answer to this question I would propose to use something like:

def roman_to_int(roman):
    """Convert from Roman numerals to an integer."""
    values = {'M': 1000, 'D': 500, 'C': 100, 'L': 50,
              'X': 10, 'V': 5, 'I': 1}
    numbers = [values[char] for char in roman]
    total = 0
    for num1, num2 in zip(numbers, numbers[1:]):
        if num1 >= num2:
            total += num1
        else:
            total -= num1
    return total + num2


First of all, you have a possible bug in your code.

If trains is empty you will get a problem at the printing of the results.

Don't code that much inside the constructor. The constructor should be used for initializing only.
Be consitent in the way you create objects

ArrayList<Station> changeStation =new ArrayList<Station>();
ArrayList<Object> trains=new ArrayList<>();

If you need comments to describe a variable, you have named the variable poorly
Let your code breathe, use some spacing

for(int i=0;i<(path.size()-1);i++)

this would be easier to read like

for (int i = 0 ; i < path.size() - 1; i++)

use methods for calculations. You should add a method which calculates the shortest path and another one that would be responsible for the output of these calculated values.
code against interfaces instead of implementations so

ArrayList<Station> changeStation =new ArrayList<Station>();
ArrayList<Object> trains=new ArrayList<>();

should be

List<Station> changeStation =new ArrayList<>();
List<Lane> trains=new ArrayList<>();

Return from methods what the methodnames implies and name the "receiving" variable accordingly

Lane train=e.getLaneColor();

So the enum Lane should be become LaneColor and train should become e.g. currentLaneColor


In both this and your bubble sort implementation you need to start using C++ idioms (otherwise this is just C code (that's fine C is a great language it's just not C++)).

I would say this is the perfect C implementation of insertion sort.

But usually when you implement these kinds of algorithms in C++ you use iterators to specify the range (as this allows you to sort several types of container including arrays).

Rather than:

void insertionSort(int a[], int s) {

You should probably use:

template<typename I>
void insertionSort(I begin, I end) {

Then you can sort any type of container with:

int  a[] = {1,4,5,27,3,9,1};
insertionSort(std::begin(a), std::end(a));

std::vector<int> v = {1,4,5,27,3,9,1};
insertionSort(std::begin(v), std::end(v));

etc...

Interestingly this also allows you to sort any type (not just integers). As long as your type supports the comparison operator. The standard library tends to implement any comparison in terms of operator<() so to avoid confusion with potential users you should implement your sort using the less than operator and potentially allow the user to specify the actual comparison operator.

// Unless you have an explicit override.
// std::less<T> uses `operator<()` to do the comparison.
// So this means the algorithm will work for type T under three situations.
//    1) operator< is defined for the type T
//    2) There is an specialization of `std::less<>` for type T
//    3) An explicit type is provided to the sort for comparing type T.
template<typename I, typename Comp = std::less<T>>
void insertionSort(I begin, I end) {
    Comp   comp;
    // Stuff


Assuming the completely broken indentation is a paste glitch (right?), this bit hits me first:

catch (Exception e)
{
    _log.Error(e);
    Apple.Game.PlayerManager.DisposePlayer(_playerData.PlayerId);
}

If DisposePlayer does what it seems to be doing, then this looks like dangerous code that's begging for ObjectDisposedException to be thrown at another, unrelated point in time.

And if your logging framework ever gets configured to throw exceptions, and _log.Error(e); actually throws (IDK, error writing to log file for example), then DisposePlayer is never going to get called.

That's why disposal of resources should happen in a finally block.

catch (Exception e)
{
    _log.Error(e);
    disposePlayer = true;
}
finally
{
    if (disposePlayer)
    {
        Apple.Game.PlayerManager.DisposePlayer(_playerData.PlayerId);
    }
}

That way you know that that bit of code will run no matter what. I added a little bool disposePlayer local variable here, because a finally block will run whether an exception is caught or not, and you only need to call that method when an exception is effectively thrown.

I'm just not comfortable seeing an object being disposed by someone else than its creator, but you haven't given us enough code to chew on for me to expand on this point.

I think these two lines take up too much horizontal space:

int MessageLength = Apple.Encoding.DecodeInt32(new byte[] { packetData[packetPosition++], packetData[packetPosition++], packetData[packetPosition++] });
uint MessageId = Apple.Encoding.DecodeUInt32(new byte[] { packetData[packetPosition++], packetData[packetPosition++] });

I would be better to give it vertical height, so that the reader can more easily see how many times packetPosition is being incremented in the process:

int MessageLength = Apple.Encoding.DecodeInt32(new byte[]
{
    packetData[packetPosition++],
    packetData[packetPosition++],
    packetData[packetPosition++]
});
uint MessageId = Apple.Encoding.DecodeUInt32(new byte[]
{
    packetData[packetPosition++],
    packetData[packetPosition++]
});


Checking if a set of checkboxes have a certain number of options checked

Instead of using an array for names, you could use some implementation of a set, which automatically skips duplications; see here.

Instead of keeping the num variable, I would just check if errors is empty to set isValid.

Actually, you can combine both suggestions by replacing names by an object that stores the unique names associated with their respective error message (or null if it passes).

{"animals[]" : someErrorMessage,  "drinks[]" : null, "colors[]" : someOtherErrorMessage}

You would need to replace your for-loop by a for (name in names) and you would only check if there is not enough check marks and add an error if that's the case.

I played with your fiddle and made a fork:

(function($) {
    $.fn.isIncomplete = function(options) {

        var opt = $.extend({
            min: function() {
                return (min === 'undefined') ? 1 : min;
            }
        }, options);

        var $ckboxes = this;
        var names = {};

        $ckboxes.each(function() {
            names[this.name] = null;
        });

        var errors = [];
        for (name in names) {
            var $checked = $ckboxes.filter('[name="' + name + '"]:checked');
            if ($checked.length < opt.min) {
                isValid = false;
                var _remaining = opt.min - $checked.length;
                var _name = name.match(/\w+/).toString().replace(/^\w/, function($0) {
                    return $0.toUpperCase();
                });
                errors.push('<strong>' + _name + ':</strong> Check ' + _remaining + ' more.');
            }
        }

        if (errors.length == 0) return null;
        else return errors;
    };
})(jQuery);

// Testing...
$('button').click(function() {
    var incompleteErrors = $(':checkbox').isIncomplete({
        min: 1
    });
    if (incompleteErrors) {
        ul = $('<ul>');
        for (var i = 0; i < incompleteErrors.length; i++)
        ul.append($('<li>').html(incompleteErrors[i]));
        $("#errors").html(ul);
    } else {
        $("#errors").html("");
        alert('Passed!');
    }
});


Extract logic applied in a sequence of integers

I managed to simplify a pair of your functions:

countDelta

countDelta = map (\(x:xs) -> (length xs + 1, x))

In fact most of the logic in your countDelta was just reinventing map, so actually using map makes it much easier.

ShowTuples

(You named it printTuples but it does not print the tuples, printing to the screen is an action, while this function is pure, so I named it showTuples as show is conventionally used in Haskell when a String is the output)

import Data.List

showTuples = intercalate "+" . map (\(x, y) -> (show x ++ "x" ++ show y))

Here you were just putting "x" in between the two elements of each tuple and "+" in between the tuples. Half of the code was reinventing map, the other half intercalate using these built-ins makes the code much shorter and self-explanatory.

getSequenceLogic

A minor simplification only here: you can drop the [] case as the xs case already handles it correctly:

getSequenceLogic [x] = showTuples [(1,0)]
getSequenceLogic xs = showTuples (groupByDelta xs)


Retrieving my public IP address with the javascript Fetch API (no jquery, no json)

One of the main reasons Promises were created was to avoid the ugly nesting of callbacks when multiple asynchronous actions need to occur. For example, rather than

fn1(dataToSend, dataForFn2 => {
  fn2(dataForFn2, dataForFn3 => {
    fn3(dataForFn3, processedData => {
      console.log(processedData);
    });
  });
});

If the functions returned Promises instead of accepting callbacks, the above could be done with

fn1(dataToSend)
  .then(fn2)
  .then(fn3)
  .then(processedData => {
    console.log(processedData);
  });

The Promise-as-callback antipattern is when you nest .thens in other .thens or pass around callbacks rather than chaining another .then onto the previous Promise. This is the trap you're falling into here. Since fetch returns a Promise itself, it would be best to return that Promise and allow consumers of this script to use it. That is, it would be really convenient (and appropriate) if consumers to be able to do something like

get_ip(IP_URLs)
  .then(console.log)
  .catch(handleErrors);

Another related nesting issue you might consider is, instead of

if (goodCondition) {
  // lots of code
} else {
  callback("No more URLs");
}

Rather than having to keep track of which brackets correspond to what upper condition, it might be preferable to return early instead:

if (!goodCondition) {
  callback("No more URLs");
  return;
}
// lots of code

But if you return the Promises instead of using callbacks, this should cease to be an issue.

The init object you're constructing seems strangely complicated. Many of the properties you're passing are the default ones already (like method: 'get', redirect: 'follow') or useless (credentials: 'same-origin'). Unless you're deliberately trying to affect some things with the object, it would be simpler and less confusing to omit it entirely (the script looks to work just fine without it, none of the properties look useful).

You have a lot of fail-handlers. If you really want to exhaustively identify what's OK and what isn't, it would be good to also check if the response is OK too:

return fetch(url).then(
  response => {
    if (!response.ok) {
      console.log('Response was not OK:', response.status);
      return getIPFromNextSite(urls);
    }

But unless you're actively analyzing exactly which stage is working and what isn't, and really need all those .fail handlers, you might consider avoiding them and .catching errors at the end instead:

function getIPFromNextSite(urls) {
  if (!urls.length) {
    // Send control flow to the consuming .catch block:
    throw new Error('No more URLs');
  }
  const url = urls.pop();
  return fetch(url)
    .then(response => response.text())
    .then((txt) => {
      if (isValidIP(txt)) {
        // Send control flow to the consuming .then block:
        return txt;
      } else {
        return getIPFromNextSite(urls);
      }
    })
    .catch((err) => {
      return getIPFromNextSite(urls);
    });
}

It's only a comment in your code, but .slice does not deep copy arrays - it only shallow copies them. (Since the array here contains immutable strings, a shallow copy is fine anyway.)

If you want to follow the standard Javascript naming conventions, you could consider using camelCase for functions and most variables by default.

When declaring variables, best to always use const. Using let warns readers of the code that you may reassign the variable name, which results in more cognitive overhead (and is confusing if there isn't actually any chance of the name being reassigned).

In full, this is how I would do it:

const IP_URLs = [
  'https://api.ipify.org/',
  'https://ipecho.net/plain',
  'https://api.kwelo.com/v1/network/ip-address/my',
  'https://myexternalip.com/raw',
];
function getIPFromNextSite(urls) {
  if (!urls.length) {
    // Send control flow to the consuming .catch block:
    throw new Error('No more URLs');
  }
  const url = urls.pop();
  return fetch(url)
    .then(response => response.text())
    .then((txt) => {
      if (isValidIP(txt)) {
        // Send control flow to the consuming .then block:
        return txt;
      } else {
        return getIPFromNextSite(urls);
      }
    })
    .catch((err) => {
      return getIPFromNextSite(urls);
    });
}
function isValidIP(txt) {
  return /^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/.test(txt);
}
const getIP = urls => getIPFromNextSite(urls.slice());

getIP(IP_URLs).then(console.log);

  Should I have used async/await?

You could. If you need to exhaustively check every error path, it would require a lot of ugly try/catch boilerplate, but if you just want a result, it looks moderately cleaner than the version above:

const IP_URLs = [
  'https://api.ipify.org/',
  'https://ipecho.net/plain',
  'https://api.kwelo.com/v1/network/ip-address/my',
  'https://myexternalip.com/raw',
];
async function getIPFromNextSite(urls) {
  for (const url of urls) {
    try {
      const response = await fetch(url);
      const text = await response.text();
      if (isValidIP(text)) {
        // Send control flow to the consuming .then block:
        return text;
      }
    } catch(e) {
      // Don't do anything, just continue on to next iteration
    }
  }
  // Send control flow to the consuming .catch block:
  throw new Error('No more URLs');
}
function isValidIP(txt) {
  return /^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/.test(txt);
}
const getIP = urls => getIPFromNextSite(urls);

getIP(IP_URLs).then(console.log);


First attempt: Python Rock Paper Scissors

This code reads like beginner code. Good beginner code, but there are a few habits you're getting into that are systemic among beginners and will screw you over later down the line.

First, your function names are somewhat confusing. I would rename pickRando to computerChoice, combatCheck to game, and finish to something like printRecord. Once you do that, you shouldn't need the comments describing them. Comments are good, but shouldn't be used in lieu of descriptive names.

Second, avoid global variables. It will cause confusing issues later down the line, so please get into the habit of not using them. In order to avoid the global variables wins, losses, and ties, you would need to restructure a lot of code and it may not be worth it for this small of a code base. Exercise to the reader, I guess. But the other globals can easily be removed. I would change pickRando to

def computerChoice():
    return random.choice(options)

The concept behind the input check is good, but I would heavily modify the structure. Here's a better way to do that

while True:
    [...]
    print("Rock, Paper, Scissors:")

    playerChoice = input('choose wisely')
    while  not playerChoice in options:
        print "invalid input"
        playerChoice == input('choose wisely')
    print("Okay, you picked " + playerChoice + ' and I picked ' + computerChoice + '!')

This restructuring should make what it's actually doing clearer.

Next: the convertible method is a very good solution if you don't know about the built-in method index. You can change the combatCheck method to something like this.

a = options.index(a)
b = options.index(b)
return (a-b) % 3

I would also comment the last line with something more descriptive than modmath. I might say something like uses modular arithmetic to calculate results.

I like that you put combatCheck in its own function from the perspective of the teacher, because it shows that you use functions, but I think it's unnecessary here, because you only use that bit of code once and it's only a few lines.

You definitely have some really great foundations. Most of your mistakes are mistakes I made in my early days of Python, and I like to think I'm a pretty OK programmer. I think with practice and time, you'll turn into an amazing programmer.


Java Is my class file methods well written?

First and most important remark : do not use double or float to represent money. Use BigDecimal instead. And make a Money class that combines the amount with the currency. edit : it's also possible to use long or int, if you always calculate in cents, this would make a Money class even more useful, to hide away that implementation detail.
Think about rounding and precision. How many fractional digits can an annual rate have, how many can a monthly rate have...? How will you round if needed?
Don't hard code the values of the rates. If there's anything banks like to change it is their rates. :)
I would find it very odd if the date of the withdrawals and deposits did not matter in calculating the interests.
I'm not sure how NewWithdrawl and NewDeposit are supposed to get their values, from the posted code. As is these fields don't seem to make much sense, it feels like they want to be parameters of methods yet to be defined.
getWithdrawl() (sic) seems to do the same sort of operation as deposit(), yet the former is named as a getter method (while it isn't one) and the latter is not. Preferably they'd be named consistently.


Add to a variable multiple in cells variables

Utilizing the cache
The reason your function is so slow is because you are traversing your matrix by rows instead of by columns.  This means that every time you load a value from a new row, you are loading it from a different cache line, which is slow compared to reading nearby values (from the same row and cache line).
I modified your function to take the whole table as input and traverse it in linear fashion, reading all entries in one row before going to the next row.  Your program took 11 seconds, and mine took 1.2 seconds, for an almost 10x speedup.
Here are my changes:
int FindSumOfMinOfColumns(int **tab, int size)
{
    int *minVals = malloc(size * sizeof(*minVals));
    int  row     = 0;
    int  col     = 0;
    int  sum     = 0;

    // Initialize with 0th element of each column.
    memcpy(minVals, tab[0], size * sizeof(*minVals));

    // Compute the minimum of each column.
    for (row = 1; row < size; row++) {
        int *pRow = tab[row];
        for (col = 0; col < size; col++) {
            if (pRow[col] < minVals[col])
                minVals[col] = pRow[col];
        }
    }

    // Sum up the minimum of each column and return it.
    for (col = 0; col < size; col++)
        sum += minVals[col];
    free(minVals);
    return sum;
}

int main(void) {
    // ...

    t1 = RDTSC();
    for (z=0; z<10; z++) // pour avoir une moyenne du temps d'execution
        somme += FindSumOfMinOfColumns(tab, NB);
    t2 = RDTSC();

    // ...
}


Importing sleep as _sleep is an awkward work around. It'd be much easier to do a plain import time, then in your sleep function refer to time.sleep. No need for odd aliases and nothing gets overwritten.

This function does nothing:

def _handle_timeout(signum, frame):
    return
    signal.signal(signal.SIGALRM, _handle_timeout)
    signal.alarm(seconds)

It will immediately return, and the following two lines will never be executed.

If TIMEOUT can be set then it's not a constant, and it should instead be a class level variable. Place it directly after the class definition, then you can directly assign it easily without needing to resort to the global keyword. You also don't need to pass it as an argument to @timeout, you can just use NetworkStatus.timeout directly there.

class NetworkStatus(object):

    timeout = 2

In online you're returning if self.online(**kw) is True, but this is the same as returning self.online(**kw) already is True. And check only returns true or false. There's no reason to have two separate functions here at all, just rename the vague check function to is_online and you're returning a boolean directly from there. Then you also have offline which makes little sense. If you're concerned about readability, then if not network.is_online() is plenty readable without having a specific function.

Further down you also have if_online and if_offline... what are these wrappers for? They seem overly generic to achieve one small goal (only run a function if the network is online/offline. It'd make more sense to have these specific to the function, rather than passing the function as an argument. Did you have a lot of functions that needed this construct? It doesn't look like you've used it here.

I'd rename mainloop to just run, or run_test. mainloop is a generic name that tells us nothing. Also, no need to store the result in up. You can evaluate directly:

if self.is_online():

Now that I'm here I notice that you never passing any keyword arguments as kw**. Indeed you never use them, instead just using string literals:

socket.gethostbyname(kw.get('remote_server', 'www.google.com'))

This is very bad practice! Those values should be constants or class attributes. You should also remove all the unnecessary kw** parameters. Why let the user pass in values that'll never be used for anything?


Checking if an array is initialized and allocated in VB.NET

Option Strict

First thing first: Enable Option Strict please read : whats-an-option-strict-and-explicit

This will make your code less error prone. If you have enabled Option Strict you will see a warning on the line ElseIf inArray(0) Is Nothing Then that late binding is not allowed if using Option Strict On.

Regions

Please read are-regions-an-antipattern-or-code-smell

  Is there a good use for regions?

  No. There was a legacy use: generated code. Still, code generation
  tools just have to use partial classes instead. If C# has regions
  support, it's mostly because this legacy use, and because now that too
  many people used regions in their code, it would be impossible to
  remove them without breaking existent codebases.

  Think about it as about goto. The fact that the language or the IDE
  supports a feature doesn't mean that it should be used daily. StyleCop
  SA1124 rule is clear: you should not use regions. Never.

Hungarian notation

The parameter name inArray is a sign, that you are misusing the original intention. Please read this: what-is-the-benefit-of-not-using-hungarian-notation

And don't forget to read the reffered links.

That beeing said let us check how we could enhance this method by grouping the conditions together.

By using OrElse or AndAlsowe can short circuit conditions, which means that if a conditionA is true the conditionB won't be evaluated. like

If conditionA OrElse conditionB Then

End If

If we invert the conditions we can simplify the whole method to

Module Module2

    <Extension()>
    Public Function IsAllocated(ByVal inArray As System.Array) As Boolean

        Return Not ((inArray Is Nothing) OrElse (inArray.Length = 0) OrElse (inArray.GetValue(0) Is Nothing))

    End Function

End Module


Dynamic AuthorizeAttribute with database

Yes.
You are close, man!

You have to make relashionships between pairs of controller+action to some user actions.

For example:
Security Staff can only view Personal Info:
- View Personal

Then your HHRR Manager can:
- View Personal
- Add Personal
- Edit Personal

And finally HHRR Director he can do more actions like:

View Personal
Add Personal
Edit Personal
Delete Personl

And now in game you should include some extra tables, bro! hehehehehehe

Lets say your system has HHRR module.
Add this module record to the AccessModule table. Then add 3 records to AccessModuleActions like

HHRR Director
HHRR Manager
Security Staff

Apply ACL to each user via PersonalModuleActions table. Acctually you should use PersonalModuleActions at website admin GUI area.

And internally (no GUI for it) you will gonna use WebSiteAccessModuleActions table
where you keep relashionships between controller methods and those "roles".

This approach allows use

  1) Ignore methods that are not described in WebSiteAccessModuleActions

  2) Build very flexible ACL subsystem.

As you see we manipulate  kinda of groups of controller methods represented in
a user friendly manner

- HHRR Director
- HHRR Manager
- Security Staff

So when I said you are close it is just implement one more level of abstraction.

Enjoy, dude!

P.S. Include Area columnto the  WebSiteAccessModuleActions if you have
identical controller in several website's areas.


Replace HTML input file element with custom styled button

Your question

Is there any downside to this approach I don't see yet ? If so, what would be a better approach to do this ?

I don't really think there is a downside to this approach. Below I outline an alternative approach to updating the text - it may not necessarily be better but possibly more robust.
Feedback
This looks like a good approach - who needs the fakepath anyway??
I tested this code in Windows 10 Chrome, Firefox and Opera; Safari on Mac OS X, as well as FIrefox on Linux Mint. It appears to work in all except in Firefox on Linux Mint, where the output  tag text was not updated correctly. I was able to update the code to use Element.innerHTML for setting the HTML correctly.
Alternative approach
An alternate approach is to use String.split() on the file input value, splitting on \, then use Array.pop() to get the last item in the array. Expand the snippet below to see it in action.
In theory, this alternate approach should be quicker because it just uses string splitting and array access instead of a regular expression replacement... Here is a jsPerf test - so far it seems it is quicker to use the split() technique in FF and Edge on Windows but not Chrome...

var input = document.getElementById('input'),
  button = document.getElementById('button'),
  output = document.getElementById('output');

//route click event on styled button to the actual file input
button.addEventListener('click', function() {
  input.click();
}, false);

//display the name of the selected file
input.addEventListener('change', function() {
  console.log('val', input.value);
  var parts = input.value.split('\\');
  output.innerHTML = parts.pop();
}, false);
input[type="file"] {
  width: 1px;
  height: 1px;
  position: absolute;
  top: -10px;
  left: -10px;
}

button {
  width: 200px;
  height: 40px;
  cursor: pointer;
}

button,
#output {
  display: inline-block;
  vertical-align: middle;
}
<input type="file" id="input">

<button id="button">Upload image</button>


Assembly program which detects all numbers with two integral divisors

mov ecx, 0    ; Counts how many division have

This begs for an optimization in the form xor ecx, ecx. This will clear ECX just the same, is shorter and faster.

cmp edx, 0
jne prepareInnerIteration
inc ecx

Another optimization this time on compairing. To compare with zero, you can equally test the value with itself. So writing test edx, edx. This shortens the program.

goToNextIteration:
  cmp  esi, edi
  jl   outerLoop

Your code performs 1 iteration too many! Consider EDI=30 then this code will jump back to outerLoop when ESI=29, but there it will instantely be incremented to ESI=30 and so the code will superfluously process the case where the control variable = upper limit.

cmp  esi, 6            ; In case no number was given. Just a blank.
je   goToNextIteration

I don't see how this comment relates to the control variable being 6.
It just by-passes the output, which is wrong because the number 6 fulfills the conditions.

What I miss is a test for any user input smaller than 6

  call read_hex ; Reads in a hexadecimal number from stdin.
  cmp  eax, 6
  jl   ExitProg
  ...
ExitProg:
  push 0
  call [ExitProcess]

; ------ Usage example ----------------------
; The first "f" is the number n which was entered by the user.

; C:\Users\michael\Desktop\fasmProgs>divisors
; f
; 6
; 8
; a
; e
; f
; ------------------------------------------

This is a misleading comment! Since the premise states that the results are to be below the inputted number, the line ; f conflicts in the usage example given.


Calculate XOR of many consecutive and non-consecutive numbers

The problem with the code is that you are processing \$\sum _{ k=1 }^{ n }{ k } \$ (or \$1+2+3+(...)+n=\frac { n(n+1) }{ 2 }\$ ) integers. At most, you'll be processing 2 billion integers. A brute force method, such as the one you presented in your code, is inefficient and slow.

What you could do is take a different approach. Instead of XORing each integer, you could exploit a pattern that is present when XORing numbers. You exploit the pattern in each row, and then just XOR all the XOR sums you get from each processed row to get the checksum you need.

The XOR Pattern

Let us start by XORing numbers 0 to 3.

Obviously, XORing zero on its own gives us zero. Now, let's XOR 0 and 1 (0 ^ 1). We would get 1. XORing 0, 1, and 2 would give us 3. Lastly, XORing 0 to 3 would give us 0. Here's a visualization to make things simpler. Take note of the Output table.

0 => 0    0000 (0)    0000 (0)    0000 (0)        Output (0 to n)
        ^ 0001 (1)    0001 (1)    0001 (1)        -----------------
        ----------  ^ 0010 (2)    0010 (2)        (0 to 0) 0000 (0) # Equals to n
          0001 (1)  ----------  ^ 0011 (3)        (0 to 1) 0001 (1)
                      0011 (3)  ----------        (0 to 2) 0011 (3) # Equals to n + 1 (2 + 1)
                                  0000 (0)        (0 to 3) 0000 (0)

Let's now try XORing from 4 to 7. XORing 0 to 4 gives us 4. 0 to 5 gives us 1 (noticed anything yet?). 0 to 6 gives us 7. And lastly, 0 to 7 gives us 0.

  0000 (0)    0000 (0)    0000 (0)    0000 (0)    Output (0 to n)
  0001 (1)    0001 (1)    0001 (1)    0001 (1)    ---------------
  0010 (2)    0010 (2)    0010 (2)    0010 (2)    (0 to 4) 0100 (4) # Its' equal to n! (<= not a factorial)
  0011 (3)    0011 (3)    0011 (3)    0011 (3)    (0 to 5) 0001 (1) # Here goes this one again!
^ 0100 (4)    0100 (4)    0100 (4)    0100 (4)    (0 to 6) 0111 (7) # And it's equal to n + 1
----------  ^ 0101 (5)    0101 (5)    0101 (5)    (0 to 7) 0000 (0) # And this zero.
  0100 (4)  ----------  ^ 0110 (6)    0110 (6)
              0001 (1)  ----------  ^ 0111 (7)
                          0111 (7)  ----------
                                      0000 (0)

Have you noticed the pattern? It's right in front of you! We could definitely see that the pattern repeats every 4 numbers. Inferring from our output table, XORing to 0 and every fifth number would give us the fifth number; XORing to 1 and every sixth number would give us 1; XORing to 2 and every seventh number would give us 2 and the every seventh number plus one; and, XORing to 4 and every eigth number would give us 0.

From there, we easily get a pattern of n, 1, n + 1, 0. This also proves 200_success's answer where XORing to every fourth number (we're starting from 0) gives us 0.

Now that we have a pattern, we just need to create a function that will get the XOR sum from 0 to n. For this answer, let's call the function, f(). I'll leave the implementation to you as that is part of the challenge. We start at zero because the pattern starts at zero and could break if we start somewhere else. To get the XOR from a range (a to b), we just do f(b) ^ f(a - 1). Why it works? Read on.

Why Does \$f(b) \oplus f(a - 1)\$ Work?

The simple answer is that \$f(a - 1)\$ cancels out \$0 \oplus (...) \oplus (a - 1)\$ from \$f(b)\$ which is just \$0 \oplus (...) \oplus b\$.

Proof on why \$a \oplus (a + 1) \oplus (...) \oplus (b - 1) \oplus b = f(b) \oplus f(a - 1)\$

First of all, remember that XOR operations are associative, commutative, and reversable.

Let

$$n = a \oplus (a+1) \oplus (...) \oplus (b-1) \oplus (b) = 0$$

where \$a, b \in Z^{+}\$ and \$ a < b \$. \$n\$ is the XOR sum from \$a\$ to \$b\$.

Let us have a function \$f(b)\$ that gets the XOR sum from \$0\$ to \$b\$.

$$f(b) = 0 \oplus 1 \oplus 2 \oplus (...) \oplus b$$

Since \$a\$ is less than \$b\$ and XOR operations is associative, we can safely assume that

$$f(b) = (0 \oplus 1 \oplus (...) \oplus (a-1)) \oplus (a \oplus (a+1) \oplus (...) \oplus b)$$

Since \$(0 \oplus 1 \oplus (...) \oplus (a-1))\$ is equal to \$f(a-1)\$, and \$(a \oplus (a+1) \oplus (...) \oplus b)\$ is equal to \$n\$, we can simplify the equation above to

$$f(b) = f(a-1) \oplus n$$

Finally, since XOR operations are reversable, we get

$$n = f(a-1) \oplus f(b)$$

Through the commutative property of XOR operations, we finally get

$$n = f(b) \oplus f(a-1)$$

After getting the XOR sum of each row using f(b) ^ f(a - 1), we XOR all the XOR sums from each row, and we get the checksum that the problem requires.

Using the method I mentioned above, I can process answer(0, 50000) in approximately 0.08 seconds on my laptop with a Core i3 processor, and 4GB RAM.

Side note: These questions (1 and 2) can help you as well. I used the answers in those questions as a source for this answer, and in solving the same problem a few days ago (relative to writing this answer).


Avoid Split to reduce memory press (on servers)

You basically have 3 other possibilities

Using Split() like you did, but different

Private Const CommaOUEqual As String = ",OU="
Friend Shared Function GetOrganization(dn As String) As String
    Return dn.Split({CommaOUEqual}, StringSplitOptions.None)(2)
End Function

Using IndexOf() similiar like you did, nut without Split()

Private Const CommaOUEqual As String = ",OU="
Friend Shared Function GetOrganization(dn As String) As String
    Dim index As Integer = dn.IndexOf(CommaOUEqual) + 4
    index = dn.IndexOf(CommaOUEqual, index) + 4
    Return dn.Substring(index, dn.IndexOf(CommaOUEqual, index) - index)
End Function

Using Regex

Private Shared regex As Regex = New Regex(",OU=(.+?),OU=(.+?),OU=", RegexOptions.Compiled)
Friend Shared Function GetOrganization(dn As String) As String
    Return regex.Match(dn).Groups(2).ToString()
End Function

Timing these 3 methods together with the 2 methods fromn you results after 500.000 iteration in

  yours

  ~340 ms (Split())
  ~330 ms (IndexOf() + Split())

  mine

  ~460 ms (Split())
  ~250 ms (IndexOf())
  ~900 ms (Regex)

So in the worst case for assuming 5.000.000 calls in 24 hours this will result for the worst case in 9 seconds and for the best case in 2.5 seconds.

But this are still only micro gain in performance.

But wait, we can do faster

Friend Shared Function GetOrganization(dn As String) As String
    Dim firstHit As Boolean = False
    Dim secondHit As Boolean = False
    Dim startIndex As Integer = 0
    For i As Integer = 6 To dn.Length - 3
        If dn.Chars(i) = "="c AndAlso dn.Chars(i - 1) = "U"c AndAlso dn.Chars(i - 2) = "O"c Then
            If Not secondHit AndAlso firstHit Then
                startIndex = i + 1
                secondHit = True
                Continue For
            End If
            If secondHit Then
                Return New String(dn.ToCharArray(startIndex, i - startIndex - 3))
            End If
            firstHit = True
        End If
    Next
    Return String.Empty
End Function

This will run for 500.000 iterations in

  ~70 ms

Using

Return dn.Substring(startIndex, i - startIndex - 3)

instead of

Return New String(dn.ToCharArray(startIndex, i - startIndex - 3))

will improve the speed to about

  ~60 ms

if you need to parse more than one item of the given string we should use this to its own class and remove the Shared.

Friend Class ParsedLDAP
    Friend Enum LDAPComponent
        OU = 1
        DC = 2
        CN = 4
        ALL = 7
    End Enum
    Public Property CommonNames As IList(Of String)
    Public Property OrganisationalUnits As IList(Of String)
    Public Property DomainComponents As IList(Of String)
    Private Sub New()
        CommonNames = New List(Of String)
        OrganisationalUnits = New List(Of String)
        DomainComponents = New List(Of String)
    End Sub
    Public Sub New(dn As String)
        Me.new(dn, LDAPComponent.ALL)
    End Sub
    Public Sub New(dn As String, parseComponent As LDAPComponent)
        Me.New()
        ParseString(dn, parseComponent)
    End Sub

    Private Const reversedOU As String = "UO"
    Private Const reversedDC As String = "CD"
    Private Const reversedCN As String = "NC"
    Private Const equalSign As Char = "="c
    Private Sub ParseString(dn As String, parseComponent As LDAPComponent)
        Dim isNotOU As Boolean = ((parseComponent And LDAPComponent.OU) <> LDAPComponent.OU)
        Dim isNotDC As Boolean = ((parseComponent And LDAPComponent.DC) <> LDAPComponent.DC)
        Dim isNotCN As Boolean = ((parseComponent And LDAPComponent.CN) <> LDAPComponent.CN)

        If (isNotOU AndAlso isNotDC AndAlso isNotCN) Then Return

        Dim currentComponent As LDAPComponent
        For i As Integer = 2 To dn.Length - 1
            If dn.Chars(i) <> equalSign Then Continue For

            Dim startIndex As Integer = i + 1
            Select Case dn.Chars(i - 1)
                Case reversedOU.Chars(0)
                    If isNotOU Then Continue For
                    If dn.Chars(i - 2) <> reversedOU.Chars(1) Then Continue For
                    currentComponent = LDAPComponent.OU
                Case reversedDC.Chars(0)
                    If isNotDC Then Continue For
                    If dn.Chars(i - 2) <> reversedDC.Chars(1) Then Continue For
                    currentComponent = LDAPComponent.DC
                Case reversedCN.Chars(0)
                    If isNotCN Then Continue For
                    If dn.Chars(i - 2) <> reversedCN.Chars(1) Then Continue For
                    currentComponent = LDAPComponent.CN
                Case Else
                    Continue For
            End Select

            While (i < dn.Length - 1 AndAlso dn.Chars(i + 1) <> equalSign)
                i += 1
            End While

            If i = dn.Length - 1 Then i += 3 ' This is needed, because otherwise the last item can't be found

            Dim currentValue As String = dn.Substring(startIndex, i - startIndex - 2)
            Select Case currentComponent
                Case LDAPComponent.OU
                    OrganisationalUnits.Add(currentValue)
                Case LDAPComponent.DC
                    DomainComponents.Add(currentValue)
                Case LDAPComponent.CN
                    CommonNames.Add(currentValue)
            End Select

        Next
    End Sub
End Class

Because I assume that you maybe have millions of calls where you need e.g the desired OU but for a much smaller number of distinct dn's I would suggest to store the results in a Dictionary(Of String, ParsedLDAP) to first lookup if the dn has been parsed by calling Dictionary(Of TKey,TValue).TryGetValue().


Increment the neighbors of a cell in a matrix

Like Simon I would store the directions into a data structure, though I would probably hard code it

//Array Index Constants
var X = 0 , Y = 1;
//All 8 neighbours ( vectors )
var vectors = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]];

The fun thing about JavaScript is that there is no ArrayIndexOutOfBoundsException in JavaScript, requesting a value out of bounds returns undefined.

So, now, you can go for

for( int i = 0 ; i < vectors.length ; i++ ){
  var vector = vectors[i];
  if( m[x+vector[X]] && m[x+vector[X]][y+vector[Y]] !== undefined )
    m[x+vector[X]][y+vector[Y]]++;
}

I did use for m[x+vector[X]] a falsey comparison, if the row X was defined it would pass the falsey evaluation ( it would be an Array ). For m[x+vector[X]][y+vector[Y]] I compared to undefined, since 0 is a realistic, acceptable value which would evaluate as false.

If I had to do a lot of matrix magic, then I would have a dedicated function to check whether a point is part of the matrix. And a dedicated function to add a vector to a point.


You need a way to specify how the message will be transformed into a sequence, therefore your function should be typed as Func<string, IEnumerable<string>>. And the lambda expressions would look like this:

x => x.Split(' ')
x => x.Select(c => new string(c, 1))

But why pass a delegate for the split-algorithm instead of simply passing the sequence of text pieces directly?

public IEnumerator TypeWordText(IEnumerable<string> pieces, message, Text textComp,
                                bool resetTextComp = false, string separator = "")
{
    if (resetTextComp)
        textComp.text = "";

    foreach (string piece in pieces)
    {
        textComp.text += separator + piece;

        if (textComp.text.Length >= message.Length)
            OnMessageTyped(message);

        yield return new WaitForSeconds(2f);
    }
}

Since in one method you add a space and not in the other, I have added the separator as optional parameter.

I also suggest to transform the char-sequence into a string-sequence (with strings of length one), so that you can always work with strings.

TextTyper.TypeText(message.Split(' '), message, vanishText, true, " ")

TextTyper.TypeText(message.Select(c => new string(c, 1)), message, vanishText, true)

Note that a string is an IEnumerable<char>. The Selects will be executed lazily at each loop of the foreach-statement. Therefore, in a certain way, you are still passing an algorithm to the method in the second call, but hidden in an enumerator.

Algorithm: But why split the string at all, just in order to recombine it afterwards? Instead of splitting the message, you could keep it as is and keep track of the typed length in an int variable. Then display message.Substring(0, typedLength). This change requires a strategy for the increment of the typed length. See Strategy pattern.

public interface ITypingStrategy
{
    void TypeNext(string message, ref typedLength);
}

Now you can implement different strategies like CharByCharTypingStrategty or WordByWordTypingStrategy as classes. The adapted TypeWordText method would have an ITypingStrategy argument instead of an enumeration of text pieces.


It's a duplicate of Ansible - Use default if a variable is not defined

version: "{{ ver | default('default_version') }}"

To use default_version in case ver is empty

- set_fact:
    version: "{{ default_version }}"
  when: ver == ""

or (Ansible Galaxy warning-free option)

  when: ver | length > 0


Showing or hiding groups of three text fields

What problem are you trying to solve? I've left your code doing the same things but rather than interrogate the DOM each time I've cached everything in local variables.

// Execute code in an Immediately Invoked Function Expression (IIFE)
// This helps stop your variables polluting the global scope.
(function () {

    // opt in to ECMAScript 5's strict mode
    "use strict";

    // As we aren't changing the DOM just store all of the selectors in
    // local variables - it's cheaper than hitting the DOM each time.
    var inputRow1 = $('#inputRow1').hide(),
        inputRow2 = $('#inputRow2').hide(),
        addRowLink = $('#add-more'),
        removeRowLink = $("#remove-last").hide(),
        // rather than checking the DOM for number of hidden children,
        // just keep track of the last row visible (0, 1 or 2)
        lastRowVisible = 0;

    addRowLink.click(function(event) {
        // stop the default action of the click event.
        event.preventDefault();

        // This is the initial state with only the first 3 input boxes showing
        // we need to show row 1 and the remove last link as well as increment the
        // last row visible to 1.
        if (lastRowVisible === 0) {
            removeRowLink.show();
            inputRow1.show();
            ++lastRowVisible;
        // The first two rows are visible. Show the last row and hide the add-more
        // link as well as increment the last row visible to 2.
        } else if (lastRowVisible === 1) {
            addRowLink.hide();
            inputRow2.show();
            ++lastRowVisible;
        }
    });

    removeRowLink.click(function(event){
        // stop the default action of the click event.
        event.preventDefault();

        // All 3 rows currently visible: need to hide the last row, show
        // the add-more link and decrement the last row visible to 1.
        if (lastRowVisible === 2) {
            addRowLink.show();
            inputRow2.hide();
            --lastRowVisible;

        // 2 rows currently visible: need to hide the second row and the
        // remove-last link and decrement the last row visible to 0.
        } else if (lastRowVisible === 1) {
            removeRowLink.hide();
            inputRow1.hide();
            --lastRowVisible;
        }
    });
}());

Here's a working fiddle: http://jsfiddle.net/RobH/CDVBs/1/

Have you considered a solution that starts with only 3 inputs and then creates extra inputs instead of showing ones that are already declared but hidden?


contents <- fmap tail . fmap lines . readFile $ "testInput"

can be written as

contents <- (tail . lines) <$> readFile "testInput"

Here we take advantage of the law fmap f . fmap g == fmap (f . g). <$> is an infix version of fmap. $ is extraneous here.

let input = map pair_to_tuple .(map (map read)) . map words $ contents :: [(Int,Int)]

can be written as

let input = map (pair_to_tuple . (map read) . words) contents :: [(Int,Int)]

For lists map = fmap, so map f . map g == map (f . g) also holds.

In

let result = map (uncurry waffles) $ input

the $ sign is also extraneous.

let decorated_result = ["Case #" ++ show i ++ ": " ++ show s | (i,s) <- zip [1..length result] result]

You can exploit Haskell's lazy evaluation and create infinite list to zip with:

let decorated_result = ["Case #" ++ show i ++ ": " ++ show s | (i,s) <- zip [1..] result]

Otherwise I'd say the code is fine.


Understanding interface with animal classes

Your example accesses the cat through a variable of type Cat and the dog through Dog. This would work, even if both classes did not implement a common interface. Inheritance is not involved.

In order to really demonstrate the usefulness of polymorphism I suggest the following code:

interface IAnimal
{
    string Name { get; set; }
    string Cry();
}

class Dog : IAnimal
{
    public string Name { get; set; }
    public string Cry()
    {
        return "Woof!";
    }
}

class Cat : IAnimal
{
    public string Name { get; set; }
    public string Cry()
    {
        return "Meow!";
    }
}

And here is a possible test:

static void Main(string[] args)
{
    var animals = new List<IAnimal>();

    animals.Add(new Dog { Name = "Robby" });
    animals.Add(new Dog { Name = "Fify" });
    animals.Add(new Cat { Name = "Mimy" });

    PrintAnimals(animals);

    Console.ReadKey();
}

private static void PrintAnimals(IEnumerable<IAnimal> animals)
{
    foreach (IAnimal animal in animals) {
        Console.WriteLine("Here is {0}: {1}", animal.Name, animal.Cry());
    }
}

It demonstrates that different types of animals can be treated the same way, but behave differently. This is what polymorphism is about. The word means many (poly) shapes or forms (morph). You can add different types of animals to a collection.

The PrintAnimals method has a parameter of type IEnumerable<IAnimal> allowing you to pass it different types of collections (arrays, lists, linked lists, stacks and many more, as yet another example of polymorphism). It uses a unique Console.WriteLine statement for all types of animals, without even knowing of which type an animal really is. The only thing it knows is, that it implements IAnimal. You could even add new types of animals later, without having to change the PrintAnimals method and it would still work as expected.


In your ReadStar1 method I assume your forgot the brackets around the if (readtxt == "star1") block? Right now you always collapse visibility of star1_1.
Your ReadStar1 and ReadStar2 methods share lot of code and should be refactored into one method. The only real difference is which file you read and what you do if you read a specific string. Pass in what you want to read and remove the concern of what should happen if you do read it by returning a bool indicating whether the string was found (the purpose of the method should be to determine if a certain file contains a certain string):

private async Task<bool> StarExists(string star)
{
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

    if (local != null)
    {
        var dataFolder = await local.GetFolderAsync("level");
        var file = await dataFolder.OpenStreamForReadAsync(star + ".txt");
        string readtxt;
        using (StreamReader streamReader = new StreamReader(file))
        {
            readtxt = streamReader.ReadToEnd();
        }

        return readtxt == star;
    }
    return false;
}

private async void CheckLevels()
{
    var hasStar1 = await StarExists("star1");
    var hasStar2 = await StarExists("star2");

    if (hasStar1)
    {
        star2_lock.Visibility = Visibility.Collapsed;
        star1_1.Visibility = Visibility.Collapsed;
    }

    if (hasStar2)
    {
        star3_lock.Visibility = Visibility.Collapsed;
    }
}

Then your constructor becomes:

public MainMenu()
{
    InitializeComponent();
    CheckLevels();
}

If you use strings like "star1" and "star2" in multiple places then consider making them public const fields of a class rather than sprinkling string literals around everywhere. If you ever decide to change them you will have to change a lot less code.


you can split up the calculation in your for loop into threads and sum up the results afterwards: here an example for 4 Threads: Use as many Threads as you have CPUs. It's important to add the result inside a synchronized block, otherwise you result could be corrupted by race conditions. I get a speed up of 50% with 4 threads compared to a single core execution.

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class CalculateE {

    static long start1 = System.currentTimeMillis();

    static BigDecimal result = BigDecimal.ONE;

    public static BigDecimal factorial(int x) {
        BigDecimal prod = new BigDecimal("1");
        for (int i = x; i > 1; i--) {
            prod = prod.multiply(new BigDecimal(i));
        }
        return prod;
    }

    public static Runnable getRunner(final int from, final int to) {
        Runnable runner = new Runnable() {
            @Override
            public void run() {
                BigDecimal e = BigDecimal.ZERO;
                for (int i = from; i < to; i++) {
                    e = e.add(BigDecimal
                            .valueOf(Math.pow(3 * i, 2) + 1)
                            .divide(factorial(3 * i),
                                    new MathContext(10000, RoundingMode.HALF_UP)));
                }
                addResult(e);
            }
        };
        return runner;
    }

    public static synchronized void addResult(BigDecimal e){
        result = result.add(e);
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable r1 = getRunner(1, 251);
        Runnable r2 = getRunner(251, 501);
        Runnable r3 = getRunner(501, 751);
        Runnable r4 = getRunner(751, 1000);
        Thread t1 = new Thread(r1);
        t1.start();
        Thread t2 = new Thread(r2);
        t2.start();
        Thread t3 = new Thread(r3);
        t3.start();
        Thread t4 = new Thread(r4);
        t4.start();
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        System.out.println("e = " + result);
        long stop = System.currentTimeMillis();
        long diff = stop - start1;
        System.out.println(diff + " ms");
    }

}


Fastest way to create random pixel image

You can write arrays of Integers directly on the WritableRaster of the BufferedImage:
public static BufferedImage createRandomImage(final int width, final int height) {
    final BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    final long bytesPerPixel = 4L;

    final int[] pixelData = new SplittableRandom().ints(bytesPerPixel * width * height, 0, 256).toArray();

    result.getRaster().setPixels(0, 0, width, height, pixelData);

    return result;
}

This performs more than three times faster on my machine in a very crude benchmark (3.92S vs 1.26S), with the caveat that for very big images like the one you desire, you have a lot of data duplication, because you basically have to allocate twice the amount of memory, since you're writing the random data to a buffer first.
This can easily be solved by writing arrays of random Integers line by line though, which nets comparable performance:
public static BufferedImage createRandomImage(final int width, final int height) {
    final BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    final long bytesPerPixel = 4L;

    for (int y = 0; y < height; y++) {
        final int[] pixelData = new SplittableRandom().ints(bytesPerPixel * width, 0, 256)
                                                      .toArray();

        result.getRaster().setPixels(0, y, width, 1, pixelData);
    }

    return result;
}

BufferedImage.setRGB is very slow, because for every pixel you set, it has to go fetch the corresponding data element:
public void setRGB(int x, int y, int rgb) {
    raster.setDataElements(x, y, colorModel.getDataElements(rgb, null));
}

which is a comparatively heavy operation.

Parallelization
Crude parallelization improves performance slightly, but it does not scale linearly with number of cores. On my 24 thread machine, the following yields a 30-40% improvement compared to the loop WritableRaster variant:
public static BufferedImage createRandomImage(final int width, final int height) {
    final BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    final long bytesPerPixel = 4L;

    IntStream.range(0, height).parallel().forEach(y -> {
        final int[] pixelData = new SplittableRandom().ints(bytesPerPixel * width, 0, 256)
                                                      .toArray();
        result.getRaster().setPixels(0, y, width, 1, pixelData);
    });

    return result;
}


I'm going to assume that search returns a data structure like this:

data = [
  { 'ArtistName' => 'Crash Test Dummies',
    'AlbumName' => 'God Shuffled His Feet',
    'SongName' => 'Mmmm_Mmmmm...',
  },
  { 'ArtistName' => 'John Powell',
    'AlbumName' => 'How to Train Your Dragon',
    'SongName' => 'Test Drive',
  },
  …
]

In that case, using song_hash as the name of the parameter to view_song_search is misleading, since it's actually an array.

There's no reason why view_song_search needs to know anything about songs, or why it should be tied to artists, albums, and songs at all.  You should write a generic table-formatting function, like this:

puts table(data, [['ArtistName', 'Artist'],
                  ['AlbumName', 'Album'],
                  ['SongName', 'Song']])

Here's an implementation of such a function.  Remarks:

A large chunk of the code is the block in the middle to shrink overwide tables.  I've tried to scale each column proportionally instead of giving one-third to each column.
The heading row resembles a data row in many ways, and should be handled using a common codepath.
The horizontal rules are printed many times; build it just once.
Use sprintf '%-*s', width, text to space-pad the text to the desired width.

def table(hashes, headings, width_limit=%x'tput cols'.to_i - 5)
  attrs = headings.map { |h| h.first }
  headings = Hash[headings]

  # Minimum widths to accommodate the heading and data of each column,
  # excluding leading space, trailing space, and vertical dividers
  col_widths = attrs.map do |attr|
    [headings[attr].size, hashes.map { |h| h[attr].size }.max].max
  end

  # If the desired width, including delimiters, exceeds the limit,
  # reduce column widths proportionally
  desired_width = col_widths.inject(:+) + 3 * col_widths.size + 1
  if desired_width > width_limit
    col_widths.each_with_index do |width, c|
      col_widths[c] = (width.to_f * width_limit / desired_width).to_i - 2
    end

    # Readjust last column for round-off errors
    desired_width = col_widths.inject(:+) + 3 * col_widths.size + 1
    col_widths[-1] += width_limit - desired_width
  end

  output = hrule = '+' + col_widths.map { |width| '-' * (width + 2) + '+' }.join
  ([headings] + hashes).each_with_index do |row, r|
    output += "\n"
    output += "\e[7m" if r == 0         # Highlight heading row
    output += '|'
    attrs.each_with_index do |attr, c|
      output += sprintf(' %-*s |', col_widths[c], row[attr][0...col_widths[c]])
    end
    output += "\e[0m" if r == 0         # Turn off highlight
    output += "\n" + hrule
  end
  output
end


I think you're overcomplicating it. Typically, I think Less users just write the media queries inline with a variable. As in:

@tablet-min: ~"only screen and (min-width: 768)";

element {
  overflow: visible;

  @media @tablet-min {
      overflow: hidden;
  }
}


Bootstrap show many move one carousel modification

Thanks for looking at this. I have concluded that I am happy with the code.

To incorporate the valid suggest by @vmariano, I have split this off into its own variable. This does make sense from a best-practices viewpoint as once I clone the item it is no longer itemToClone it is a clonedItem.

Final code:

(function(){
  $('.carousel-showmanymoveone .item').each(function(){
    var itemToClone = $(this);

    for (var i=1;i<4;i++) {
      itemToClone = itemToClone.next();

      // wrap around if at end of item collection
      if (!itemToClone.length) {
        itemToClone = $(this).siblings(':first');
      }

      // grab item, clone, add marker class, add to collection
      var clonedItem = itemToClone.children(':first-child').clone();
      clonedItem.addClass("cloneditem-"+(i))
         .appendTo($(this));
    }
  });
}());


Returning the results of four $resource calls as a JSON array in AngularJS

Never, and I mean NEVER, manually construct JSON. That's just asking for trouble. Construct the object then use JSON.stringify. FYI, arrays are valid JSON so you can construct an array and pass it to JSON.stringify.

Next, it doesn't seem like your calls  depend on each other. You can just launch them all in parallel and use Promise.all (or Angular's equivalent API) listen to know when all of them have resolved. The resolved value is an array of values in the same order as the promises. That guarantees that the first call's result is the first item in the resolved value.

Lastly, since you're already using promises, just return a promise from your function. Using callbacks in the presence of a promise defeats the entire purpose of promises.

One more thing, just pointing out that you are returning JSON, a string, from getAllEvents and not an object. Not sure why you're doing that exactly, but if you aim to get the object for manipulation, you can skip that part.

const resource = $resource('/app/data/event/:id/:ext', {id:'@id',ext:'@ext'}, {"getAll": {method: "GET", isArray: false}})

getAllEvents(){
  const promise1 = resource.get({ id: 1, ext: '.json' }).$promise
  const promise2 = resource.get({ id: 2, ext: '.json' }).$promise
  const promise3 = resource.get({ id: 3, ext: '.json' }).$promise
  const promise4 = resource.get({ id: 4, ext: '.json' }).$promise

  return $q.all([ promise1, promise2, promise3, promise4 ])
}

// Usage
someService.getAllEvents().then(values => {
  // values[0] = your first file
  // values[1] = your second file
  // values[2] = your third file
  // values[3] = your fourth file
});


This strikes me as somewhat...clumsy code that makes the job more difficult than truly necessary.

I'd break the task up into pieces, something like:

for every candidate position in the haystack
    if the needle matches at this point
        return success at this point
return failure

So that leaves us with two subordinate tasks:

Figure out the candidate positions
Check for a match starting at a specified point

The first is pretty simple: the candidate positions are the beginning of the haystack through the length of the haystack minus the length of the needle (and if the needle is larger than the haystack, it can't possibly match).

The second is even simpler: step through both strings, and if they don't match at a given point, return indicating failure. If (and only if) you reach the end of the second without a mismatch, return indicating success.

So let's write some code for that:

size_t length(char const *s) {
    size_t i;
    for (i = 0; s[i]; i++)
        ;
    return i;
}

bool match(char const *a, char const *b) {
    while (*b)
        if (*a++ != *b++)
            return false;
    return true;
}

Then we can do the function itself:

char const *find_substr(char const *haystack, char const *needle) {
    size_t len1 = length(haystack);
    size_t len2 = length(needle);

    for (size_t i = 0; i+len2<=len1; i++)
        if (match(haystack + i, needle))
            return haystack + i;
    return NULL;
}

Then we probably want a bit of test code to verify that it works to at least some degree under some circumstances:

char const *check(char const *s) {
    if (s)
        return s;
    return "[NULL POINTER]";
}

#define elements(arr) (sizeof(arr)/sizeof(arr[0]))

int main() {
    char input1[] = "This is some input for the function";

    // tests: match middle, non-match, match begin, match end, empty string
    char const *tests[] = { "for", "was", "This", "ion", "" };

    for (size_t = 0; i < elements(tests); i++)
        printf("%s\n", check(find_substr(input1, tests[i])));

    printf("%s\n", check(find_substr("the", "this is a longer string")));
}

There are certainly other ways the job could be done, but that seems to me like it's at least a reasonable way to implement what's probably the simplest (and most naive) one.


Well, the first thing I would recommend is replacing all of those println statements with some kind of logging. In any kind of production environment, logging is something that needs more thought and care so that it is useful, without consuming resources unnecessarily. Or, if they're just for the original developer during development, maybe delete them.

I find the structure of this code to be rather odd. For all the trappings of OO programming, what you essentially have is two global public functions and one global public variable.

The function name setQ doesn't seem to say what you're actually doing - which appears to be creating a channel and publishing a message to it. publishMessage would make more sense, I think.

All of the code that checks the usability of the connection should be extracted into a single function, something along the lines of haveUsableConnection - the two if/else blocks are making it hard to see the code that is actually doing the work.

I question the hard coded IP address. Magic numbers and magic strings are frequently a bad idea.


You are combining an IQueryable with a local sequence, dates. It is possible to do that, but Entity Framework1 needs a lot of code to convert the sequence into something that behaves like a SQL table. I'm sure this is a major performance killer.

From what I see, you can do without this local sequence. You know the begin and end date. So it's possible to get the forecasts between those dates. If you group those forecasts by their Date, you achieve the same grouping:

from r in context.StaffingResourceDatas
where r.EmployeeId != null && !exclusionList.Contains(r.ResourceTitleId)
let forecasts = context.StaffingForecasts
                       .Where(f => r.ResourceId == f.ResourceId
                                && f.Date >= start && f.Date <= end)
select new ChartResourceModel
{
    ResourceId = r.Key.ResourceId,
    Division = r.Key.ResourceDivision,
    Type = r.Key.ResourceType,
    Dates = (from fc in forecasts
             group fc by d.Date into fcg
             select new ChartDateModel
             {
                 Date = fcg.Key,
                 Available = fcg.Sum(f => f.Hours) < 24
             })
}

1 I assume this is EF, because Linq-to-Sql doesn't allow local sequences in a LINQ query.


You don't really need to know the length of the fractional part.  Simply separate the fractional from the integral and handle each one separately.

static string DecToStr(decimal value)
{
    int integral = 0;
    decimal fractional = 0;
    SplitDecimal(value, out integral, out fractional);
    StringBuilder sb = new StringBuilder();
    while(integral > 0)
    {
        sb.Insert(0,integral % 10);
        integral /= 10;
    }
    sb.Append('.');
    while(fractional != 0)
    {
        int temp = 0;
        SplitDecimal(fractional * 10, out temp, out fractional);
        sb.Append(temp);
    }
    return sb.ToString();
}
static void SplitDecimal(decimal value,out int integral,out decimal fractional)
{
    integral = (int)value;
    fractional = value - integral;
}

EDIT  added check for negative

static string DecToStr(decimal value)
{
    int integral = 0;
    decimal fractional = 0;
    StringBuilder sb = new StringBuilder();
    if(value < 0)
    {
        value *= -1;
        sb.Append('-');
    }
    SplitDecimal(value, out integral, out fractional);
    while(integral > 0)
    {
        sb.Insert(0,integral % 10);
        integral /= 10;
    }
    sb.Append('.');
    while(fractional != 0)
    {
        int temp = 0;
        SplitDecimal(fractional * 10, out temp, out fractional);
        sb.Append(temp);
    }
    return sb.ToString();
}
static void SplitDecimal(decimal value,out int integral,out decimal fractional)
{
    integral = (int)value;
    fractional = value - integral;
}


Compute text area given letter heights and a text

getintval is just fromMaybe 1. finder always produces Just - you probably meant to map Nothing to Nothing. finder' is just lookup. foldl (\acc x -> max acc x) 1 is just maximum (so long as ch is never empty). k can be inlined.

solve' :: [Char] -> [(Char, Int)] -> Int
solve' ch lst = (*length ch) $ maximum $ map (fromMaybe 1 . (`lookup` lst)) ch

zipWith (\x y -> (x, y)) is just zip. read's type can be deduced. rec and word1 can be inlined.

solve :: [Char] -> [Char] -> Int
solve wght val = solve' val $ zip ['a'..'z'] $ map read $ words wght

mapMaybe throws away invalid characters. We can flatten the call tree by letting main assemble the pieces.

solve :: [Char] -> [(Char, Int)] -> Int
solve ch lst = (*length ch) $ maximum $ mapMaybe (`lookup` lst) ch

parse :: [Char] -> [(Char, Int)]
parse = zip ['a'..'z'] . map read . words

main :: IO ()
main = do
  weight <- getLine
  pdfstr <- getLine
  print $ solve pdfstr $ parse weight


Chess Dictionary Validator (Python) (Automate The Boring Stuff)

As you said the code works - there might be additional conditions for a valid board, that you are not checking for which you will be able to expand on using the same structure. I looked up the chapter from the book you mention and your implementation meets the requirements outlined there.
Since this is Python, there are more than one way to implement the requirements, at a minimum I'd recommend refactoring the code to be self documenting instead of relying on comments. This will require only minor refactoring of your code.
Then building on that may be consider taking a functional approach and utilizing python builtins. YMMV - here is my implementation, it is not perfect, but that is not the intent here.
def checkCriteria(pieces, fn, cnt):
    if len(list(filter(fn, pieces))) > cnt:
        return False

    return True

def checkValidPositions(input_pos):
    positions = set()
    for col in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']:
        for row in range(1, 9):
            positions.add(str(row) + col)

    return all(pos in positions for pos in input_pos)

def checkMaxPiecesByColor(pieces):
    return all(checkCriteria(pieces, lambda piece: len(piece) > 0 and piece[0] == ch, 16) for ch in ['w', 'b'])

def checkKingCount(pieces):
    return all(checkCriteria(pieces, lambda piece: piece == king, 1) for king in ['bking', 'wking'])

def checkPawnCount(pieces):
    return all(checkCriteria(pieces, lambda piece: piece == pawn, 8) for pawn in ['bpawn', 'wpawn'])

def checkValidPieces(pieces):
    valid_pieces = set()
    for color in ['w', 'b']:
        for piece in ['pawn', 'knight', 'bishop', 'rook', 'queen', 'king']:
            valid_pieces.add(color + piece)

    return len(pieces - valid_pieces) == 0

def isValidChessBoard(board):
    pieces = board.values()
    positions = board.keys()

    if not checkValidPositions(positions):
        return False

    if not checkMaxPiecesByColor(pieces):
        return False

    if not checkKingCount(pieces):
        return False

    if not checkPawnCount(pieces):
        return False

    if not checkValidPieces(set(pieces) - set([''])):
        return False

    return True


Getting a serial number from shared table

You propably won't ever get the effect that 2 people create the same unique identifier at the same time. Still, it could possibly happen, most databases will handle this. If you create your db with unique values only in your table, it will automatically give you an error when 2 values are identic.


Refactoring code finding if Binary Tree is BST

1) You would like to get rid of the System.out.println() inside methods. Noone expects a method to write to the console unless the method has print in the name.

2) Just comparing the root with left tree max and right tree min can lead to wrong result. Consider,

    12
   /  \
  9    15
 / \
3   5

Here the left sub-tree is not a BST but 12 > 9 and 15 > 12. You must also ensure that left-subtree and right-subtree of root are also BST.

3) BinaryTreeBST is kind of redundant. Consider naming the class IsBSTCheck or IsBinarySearchTreeCheck. Also change the method name binaryTreeBST to isBST or isBinarySearchTree to reflect what the method does.


I have a couple of issues with the main function.

First, system("pause") may work for windows but won't elsewhere. You should dump it.

Second, Too many returns at the end.

Third, The hardcoded input makes it kinda hard to test (and doesn't look good). Just read the first parameter from the command line or read in from standard in. Here is an easy way to do so:

int main(int argc, char** argv) {
    string str;
    if(argc >= 2){
        str = argv[1];
    } else {
        cout << "Enter a string: ";
        cin >> str;
    }
    cout << rank(str) << endl;
    return 0;
}


Select highest and second highest values

I've done my best to refactor your code in such a way that you can use it to learn to improve your coding, but also in such a way that it all makes sense. I'll post it and then explain the process and some tips.

The Code

Option Explicit
Sub HighlightHighestValueRows()
    ' Select highest value not already selected (as designated by highlights green and yellow)

    Dim TargetSheet As Worksheet

    ' Use an Explicit reference to the sheet you are operating on
    ' This will find the sheet named "Sheet1" within the workbook that the code is run in.
    Set TargetSheet = ThisWorkbook.Sheets("Sheet1")

    ' Use more descriptive variable names.
    Dim SearchRange As Range
    Set SearchRange = TargetSheet.Range("C2:D500000")

    ' Because of the variable name, I have no clue what this is supposed to be.
    ' Keep this in mind when coding.
    Dim FoundCell As Range
    Set FoundCell = TargetSheet.Range("C2")

    ' r is undeclared which means its a Variant.
    ' I've declared it and given it a more proper name to prevent errors.

    ' Notice how the code makes sense as you read it with more descriptive naming conventions.
    ' Any reader will see this and know we are looping through single cells within
    ' a larger range (at least any reader with some VBA knowledge).

    Dim SearchCell As Range
    For Each SearchCell In SearchRange
        ' I prefer to avoid arrow code (which is what I turned your And's into) but it is more efficient overall
        ' to use nested If blocks versus using a longer AND statement. It also makes more sense to the reader.
        If SearchCell.Value > FirstCell.Value Then
            If SearchCell.EntireRow.Interior.ColorIndex <> 4 Then
                If SearchCell.EntireRow.Interior.ColorIndex <> 6 Then
                    Set FoundCell = SearchCell
                End If
            End If
        End If
    Next SearchCell

    ' Even after refactoring this loop I dont see what you're trying to accomplish. Are you highlighting all rows that match
    ' the value of the highest cell value? If so, why not just store the highest value in a variable? Something like:
    ' Dim Foo as Double
    ' Foo = FirstCell.Value
    ' Then much later
    ' If SearchCell.Value = Foo Then DoSomething

    For Each SearchCell In SearchRange
        If FoundCell.Value = SearchCell.Value Then
            If SearchCell.EntireRow.Interior.ColorIndex <> 4 Then
                If SearchCell.EntireRow.Interior.ColorIndex <> 6 Then
                    SearchCell.EntireRow.Interior.ColorIndex = 22
                End If
            End If
        End If
    Next SearchCell

    ' Select second highest value not already selected (as designated by
    ' highlights green, yellow, and red, which is first highest)

    ' No need to declare a new range variable since the first one doesnt need to be reused.

    Set SearchRange = TargetSheet.Range("C2:D500000")
    Set FoundCell = TargetSheetRange("C2")
    For Each SearchCell In SearchRange
        If r.Value > q Then
            If r.EntireRow.Interior.ColorIndex <> 22 Then
                If r.EntireRow.Interior.ColorIndex <> 4 Then
                    If r.EntireRow.Interior.ColorIndex <> 6 Then
                        Set FoundCell = SearchCell
                    End If
                End If
            End If
        End If
    Next SearchCell
    For Each SearchCell In SearchRange
        If FoundCell.Value = SearchCell.Value Then
            If SearchCell.EntireRow.Interior.ColorIndex <> 22 Then
                If SearchCell.EntireRow.Interior.ColorIndex <> 4 Then
                    If SearchCell.EntireRow.Interior.ColorIndex <> 6 Then
                        SearchCell.EntireRow.Interior.ColorIndex = 20
                    End If
                End If
            End If
        End If
    Next SearchCell

    'Designates 1st highest with the number 1
    Set SearchRange = TargetSheet.Range("V2:V500000")
    For Each SearchCell In SearchRange
        If SearchCell.EntireRow.Interior.ColorIndex = 22 Then
            ' Be sure to qualify your reference to the value of the cell
            SearchCell.Offset(0, 1).Value = "1"
        End If
    Next

    'Designates second highest with the number 2
    Set SearchRange = TargetSheet.Range("V2:V500000")
    For Each SearchCell In SearchRange
        If SearchCell.EntireRow.Interior.ColorIndex = 20 Then
            SearchCell.Offset(0, 1).Value = "2"
        End If
    Next
End Sub

Option Explicit

I cannot stress the importance of this being at the top of ALL of your code modules. What Option Explicit does is it causes a compile-time error when a variable is undeclared. This prevents run-time errors when you try to use variables that aren't set properly, and it will save you countless hours of debugging time.

Go To Tools > Options Editor > Require Variable Declaration. You'll thank yourself later.

Variable Naming

Not to be a jerk here, but your variable names are horrible and difficult to understand. You have rng, rng2, rg, q, s, r, cell and the worst part is that you don't need all of them. I declared four variables total (and one of those you didnt even have a variable for, but you did need).

Here's a tip, make sure your variables make sense. You should be able to look at them and have a pretty good idea of what they do. SearchRange is easy to understand: it is the range we are searching in. SearchCell is just as easy to understand: it is the cell we are currently searching in. Finally, FoundCell, you guessed it, is the cell we found using our criteria. It is pretty much bulletproof when you start to code like this (actually, not really. You'll learn that bulletproof coding takes a lot more work than a handful of good variables.) and it makes your code easy to maintain.

Additionally, there is no need to declare two variables if you need one. In other words, if SearchRange is used only for the first loop, and never needed after that, I dont have to make a NewSearchRange for the second loop. I can just use SearchRange.

General Names

Just as Variables need good names, so do subroutines. It is all too easy to take the Macro1 that the recorder gives us, and to leave it this way. When you have larger projects, Macro1 and Macro2 become undistinguishable, and god forbid you have a Module1 and Module2 as well. Name everything. That's pretty much my mantra. From Worksheets to Tables, and PivotTables, and Workbooks, to code modules, subs, functions, etc., give it a proper name. The sooner you get in the habit, the more time you'll save.

Implicit Object References

You'll likely hear this one a lot, so it is important to learn. Whenever you are working on an object, you must consider the scope of that object. While Range("A1") looks fine to the untrained eye, anyone worth their salt in the VBA community will point out that it is a unqualified Range reference. Even worse, is if we have Foo = Range("A1") and one step further is this nasty bit:

Dim Foo
Foo = Range("A1")

It looks harmless right? Wrong. Foo is Dim'ed but it isnt given a type so it is now the dangerous Type Variant which is a known problem-child. Variants are great when you need them, but they have a habit of rearing their ugly head for those knew to the language. But wait, there's more! Range("A1") is unqualified on both sides. So this means it is actually:

Foo = ActiveSheet.Range("A1").Value

Which is fine if it is what you meant but it may not be what you meant. The thing is, not only do you not know what the Activesheet is at the time of the code running (unless you Activate it, which is it's own problem) but you also don't have control over the type going into Foo. It could be a String, or an Integer, or a Double. If you use Set Foo it'll be a Range. Foo will happily take anything you give it, which is a problem.

To solve this, be smart about your code:

Dim Baz as Worksheet

' I use ActiveSheet, but you can use any sheet reference here.
' For example, 'ThisWorkbook.Sheets("Bar")' is quite common.
Set Baz = ActiveSheet

Dim Foo as String
Foo = Baz.Range("A1").Value

Know I know **exactly* what my code is doing, and I can debug it much faster if something breaks.

Indentation

This is a pet peeve of mine, and it is a pet peeve of the community as well. Always indent your code (properly) and never post code on SO that is not indented. We will be cursing your name as we indent it ourselves (or, even more frequently, we just refuse to help). A lack of indentation will make bad code even harder to read.

Shameless Plug For Rubberduck

Mat's Mug and his team have a tool called 'Rubberduck' that goes a long way towards enabling you to fix these problems. Everything from indentation, to variable naming and variable use, even to Function and Subroutine calls. I highly suggest checking it out: http://rubberduckvba.com/ .

In Closing

Whatever you do, don't simply copy and paste my code, throw it into your module, and just go on your merry way. I spent time on this to help you learn, and my hope is that six months from now you will be in my shoes. If you do decide to forego the learning opportunity here, you will miss out on all of the things VBA can really offer.

Best of luck!


Some minor comments:

you are assuming there are no invalid chars in the input string.
why not pass the string length into the function; the caller has to know it in order to allocate the hex buffer.
len could be const
unnecessary brackets around RHS expressions in hex[i] assignments
I would prefer the second assignment to be |= not +=
it is usual to use uppercase names only for #defined constants


So let me get this straight, you are trying to determine if list A is a subset of list B?

internal bool DoIdsMatchThoseFromXml(List<string> ids, List<string> xmlIds)
{
    return !ids.Except(xmlIds).Any(); // A - B = {}
}

Or are you trying to see if list A is set equal to list B?

internal bool DoIdsMatchThoseFromXml(List<string> ids, List<string> xmlIds)
{
    return ids.Count == xmlIds.Count // assumes unique values in each list
        && new HashSet<string>(ids).SetEquals(xmlIds);
}

I would avoid performing linear searches through this as you'd be looking at O(n*m) performance when you could be doing O(n+m).  Use set operations if you can.  Use HashSet<string> if possible too.


Swift function to interpret Roman numerals (ported from JavaScript)

Let's do this from inside out. temp.starts(with: glyph) is correct, but
there is also a dedicated method temp.hasPrefix(glyph) for strings.

The loop to find the first dictionary entry with a matching prefix
can be shortened to

guard let (glyph, quantity) = dict.first(where: { temp.hasPrefix($0.glyph) }) else {
    throw RomanNumericError.badInput(original: original, temp: temp)
}

(also making the var found obsolete.)

Mutating the temporary string can be avoided by working with a SubString (which is a kind of view into the original string) and
only updating the current search position:

var pos = original.startIndex
while pos != original.endIndex {
    let subString = original[pos...]
    // ...
    pos = original.index(pos, offsetBy: glyph.count)
}

Naming: This is very opinion-based, here are my opinions:

Declare the function as func romanToInt(_ roman: String),
so that it is called without (external) argument name:
romanToInt("MMXIV").
Rename var int to var value.
dict is also a non-descriptive name (and it is not even a dictionary), something like glyphsAndValues might be a better choice.

Summarizing the suggestions so far, we have

func romanToInt(_ roman: String) throws -> Int {
    var value = 0
    var pos = roman.startIndex
    while pos != roman.endIndex {
        let subString = roman[pos...]
        guard let (glyph, quantity) = glyphsAndValues.first(where: { subString.hasPrefix($0.glyph) }) else {
            throw RomanNumericError.badInput(roman: roman, at: subString)
        }
        value += quantity
        pos = roman.index(pos, offsetBy: glyph.count)
    }
    return value
}

Now the error handling. Yes, throwing an error is a good and Swifty
way to report a failure to the caller. (An alternative is to return an
optional value which is nil in the error case, but that does not
allow to provide additional error information.)

The creation of the error message however should be done in the
error class, by adopting the LocalizedError protocol:

enum RomanNumericError: Error {
    case badInput(roman: String, at: Substring)
}

extension RomanNumericError: LocalizedError {
    public var errorDescription: String? {
        switch self {
        case .badInput(let roman, let at):
            return "Error parsing roman numeral '\(roman)' at '\(at)'"
        }
    }
}

The big advantage is that the caller does not need to know which
error the function throws, and can catch a generic Error:

do {
    try print(romanToInt("MMXIV"))
    try print(romanToInt("MMYXIV"))
} catch {
    print(error.localizedDescription)
}

// Output:
//   2014
//   Error parsing roman numeral 'MMYXIV' at 'YXIV'


You have just literally lost the async part of your ReadAsStringAsync method. By calling the Result property of your Task object, you will block your calling thread since it is going to wait for the async thread to return with the result of the operation. The Result property is just like the Wait method.

You should use await instead of Result or Wait, since:

Result and Wait will encapsulate your Exception into an AggregateException.
You could easily encounter a deadlock situation. You shouldn't block on async code normally.

However, without Result and Wait you simply cannot make a property safely async. It is not supported in C#, only methods, lambda expressions or anonymous methods can use await. Properties should perform fast and non-blocking operations. If you want to perform a long running activity, don't make it a property (or just call a synchronous method in the setter).

private HttpContent Content;
private string SerializedContent;

public async Task SetHttpContent(HttpContent Content)
{
    this.Content = Content;
    SerializedContent = await Content.ReadAsStringAsync();
}

// ...

await SetHttpContent(new object);


Safely getting the next element of a list

It looks like you are trying to do the same thing in two different ways.

To detect the case where e is not in xs, you should check whether yb is empty.  (If that's what you were trying to do with nextElem' _ (x : [])= Nothing then you should note that it doesn't do that.)  I'm not sure what the purpose of the otherwise case is.  If break didn't find any element equal to e, recursion won't find it, either.  Therefore, a simpler solution would be

nextElem :: Eq a => a -> [a] -> Maybe a
nextElem e xs
  | null match = Nothing
  | null rest  = Just (head xs)
  | otherwise  = Just (head rest)
  where
    (skip, match) = break (== e) xs
    rest = tail match

What is the expected result for nextElem something [something] — a one-element  list that happens to contain the element you are looking for?  I believe you would produce Nothing.  I would have expected something instead.  If you want to preserve the original behavior, where nextElem 'a' "a" produces 'a', then you could insert

nextElem e [_] = Nothing

as a special case to this solution.


Word splitting / text parsing with consideration for quotes

I'm not saying the below revision is an improvement but it has eliminated the need for MoveNext. The penalty is to have the index as a separate argument to loop which violates the idea of a state object. One could argue that the index is not a part of the (splitting)state but just an iterator variable and then everything are nicely justified again :-)

module RevisedSplitting =

    type String with
        member this.charAt index =
            this.[index]

    type Quote =
       | Single
       | Double
       | None

    type State = {
       Start : int
       Quote : Quote
       }

    let InitState =
       {Start = 0; Quote = None }

    let FlipQuote s index (text : string) =
       match text.charAt index, s.Quote with
       | '\'', None   -> {s with Quote = Single}
       | '"' , None   -> {s with Quote = Double}
       | '\'', Single -> {s with Quote = None}
       | '"' , Double -> {s with Quote = None}
       | _ -> s

    let StartNew s index =
       {Start = index; Quote = None}

    let NotEmpty s =
       not (System.String.IsNullOrWhiteSpace(s))

    let GetToken s index text =
       (string text).Substring(s.Start, index - s.Start)

    let GetChar index (text : string) =
       sprintf "%c" (text.charAt index)

    let ExtractTokens (text : string) =
       let rec loop index state =
          seq {
             if index < (text |> Seq.length) then
                match text.charAt index, state.Quote with
                | '"' , _
                | '\'', _     -> yield! FlipQuote state index text |> loop (index + 1)
                | ' ' , None
                | '(' , None
                | ')' , None  -> yield  GetToken state index text
                                 yield  GetChar  index text
                                 yield! StartNew state (index + 1) |> loop (index + 1)
                | _   , _     -> yield! state |> loop (index + 1)
             else
                yield GetToken state index text
          }
       loop 0 InitState |> Seq.where NotEmpty


The first thing that comes to attention is that you are repeating stuff unnecessarily.

Every loop, you try to import random and download the movie charts.

Importing random has only a small performance penalty, since Python will quickly notice that it is already imported, but there is some penalty nevertheless.

Downloading the charts again and again depends highly on the speed of your internet.

It is usually also good to separate your concerns into modular functions. This way you can easily swap out implementations or reuse them later.

Python has an official style-guide, PEP8, which programmers are encouraged to adhere to. It recommends using lower_case_with_underscores for variables and functions, instead of camelCase.

I would also use str.format to put the n into the path string and make the path strings themselves constants, which makes it easier to change them if IMDB ever changes their website.

Doing this, your code becomes:

from lxml import html
import requests
import random

TITLE ='//*[@id="main"]/div/span/div/div/div[3]/table/tbody/tr[{}]/td[2]/a/text()'
YEAR = '//*[@id="main"]/div/span/div/div/div[3]/table/tbody/tr[{}]/td[2]/span/text()'
URL = '//*[@id="main"]/div/span/div/div/div[3]/table/tbody/tr[{}]/td[2]/a/@href'

def get_summary(url):
    moviepage = requests.get(url)
    details = html.fromstring(moviepage.content)
    return details.xpath("normalize-space(//div[@class='summary_text']/text())")

def get_movie(tree, n):
    title = tree.xpath(TITLE.format(n))
    year = tree.xpath(YEAR.format(n))
    url = str(tree.xpath(URL.format(n))).replace("['", "").replace("']", "")
    url = 'http://www.imdb.com' + url
    return title, year, url

def get_user_yn(message):
    while True:
        answer = input(message).upper()
        if answer in ('Y', 'N'):
            return answer == 'Y'
        print("Invalid input. Please enter a Y or a N. ")

def movie_picker():
    page = requests.get('http://www.imdb.com/chart/top')
    tree = html.fromstring(page.content)
    while True:
        # Parse the movie's url and pull the summary from the details page
        n = random.randint(1, 250)
        title, year, url = get_movie(tree, n)
        summary = get_summary(url)
        print(title)
        print(year)
        print(summary)
        if not get_user_yn("Have you already watched this movie? Enter Y or N. : "):
            print("Enjoy the movie!")
            break

if __name__ == '__main__':
    movie_picker()

With this done, next I will focus on the actual implementation of these functions.

The parser you use is very manual. You have to pass the whole path to the element you are looking for. A more user-friendly parser is BeautifulSoup from the module bs4. You can install it on Ubuntu/other Debian derivatives via sudo apt install python-beautifulsoup.

It has a method called find which returns the first tag matching some criteria. So to find the title, we can just do soup.find("td", class_="titleColumn"). Or use the find_all command to get a list of all matching tags. You will see that the parsing is a lot easier to follow with this, compared to lxml.

I would shuffle the movies list and then iterate over the shuffled list, guaranteeing that a movie will not be picked twice (during one run of the script).

from bs4 import BeautifulSoup
import requests
import random

def get_movies(url):
    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    movies = soup.find_all("td", class_="titleColumn")
    random.shuffle(movies)
    return movies

def get_summary(url):
    movie_page = requests.get(url)
    soup = BeautifulSoup(movie_page.text, 'html.parser')
    return soup.find("div", class_="summary_text").contents[0].strip()

def get_movie_info(movie):
    title = movie.a.contents[0]
    year = movie.span.contents[0]
    url = 'http://www.imdb.com' + movie.a['href']
    return title, year, url

def get_user_yn(message):
    while True:
        answer = input(message).upper()
        if answer in ('Y', 'N'):
            return answer == 'Y'
        print("Invalid input. Please enter a Y or a N. ")

def movie_picker():
    for movie in get_movies('http://www.imdb.com/chart/top'):
        # Parse the movie's url and pull the summary from the details page
        title, year, url = get_movie_info(movie)
        summary = get_summary(url)
        print(title, year)
        print(summary)
        if not get_user_yn("Have you already watched this movie? Enter Y or N. : "):
            print("Enjoy the movie!")
            break

if __name__ == '__main__':
    movie_picker()


Fibonacci number function: convert to tail-recursion?

A concise and idiomatic (I think) implementation (which happens to be tail recursive) but without your / 2 optimisation would be:

let fib n =
    let rec tail n1 n2 = function
    | 0 -> n1
    | n -> tail n2 (n2 + n1) (n - 1)
    tail 0I 1I n


Toggling the visibility of drop-down menu items

If you are ever writing an element ID that contains a number, as opposed to a totally unique name, you should re-think how you're using them. In fact, if you want to take a totalitarian mental shortcut, just never use IDs (at least, until you're very experienced and understand their pros/cons). Most JavaScript frameworks allow you to easily query for all elements that use a certain class, and even if you aren't using a framework, it's not so hard to loop through the results of a selector. That said, it's possible the main difficulty in this instance is associating a dropdown button with dropdown content. If the HTML is up for modifying, here's a loose way that I would do it.

HTML:

   <button type="button" class="openDropdown">Open</button>

CSS:

.dropdownContent:not(.visible) {
  display: none;
}

JS:

var dropdowns = document.querySelectorAll('.dropdown');
for (var i = 0; i < dropdowns.length; i++) {
  var dropdown = dropdowns[i];
  var content = dropdown.querySelector('.dropdownContent');
  dropdown.querySelector('.openDropdown').addEventListener('click', function() {
    content.classList.toggle('visible');
  }
}

Part of the reason I used classes as opposed to direct styling is it's easier to toggle; but also, the other options for display: properties can often conflict with a developer's attempt to show/hide it. inline-block is very useful, but has previously been messed up for me because of code that was showing/hiding an element and overrode that.

EDIT: RoToRa found a bug in the above code - the closure generation for the addEventListener block will preserve the variable content, but that variable will change before the loop actually finishes, so in the end it will only apply to the last instance. (You won't notice the issue if you only have one dropdown) Here's my attempt at a fix: Note the arguments to the listener, and the .bind at the end.

var dropdowns = document.querySelectorAll('.dropdown');
for (var i = 0; i < dropdowns.length; i++) {
  var dropdown = dropdowns[i];
  var content = dropdown.querySelector('.dropdownContent');
  dropdown.querySelector('.openDropdown').addEventListener('click', function(content, evt) {
    content.classList.toggle('visible');
  }.bind(null, content);
}

Closures are very convenient automatic ways to preserve a variable with asynchronous programming, but bind is a more manual way that treats it as an argument. Another option would have been to turn the entire inside of the loop into a function, and run it immediately (creating a separate closure context that will exist once for each loop run)