Delete orphaned SIDS + change to full control

Should be able to add a little more if you answers my questions in a comment I made on your question. In the mean time there definitely are some points worth bringing to light. I am going to assume you have at least PowerShell v3.0.

Over complicated folder name query

Property Expansion done right

You don't need to build an array for the fullname. Nor do you really need to get the fullname via a directory object for the $root as you already have it. If dot notation does not work Select-Object Fullname would work just as well.

$folders = @($root) + (Get-ChildItem $root -Recurse -Directory).FullName

Since $root is not an array we make it one, just as you did, with @() then simply concatenate the rest of the folder names to make the list of folders.

Avoid array concatenation

This is not a bid deal if you read into my first couple of points but I still want to cover this. It is a memory intensive waste as it destroys and recreates the array adding the new element. Use the pipeline if possible to avoid this.

Regular Expressions

I wanted to draw attention to -match. That operator and others like -replace support regular expressions as well.

In regex "S-1-5*" would match anything that had those characters anywhere in the string and not just the beginning. More importantly it would match strings like "S-1-5555" since 5* matches 0 or as many 5's as it can find. If you wanted to keep using match I would recommend the start of line anchor. In the spirit of what you were trying to do "^S-1-5" would accomplish the same thing. Look for a string that starts with "S-1-5". However the easier solution is just to use -like which is the operator you were, in essence, using

if ($acc_ir -like "S-1-5*")

Double processing

While you have two actions to perform (remove dead sids and change permissions) all the work is still being done on the same folder set. I would not bother looping twice. You could just loop the once and merge your if statements inside the single loop.

foreach ($folder in $folders) {
    try {
        $acl = Get-Acl -Path $folder
        foreach ($acc in $acl.access ) {
            $acc_ir = $acc.IdentityReference
            $acc_fsr = $acc.FileSystemRights
            if ($acc_ir -match "GROUP" -and $acc_fsr -match "FullControl") {
                # Logic for when the group is matched and has fullcontrol
            } elseif ($acc_ir -match "S-1-5*") {
                # Logic for when their is a dead sid.
            }
        }
    } catch {
        # Errors captured here.
    }
}

This would have implications in your log as the entries would no longer be grouped by action but I will cover that later.

Perhaps you prefer the separation

If you didn't want to go the route of the single loop (which you should for performance) I would suggest you use Where-Object in place of your if's as that is in effect what you are doing. Consider you first loop group where you remove the dead sids.

$acl.access | Where-Object{$_.IdentityReference.Value -match "^S-1-5"} | ForEach-Object{
    $acc_ir = $_.IdentityReference.Value
    $acl.RemoveAccessRule($_) | Out-Null
    Set-Acl -Path $folder -AclObject $acl -ErrorAction Stop
    $hour = Get-Date
    Write-Host -ForegroundColor Green "$hour - $acc_ir deleted in $folder"
    Write-Output "$hour - $acc_ir deleted in $folder" | Out-File -Append $log
}

Logging

About Out-File

It is considered one of the weaker means to output text to a file. Add-Content is a good upgrade as it is just as easy to use and performs better. It also is a cmdlet that appends by default and adds a newline to the end of the string automatically. You could also use Set-Content for the first line if you intend to clean the log every time the script is run.

Functions

You should be using at least one function here. You are repeating your blocks of code several times throughout your script. A function would make it easier to read the code and more importantly simpler to make changes to your logging.

function Log-Action($reference,$location,[switch]$LogError){
    $now = (get-Date).ToString()
    If($LogError.IsPresent){
        Write-Host -ForegroundColor Red "$now - error with $reference in $location"
        Write-Output "$now - error with $reference in $location" | Add-Content $log
    } else {
        Write-Host -ForegroundColor Green "$now  - $reference deleted in $location"
        Write-Output "$now  - $reference deleted in $location" | Add-Content $log
    }
}

That would work but some would say that it has a terrible name as it performs two duties.... Logging both errors and information. Also removes the need to save the current time in different variables.

Either way this would be how you would call it in the script...

try {
    $acl = Get-Acl -Path $folder
    foreach ($acc in $acl.access ) {
        $acc_ir = $acc.IdentityReference.Value
        if ($acc_ir -match "S-1-5*") {
            $ACL.RemoveAccessRule($acc) | Out-Null
            Set-Acl -Path $folder -AclObject $acl -ErrorAction Stop
            Log-Action $acc_ir $folder
        }
    }
} catch {
    Log-Action $acc_ir $folder -LogError
}

Objects and CSV output

Something else to consider would be to try and export CSV data so that it would not matter what order your output was as your could organize it as you saw fit with a simple column sort in Excel or similar program.

This one might be harder to show without major changes but here is how it could go.

# Need to use this for each contruct in order to use the pipeline.
$folders | ForEach-Object{
    $folder = $_
    # Build the row
    $result = [pscustomobject][ordered]@{
        Time = (Get-Date).ToString()
        Folder = $folder
        IdentityReference = $null
        Action = "Remove dead SID"
        ActionSuccedded = $false # Assume False

    }

    # reset in case of early failure where this might not get populated
    $acc_ir = $null

    try {
        $acl = Get-Acl -Path $folder
        $acl.access | ForEach-Object{
            $acc = $_
            $acc_ir = $acc.IdentityReference.Value
            if ($acc_ir -match "S-1-5*") {
                # Stuff Happens
                # Log the changes
                $result.Time = (Get-Date).ToString()
                $result.IdentityReference = $acc_ir
                $result.ActionSuccedded = $true
                # send the result through the pipeline
                $result
            }
        }
    } catch {
        # Error has occured.
        $result.Time = (Get-Date).ToString()
        $resulr.IdentityReference = $acc_ir
        # send the result through the pipeline
        $result
    }
} | Export-CSV -NoTypeInformation $log

This way you have highly functional output since we populated a result object with the status of each action and get output that looks something like this

Time                  Folder       IdentityReference                             Action          ActionSuccedded
----                  ------       -----------------                             ------          ---------------
1/23/2016 11:28:17 PM C:\temp      S-1-5-21-1220945662-1202665555-839525555-5555 Remove dead SID            True
1/23/2016 11:28:17 PM C:\temp\test S-1-5-21-1220945662-1204465555-839525555-5555 Remove dead SID           False

Most of my suggestions don't build together but I wanted to cover each one separately in an effort to maintain focus. You will have to forgive me if I lost you on any part of this.


This is what I would do.

First, rename coordinates to coord_list so you can eliminate mylist which is kind of useless since you only use immediately assign it to coordinates. To make things slightly simpler I assigned count to coord_list.Count so now you can just check count instead of coord_list.Count. Instead of executing the loop if the Count is bad, we check that count is between 1 and 3  before entering the loop. From here it loops though the activeDataConnections and has been changed so it checks count instead of repetition of the same logic.

Here is the code:

def getTableGroupTopMember_Test1(coord_list):
    '''
    Depending on the number of coordinates given, this function/code returns a unique coordinate.
    '''
    count = coord_list.Count

    # thanks to 200_success
    if not 0 < count < 4:
        print "your code is shit!"
        return

    for adc in activeDataConnections:
        for table in adc:
            if table.Name == coord_list[0] and count == 1:
                print "/"
            elif table.Name == coord_list[0]:
                for topgroup in table.TopAxis.Groups:
                    if topgroup.Name == coord_list[1] and count == 2:
                        print topgroup.Address
                    elif topgroup.Name == coord_list[1]:
                        for topmember in topgroup:
                            if topmember.Name == coord_list[2]:
                                print topmember.Address

getTableGroupTopMember_Test1(["Table10"])
getTableGroupTopMember_Test1(["Table10", "profile_julesage",])
getTableGroupTopMember_Test1(["Table10", "profile_julesage", "_25_to_34"])


Not bad! Let's go through it line-by-line.

typedef unsigned char BYTE;

This is fine, but just so you know, starting from C++17, there is a std::byte that could replace this. If you're not using C++17 yet, fine, but if this is code is for C++17 or better, that's something you can take advantage of.

inline int bmpEncoder(const std::string &location,
    const unsigned __int32 &width, const unsigned __int32 &height,
    const std::vector<BYTE> &buffer,
    const bool &hasAlphaChannel = true) {

I'm not sure that the inline specifier serves any purpose here. Compilers generally ignore inline suggestions anyway, but in this case I can't see this entire huge function being something you'd want to inline. If you added it to get a header-only library function, that makes sense, but this doesn't really seem like a candidate for a header-only library.

You use __int32 and similar types all over the code, but were you aware there are standard versions? Just include <cstdint> and you get access to the fixed-width integer types. Instead of const unsigned __int32, you'd do std::uint32_t.

I don't really see the benefit of taking 32-bit integers by reference. They're basically cost-free to copy, so you might as well use them by value.

Taking the image data by const std::vector<BYTE>& is a good idea... but you can do even better! You see, if you take your image data by const std::vector<BYTE>&, that means the image data must be in a std::vector<BYTE>. Maybe that's usually the case... but why restrict the options? Ultimately, to use fout.write(), you just need the image data to be in a contiguous array. A std::vector<BYTE> works... but so does a std::unique_ptr<BYTE[]>, or an std::array<BYTE, N>, or third-party container types.

So rather than taking a std::vector<BYTE>, you could just take a const BYTE* and std::size_t pair. Even better, you could use a gsl::span (which is probably going to be in C++20 as std::span).

Finally, there's no reason to take a bool argument by const-ref. Just take it by value.

Oh, also, you only seem to be using the return value as a true/false thing to denote errors. You could do that with a bool, but you should look into better ways to report errors, like std::error_code or exceptions (or the proposed std::expected).

So here's what all that put together looks like:

int bmpEncoder(const std::string &location,
    std::uint32 width, std::uint32_t height,
    const BYTE* buffer, std::size_t buffer_size,
    bool hasAlphaChannel = true) {

Or with span:

int bmpEncoder(const std::string &location,
    std::uint32 width, std::uint32_t height,
    std::span<const BYTE> buffer,
    bool hasAlphaChannel = true) {

The first thing you do in the function is open the output file, then double-check that it's open. But that's the last error-checking you do. If there's any problems writing the output after that, they just get forgotten, so this function could return 1 even though the output never got written.

You have multiple options for how to deal with this. The simplest is to just not bother to do any error checking until the end of the function - just open the file, and write everything to it, then at the end return bool{fout};. That will return 1 if everything worked and all your image data was written to the file (you should probably flush it beforehand), 0 otherwise. If there's an error early in the process, you will waste time spitting bytes into the ether, but no big deal - no harm will be done except time wasted, and the error will be detected.

Another option is to turn exceptions on in your output stream. If any error occurs, output will stop immediately. You can either catch the exception and return 0, or let the exception propagate if you prefer.

So the next bit is the biggest part of the function. What you do here is set up all your data in local variables... then copy all those local variables to a buffer... then write the buffer to the output file. That all seems a bit unnecessary.

Here's what I recommend instead. Create a set of functions that write binary values to the output stream. For example

inline std::ostream& write_binary_8bit(std::ostream& out, char c) {
    return out.put(c);
}

inline std::ostream& write_binary_8bit(std::ostream& out, char const* c, std::size_t n) {
    return out.write(c, n);
}

inline std::ostream& write_binary_8bit(std::ostream& out, BYTE const* c, std::size_t n) {
    return write_binary_8bit(out, reinterpret_cast<char const*>(c), n);
}

inline std::ostream& write_binary_16bit(std::ostream& out, std::uint16_t v) {
    return out.put(v & 0xFFu).put((v >> 8) & 0xFFu);
}

inline std::ostream& write_binary_16bit(std::ostream& out, std::int16_t v) {
    return write_binary_16bit(static_cast<std::uint16_t>(v));
}

// And so on for whatever types you need...

Then your function code just becomes:

write_binary_8bit(fout, "BM", 2);   // signature
write_binary_32bit(fout, buffer.size() + padding * (height - 1) + 14 + 124; // file size
write_binary_32bit(fout, 14 + 124); // offset

write_binary_32bit(fout, 124);      // DIBSize
write_binary_32bit(fout, width);    // width
write_binary_32bit(fout, height);   // height
write_binary_16bit(fout, 1);        // numPlanes
write_binary_16bit(fout, (hasAlphaChannel) ? 32 : 24);    // bitsPerPixel
// and so on

Now you can get rid of the header vector and the macro.

Then it's on to writing the actual image data.

for (int i = height - 1; i >= 0; i--) {
    std::vector<BYTE> row(buffer.begin() + i * bWidth, buffer.begin() + i * bWidth + bWidth);
    fout.write((char *)row.data(), row.size() * sizeof(BYTE));
    fout.seekp(padding * sizeof(BYTE), std::ios::cur);
}

What you're doing here is that for each row, you're creating a new vector, copying the row data into it, then writing the vector. Why the extra steps? All you really want to do is write the row data. So just write it directly. No need for the extra vector.

for (int i = height - 1; i >= 0; i--) {
    write_binary_8bit(buffer.begin() + i * bWidth, bWidth);
    fout.seekp(padding, std::ios::cur);
}

One thing you might want to do here is some error checking, though. You need to be sure that the image data buffer isn't truncated - that it actually does hold width×height pixels, or you might be reading (and writing to a file) random memory data. That's how security disasters like Heartbleed happen.

And finally:

fout.close();

This is unnecessary. The file will close itself automatically.

What you might want to do, though, is:

return bool{fout.flush()};

That will flush everything buffered to disk (hopefully), and check the error status of the stream.

In summary, my major recommendations are:

use standard types (instead of __int32)
avoid unnecessary buffering by writing data directly (rather than creating a buffer, copying the data to the buffer, then writing the buffer)
get rid of the preprocessor macro (and unnecessary buffer) by using helper funcions
consider better error checking


Passing a string, around quotation marks into another string, all in a mutli line string

No matter how you do it, it'll be always messy. Instead of hardcoding the strings use resource files instead. You can embed *.txt files inside the exe/dll and easily read them without having to escape anything.

See this question on Stack Overflow: How to read embedded resource text file
. You'll find everything you need there.

To insert the message use the {0} placeholder with

string.Format(stringFromResource, txtMessage.Text);


Web scraper extracts zip files and publishes them to redis

It's not generally recommended to do a lot of work in the initializer, I would move the code to download the files into a separate method.
Normal Ruby style is usually to not use parentheses when no parameters are passed to methods, i.e. s.extract_zip not s.extract_zip().
It's usually frowned on to do type comparisons in Ruby like this:

filenames = filenames[0..limit-1] if limit.is_a?(Integer) && limit-1 >= 0

so either assume that the user passes a valid value or nil (this is what I would do):

filenames = filenames[0..limit-1] if limit && limit > 0

or just do a straight conversion:

filenames = filenames[0..limit.to_i-1] if limit.to_i >= 0

Use constants for magic values,

DEFAULT_URL = 'uri: "http://feed.omgili.com/5Rh5AMTrc4Pv/mainstream/posts/'
def download_files(uri: DEFAULT_URI, ...)

Use single quotes for strings that don't sue replacements or escaped characters (\n)
I would also not require parameters on the initializer that are just stored for use in one method (unless you expect to be calling it multiple times) so my usage would more likely be:

s = Scraper.new
s.download_files(url: ..., limit: 1)
s.extract_zip(zip_dir: ....)
s.push_xml_to_redis(xml_dir: ....)

However you might want to balance this with not expecting the user of your class to not have to call so many methods, or know so much, to call your class. As such I might design this for usage like:

s = Scraper.new
s.uri = ...
s.xml_dir = ...
s.scrape!

If I was an interviewer, I would even be more impressed if you separated out your logic into a class for scraping and one for writing (which could easily be replaced with a different backing store, say s3 or file-system based)

class RedisStore
  def initialize(redis_key)
    ...
  end
  def store!(filename, data)
    @redis.hset(self.redis_key, filename, data)
  end
end
class Scraper
  ...
  def push_xml_to_store(store)
    ...
    file_list.each do |filename|
      store.store!(filename, file_data)
    end
  end
end

store = RedisStore.new
scraper.push_xml_to_store(store)

this would also make testing either.
One last point. It would be good to do this without creating temporary files. This would simplify usage because there would be no need to worry about setting the correct zip_dir and xml_dir or cleaning up afterwards.


Is decimal, hexadecimal, octadecimal, binary converter efficient?

Disclaimer: I'm new here, so this might not be the type of review people give, but I'm trying to match it as best as I can.

Formatting

A comment explaining the purpose of combineResults(String a, String b) next to the method would be helpful.  (Yes, there's one in the main method, but documentation next to the helpers is good, too.)

The same could be said for numConverter(int number)...

Other than that, indentation looks good, braces look fine, etc.  :)

Algorithm

In general: You should be passing around StringBuilders or StringBuffers (or chars) instead of Strings.  The former are mutable, while the latter isn't mutable.  This will save some performance.  (e.g. appending is better on memory with the builders and buffers, rather than with raw Strings.)

Main Algorithm

Ok...  You took kinda an odd approach to converting bases.  Rather than using all those while loops, you should focus on determining the next least significant digit by using the modulus operator followed by division.

For example, in pseudocode:

while(number > 0) {
  nextDigit = number % base; //Get the next digit using modulo
  number /= base;
  // prepend nextDigit to result String Buffer
}

This makes the combineResults() method unneeded, as prepend is built-in to the StringBuilder.

NumConverter

In the spirit of StringBuilders vs. String, this should return a char rather than a String.

Your current code assumes that the only number ever fed to this method will be less than 16.  This could be a problem if it's a larger library, or if you want to expand the bases to more than hexadecimal.

You could use a switch/case construct instead of the else if's...

Or, if you really want to shorten the code, you could do something like (note: this also implements the char return instead of String):

char numConverter(int digit) {
   if (num >= 16 || num < 0) //If we're not given a valid digit
     return 0; //Let the output know somehow...  could throw an exception instead.
   else if (digit <= 10) //If we're dealing with a "normal" digit
     return ((char)num + '0'); //... return the numeric equivalent
   else //We're in extended digit range: we need letters!
     return ((char)digit + 'A' - 10); //Return hex equivalent of 10-15 (A-F)
}


Avoid existSync function on Node.js - Express API controller

I would consider asynchronously checking for all 5 potential
files at once, meaning that checks can be paralellized.  Once all are complete, you can evaluate the compiled results and return the most recent file.

Depending on your expected call pattern ( for example, are more recent files typically the ones being requested?), you may consider keeping a cached copy of all or part of the file listings in memory to avoid disk read altogether.

Another thing you may really want to think about is your API interface. I would find it extremely hard to understand that a request for a file that may not actually exist would return a 200 result. This would be very non-standard from a REST API standpoint. Perhaps the client calling this service should own the logic of checking for 5 days’ worth of results.

Why all the weird formatting steps from Date object? Just output directly to your desired format instead of chaining together a bunch of string manipulation.

If file is already JSON format, why parse it and then reserialize when delivering response? Had you consider serving these files statically?  You could GREATLY simplify this code (down to literally two or three lines by serving these files statically and letting caller own the logic of looking for days in the past. Not to mention. You can get all the serve static behaviors around cache-control, etags, etc. this way if cacheability matters to your client.


Update / save / display values in a table

Yup, looks like The Angular Way™. A good rule of thumb for controllers is that 1) it exposes data, 2) it exposes functionality, 3) not tied to any specific template. There's a few things though.

var familyMembers = [
    { name: "Joe", age: 42}
    , { name: "Jane", age: 40}
    , { name: "Bob", age: 13}
];

Why is this outside the controller? Why not define it inside? If you want it defined separately from the controller, consider using a provider/service/factory to store it. Then pull that provider/service/factory into the controller as a dependency.

Init isn't really some initialization. It's resetting your form data. A better way to do this, instead of emptying the object values, is to create a function that returns a blank version of the object and replace the form data.

function createMember(){
  return { name: '', age: '' };
}

function resetForm(){
  $scope.formData = createMember();
}

// Assuming the form uses `$scope.formData` as the form object

As for saving, before you reset, you just copy the form data using angular.copy and pop it in the members array. This way, the object you put in the array isn't the same object referenced by the form data, which may still be subject to binding. Then you reset the form data.

function saveForm(){
  var newMember = angular.copy($scope.formData);
  members.push(newMember);
  resetForm();
}


Pythonic approach

For sound playback in Python, see this discussion.
Avoid os.system

If you are forced to use it, supply a fully qualified path to the executable. You never know what weird program called play may be in the search path prior to an intended one.
Modularize

As written, the code is not reusable. An attempt to import it would result in an immediate alarm sound. Put the call to alarm in an

if __name__ == '__main__':

clause.
Avoid magic numbers

All the parameters (beep duration, volume, etc) better be passed via a command line (see sys.argv and optparse module).
Dummy variable

is customarily denoted as _:

    for _ in range(20):


Comparer that compares by int than by enum type

private static readonly List<RegionType> sortOrderByType = new List<RegionType>
{
    RegionType.DeletionBeforeNamedRegion,
    RegionType.NamedRegion,
    RegionType.DeletionWithinNamedRegion,
    RegionType.InsertionWithinNamedRegion,
    RegionType.DeletionAfterNamedRegion,
    RegionType.InsertionBetweenNamedRegions,
};

Sorting needs to be fast, right? So how about using a dictionary for the oder lookup and not the O(n) List.IndexOf?
private static readonly Dictionary<RegionType, int> _regionTypeOrder = new RegionType[]
{
    RegionType.DeletionBeforeNamedRegion,
    RegionType.NamedRegion,
    RegionType.DeletionWithinNamedRegion,
    RegionType.InsertionWithinNamedRegion,
    RegionType.DeletionAfterNamedRegion,
    RegionType.InsertionBetweenNamedRegions,
}
.Select((x, i) => new { Key = x, Order = i })
.ToDictionary(x => x.Key, x => x.Order);

with it, the lines

var xSort = sortOrderByType.IndexOf(x.Type);
var ySort = sortOrderByType.IndexOf(y.Type);

can become
var xSort = _regionTypeOrder[x.Type];
var ySort = _regionTypeOrder[y.Type];

var xSort = sortOrderByType.IndexOf(x.Type);
var ySort = sortOrderByType.IndexOf(y.Type);

if (xSort < 0) xSort = int.MaxValue;
if (ySort < 0) ySort = int.MaxValue;

the index should never be less then zero. If it is, then there is an error. Its an enum and the property isn't nullable so I think the protection isn't necessary.
After getting ther RegionType order from the dictionary you should be able to immediately call this

return xSort.CompareTo(ySort);


Finding matching Node instances in an array - running slow

What's absolutely crucial when doing time comparisons between languages is that we make sure we're actually testing the same thing.  In this case, we're not.

But before I get into that into too much detail, I'm going to suggest a slightly better method of testing this code.

First of all, I've moved the actual running code (everything but the class declaration and the == function definition) into an IBAction method so that I can press a button and test it multiple times all in the same build.

Second, I'm going to change the definition of the class for this test to assign random values to its properties.  So the class definition will look like this for my test:

public class Node : Equatable {
    var cost : Int = 0
    var x : Int = Int(arc4random_uniform(100))
    var y : Int = Int(arc4random_uniform(100))
}

This forces the timing to be a little more realistic since branch prediction might easily figure out that the result of == is always true and just fly through our loop.

And third of all, I'm going to test with a much larger array.  I want 10,000 elements.  This may be unrealistically large for actual usage, but when testing speed and trying to optimize time, it's good to work with very large sample sizes.

So, without changing anything else, this is what I'm going to test, and I will include results from the time profiler:

public class Node : Equatable {
    var cost : Int = 0
    var x : Int = Int(arc4random_uniform(100))
    var y : Int = Int(arc4random_uniform(100))
}

public func == (a : Node, b : Node) -> Bool {
    return (a.x == b.x) && (a.y == b.y)
}

class ViewController: UIViewController {
    @IBAction func test(sender: UIButton) {
        var t = NSDate()
        let a = [Node](count: 10_000, repeatedValue: Node())
        let b = Node()
        var count = 1
        for i in a {
            if i == b {
                count++
            }
        }

        var elapsed = t.timeIntervalSinceNow * -1000
        println(elapsed)
    }
}

Completely as written, and using whatever optimization defaults you get when you create a new project in Swift, this takes my desktop 47-50 milliseconds.  On an iPad Mini, this takes about 265-270 milliseconds.

This is the time profile of the code I posted.  I pressed the button to run the test 8 times.  Notice a few lines:

84.9% is where our Swift version of our IBAction method is.  The first 15.1 percent is the time it took to launch our app, initialize, run the view controller, receive the touch events, etc.  The other 84.9% is code that runs from inside our IBAction method.
1.1% is how much of the total time is spent comparing our Node objects with our custom == function.  The array is 10,000 elements large, and we're iterating through it completely 8 times.  We're calling the == function 80,000 times, and it only takes 1.1% of the total time.  Our == function is perfectly fine.

The code that's taking the most time is here:

Unfortunately, we can't see exactly what these are.  They're all from within the Swift library though.  And since Swift is still growing and rapidly changing, it'll probably be a while before the Time Profiler actually gives us the actual method names for these.

I tried moving code around, trying to get different results, but they're all pretty much the same.  I suspected that the array initialization was taking up about half the time and tried moving that out of the timer, but it doesn't seem to make a difference.

What I can tell you though, is this:

Your == method, which is what is all that you've written which is being tested here, is perfectly fast.  It takes almost no time at all.
It's relatively well known that at this point in time, Swift is absolutely horrendous with accessing arrays in loops like this.  But Swift is very much so a growing and evolving language.  Hopefully the Apple engineers are working on improving it.


Build a dictionary based on split string

Obvious but easy

There are some issues that are immediately obvious and easy to correct.

In this statement:

return ''.join([repr(a), '-', repr(b - 1)]) if a != b else repr(b)

The multiple repr are awkward,
and so is the join.
It would be less awkward, simpler and more readable by using string formatting:

return '{}-{}'.format(a, b - 1) if a != b else repr(a)

This can be written a lot simpler:

if char in ['(', '{', '[', ')', '<', '}', ']', '>']:

Like this:

if char in '({[)<}]>':

But actually, it's a bit disturbing that the opening and closing brackets are ordered inconsistently. For example, looking at this string, it's not immediately obvious that it includes all matching closing brackets for all opening brackets. This way would be immediately obvious and less error prone:

if char in '(){}[]<>':

This is both confusing and disturbing:

def convert_string(string):
    string_content = string
    string = Positions(string)

Why shuffle around the string parameter?
It's a bad practice to reassign the value of a parameter,
as it makes it confusing what it really stands for throughout the function.

Another problem here is calling an instance of Positions a "string".
Later in the code when I read "string",
I think it's an actually string, but in fact it's not,
it's an instance of "Positions".
Very misleading.

Since empty strings are falsy, instead of this:

if internal_string != '':
    # ...

You can write simply:

if internal_string:
    # ...

Obvious but harder

There are some issues that are sort of obviously wrong,
but not so easy to correct.

This sorting function smells:

def sort(dictionary):
    return sorted(dictionary.items(), key=lambda v: int(v[0].split("-")[0]))

Instead of splitting a string and parsing to int,
my instinct says there should be a way to use the original int values directly.

In general, the code formats these strings from int values,
and it seems silly to later un-format the strings so you can sort.
There should be a better way.

The Positions class stinks.
It's called "Positions",
but its fields are "name" and "content".
Sounds more like a key-value pair.

Then there's this code with the comment:

   self.content = {}  # creates a new empty list for each bracket

The comment talks about "list", but the code uses a dictionary.

And there's the push method:

def push(self, pos, content):
    self.content[pos] = content

push is a term commonly used with stacks, or sometimes with lists.
But here the method puts a value into a dictionary,
an operation normally called "put".

Alternative implementation

Based on the above suggestions,
and reorganizing to more meaningful elements,
you could do something like this:

from functools import total_ordering

@total_ordering
class Item:
    def __init__(self, start, end, content):
        self.start = start
        self.end = end
        self.content = content

    @property
    def position(self):
        a = self.start
        b = self.end
        return '{}-{}'.format(a, b - 1) if a != b else repr(a)

    def __lt__(self, other):
        return self.start < other.start

def convert_string(string):
    start = 0
    internal_string = ''
    items = []
    for (pos, char) in enumerate(string):
        if char in '(){}[]<>':
            items.append(Item(pos, pos, char))
            if internal_string:
                items.append(Item(start, pos, internal_string))
                internal_string = ''
            start = pos + 1
        else:
            internal_string += char

    if internal_string:
        items.append(Item(start, len(string), internal_string))

    return items

Although with the implementation of __lt__,
I made it possible to sort simply by sorted(items),
actually there is no need to sort,
as the items are naturally sorted.

Note: the purpose of @total_ordering is to implement the other rich comparison operators like __le__, as recommended by PEP8.


Improving the algorithm

Realize that you don't actually need to remove elements from a collection. You can just count how many sticks would disappear in each step.

Take for example this sorted list of sticks:

1 1 1 2 2 3 3 3 3 3 4 5 5 5

At each cutting step, the shortest sticks disappear:

1 1 1 2 2 3 3 3 3 3 4 5 5 5
^^^^^
3 will disappear

      2 2 3 3 3 3 3 4 5 5 5
      ^^^
      2 will disappear

          3 3 3 3 3 4 5 5 5
          ^^^^^^^^^
          5 will disappear

And so on. You can just count the number of sticks that will disappear, and figure out from that how many will remain.

Use interface types in declarations

Instead of this:

ArrayList<Integer> list = new ArrayList<Integer>(size);

It's recommended to declare variables with their interface types:

List<Integer> list = new ArrayList<Integer>(size);

Style

This is way too compact writing style:

for(int i=0;i<size;i++)

It's much more readable this way, by putting spaces around operators:

for (int i = 0; i < size; i++)

Checking an empty list

Instead of this:

    while(list.size()>0)

A more idiomatic way to write:

    while(!list.isEmpty())

Suggested implementation

Putting the above tips together:

public static void main(String[] args) {
    List<Integer> sticks = readSticksFromStdin();
    Collections.sort(sticks);

    int pos = 0;
    int remaining = sticks.size();
    while (0 < remaining) {
        System.out.println(remaining);
        int count = countEqualFrom(sticks, pos);
        pos += count;
        remaining -= count;
    }
}

private static int countEqualFrom(List<Integer> sticks, int from) {
    int value = sticks.get(from);
    for (int i = 1; from + i < sticks.size(); ++i) {
        if (value != sticks.get(from + i)) {
            return i;
        }
    }
    return sticks.size() - from;
}

private static List<Integer> readSticksFromStdin() {
    Scanner scanner = new Scanner(System.in);
    int num = scanner.nextInt();
    List<Integer> sticks = new ArrayList<>(num);
    for (int i = 0; i < num; ++i) {
        sticks.add(scanner.nextInt());
    }
    return sticks;
}


Mutative Heap's algorithm (permutations generator) in Clojure

I'd also, if possible, like to see a fully FP implementation of this,
  but I'd wager that that would be quite difficult.

Here is a functional implementation of Heap's algorithm in Clojure, based on page 12 of Robert Sedgewick's lecture (Don't look at the next page - the code is dubious).

The idea is to generate the sequence of swaps as pairs of indices. That's what the swaps function does. For an argument n, it generates n! - 1 of them:

(defn swaps [n]
  (if (= n 1)
    ()
    (let [base (swaps (dec n))
          extras (if (odd? n) (repeat (dec n) 0) (range (dec n)))]
      (concat
        base
        (mapcat (fn [x] (cons [x (dec n)] base)) extras)))))

It interleaves the extras between n copies of the base, the sequence of swaps of n-1 elements.

For example,

=> (swaps 3)
([0 1] [0 2] [0 1] [0 2] [0 1])

The perms function ...

(defn perms [v]
  (reductions
    (fn [a [i j]] (assoc a i (a j) j (a i)))
    v
    (swaps (count v))))

... simply applies these swaps successively to its vector argument.

For example,

=> (perms ['A 'B 'C])
([A B C] [B A C] [C A B] [A C B] [B C A] [C B A])


The function is maybe too ambitious in doing two things.

char *get_substr(char *str, char **endptr, const char *str_dim) {
    str = remove_leading_whitespace(str);
    char *substr = strtok(str, str_dim);
    *endptr = strtok(NULL, "\0");
    return substr;
}

I would keep the API simple and leave out endptr.


Generate simple sinusoidal sounds and plot signal/fft

A lot of things here are already good, like:

fs, duration and t being members on SoundStimuli
The choice of which things to initialize in the first __init__ (mostly)

Things that could be improved:

SoundStimuli is arguably SoundStimulus
self.signal should not be an optional member variable; the base class should be made effectively abstract and the signal should be returned from a getter or property whose base implementation raises NotImplementedError.
In play, the absence of a signal should be fatal, so you should naively access self.signal, and let any exceptions fall through to the caller
After p.open, wrap the rest in a try, and put the close() in a finally
convert2float is not a great idea - it replaces a member with a different version of the same member. That means that before this is called, the instance is by definition in an invalid state, which should be avoided.


Populating an unordered list from values in a JSON file

What you're looking for is JSON.parse. It's not in the Node docs, because it's "lower" than that: Every modern javascript runtime has it (see MDN).

Here's a simple function to read a file, parse it as JSON, and send it to a callback (all in Node)

function readJSONFile(filename, callback) {
  require("fs").readFile(filename, function (err, data) {
    if(err) {
      callback(err);
      return;
    }
    try {
      callback(null, JSON.parse(data));
    } catch(exception) {
      callback(exception);
    }
  });
}

In keeping with Node conventions (and just mirroring readFile itself), you pass it a callback with this signature: function(err, json). E.g.

readJSONFile("path/to/file.json", function (err, json) {
  if(err) { throw err; }
  console.log(json);
});

You can make a none-async one if you prefer, but Node's nature is async.


Write it better/neat/fast (if condition)

I think using LINQ together with string.Join() would be the best option here:

var fields = new[] { "Address", "City", "District", "Province" };
var setValues = fields.Select(field => (string)dr[field])
                      .Where(value => !string.IsNullOrEmpty(value));
string fullAddress = string.Join(", ", setValues);


Well, the first thing to do is extracting the distance-calculation and replacing the costly call to pow():

inline static double distance2(city* a, city* b) {
    double dx = a->x - b->x;
    double dy = a->y - b->y;
    return dx * dx + dy * dy;
}

Next, let's stop always copying the cities when not really needed.

Optionally, use a sentinel value (INFINITY) so we don't need to single out any candidate for nearest city.

Another nearly gratuitious change I did was starting with the last city given.

I suggest you also invest in slightly more spaces, they make things more readable, especially around operators.

The changed function:

double tsp(city* cities, int N) {
    double S = 0;
    for (int i = N; --i > 0;) {
        double best_d2 = distance2(cities + i, cities + 0);
        int best_pos = 0;
        for(int j = i; --j > 0;) {
            double d2 = distance2(cities + i, cities + j);
            if(d2 < best_d2 || d2 == best_d2 && cities[j].ind < cities[best_pos].ind) {
                best_d2 = d2;
                best_pos = j;
            }
        }
        S += sqrt(best_d2);
        city temp = cities[best_pos];
        cities[best_pos] = cities[i - 1];
        cities[i - 1] = temp;
    }
    return S + sqrt(distance2(cities, cities + N - 1));
}


Extracting the src attribute and content of  tags in HTML files in a directory

You can use getattr function to merge your two functions into a single one.

def extract_attribute(src, attr_name):
    for file in os.listdir(src):
        filepath = os.path.join(src, file)
    with open(filepath) as f:
        html = f.read()
    parser = HtmlParser(html)

    yield from getattr(parser, attr_name)

Note that in Python 3.3+ there is yield from statement so you can yield values directly from iterable without writing for loop

Now if you still want to have two separate functions instead of passing attribute_name argument each time you can use function partial from functools

from functools import partial

extract_src_js = partial(extract_attribute, attr_name='src')
extract_int_js = partial(extract_attribute, attr_name='script_text')

Please also note that I've removed dst parameter from your functions since it was not used, however if it's just a part of your function you wanted us to review, just return it back.


Exposing configuration elements to program

Encapsulation

It's not really necessary that you expose these at all:

public static final String OUTPUT_PATH = "output_path";
public static final String NUM_THREADS = "num_threads";

Let the ConfigFactory be responsible for that, and save the actual values as instance variables, instead of using public ConfigParameter getValue(String s).

For example, instead of exposing getValue(String s), expose these:

public int getNumThreads() {
    ...
}

public String getOutputPath() {
    ...
}

Where the implementation of those methods could either be return getValue(SOME_KEY); or return this.numThreads; , if you add such private fields that you initialize after you've read the config file.

Testability, Dependency Injection

Why is this even a singleton? It's good that you have a method that takes a path so that you can use different configs, but your code leaves some things to be desired.

Immutability / Concurrency: It is currently possible that one thread reads a value, while another thread calls the build method for the Nth time.
Generics: ConfigParameter is using generics, but your getValue method simply returns ConfigParameter, you could change that to:

public <T> ConfigParameter<T> getValue(String s)

Mocking / Testing: If you would want to write unit tests (which you of course want to do), you would have to actually read a configuration file to be able to use the config. However, if you extract an interface, that exposes the important methods, such as getNumThreads() then you could easily create other implementations of this interface, which doesn't even have to read from a config file!

Additionally, instead of a enum I would use a static factory method.

Here's how to use it as an static factory method, although I hope you will take my other advice as well about extracting an interface etc:

public class MyConfig { // it's not a factory

    private Map<String, ConfigParameter> mSettings = new HashMap<String, ConfigParameter>();

    public static MyConfig build(String path) {
        MyConfig config = new MyConfig();
        InputStream inputStream = getClass().getResourceAsStream(path);
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
            inputStream.close();
            for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            // for brevity I only look for ints
            if(StringUtils.isNumeric(entry.getValue().toString())) {
                    config.mSettings.put(entry.getKey().toString(), new ConfigParameter<Integer>((Integer) entry.getValue()));
                } else {
                    config.mSettings.put(entry.getKey().toString(), new ConfigParameter<String>(entry.getValue().toString()));
                }
            }
            return config;
        } catch(IOException e) {
            return null; // return null to indicate that a problem occurred
            // although the best thing would be to throw an exception here
        }
    }

    // ... ConfigParameter and other stuff
}


One thing I noticed is that you're passing this.handleUpvoteClicked.bind(this) as a prop to your FlatButton components. The problem is that the call to Function.prototype.bind creates a new function instance for both click handlers every time your Post renders, meaning your FlatButton components see a different value (function reference) being passed in as a prop, and they'll also re-render. Probably not a big deal for your simple setup, but it's something to keep in mind for later, because it can drastically affect performance for bigger apps.

The solution is to bind your methods in the constructor. That way .bind(this) is only called once during construction (good because that method is a little slow), and your components will see a consistent function reference being passed in as a prop and will know they don't have to re-render.

I also tweaked your conditionals inside the click handlers a bit, so that they only run if the button isn't disabled.

Here's what I came up with:

import React, { Component } from 'react';
import { Card, CardText, CardHeader } from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';

class Post extends Component {

  constructor(props) {
    super(props);

    this.state = {
      disabledUpvote: false,
      disabledDownvote: false
    }

    this.handleUpvoteClicked = this.handleUpvoteClicked.bind(this);
    this.handleDownvoteClicked = this.handleDownvoteClicked.bind(this);
  }

  handleUpvoteClicked() {
    if (!this.state.disabledUpvote) {
      this.setState({
        disabledUpvote: true,
        disabledDownvote: false
      });
    }
  }

  handleDownvoteClicked() {
    if (!this.state.disabledDownvote) {
      this.setState({
        disabledUpvote: false,
        disabledDownvote: true
      });
    }
  }

  render() {
    const { content, createdAt, votes } = this.props.post;

    return (

        <Card>
          <CardText>

              {moment(createdAt).fromNow()}

            {content}

              <FlatButton
                label="Upvote"
                primary={true}
                disabled={this.state.disabledUpvote}
                onClick={this.handleUpvoteClicked} />
              <FlatButton
                label="Downvote"
                secondary={true}
                disabled={this.state.disabledDownvote}
                onClick={this.handleDownvoteClicked} />

          </CardText>
        </Card>

    );
  }
}

export default Post;


Update URL with new parameter value in controller action

I believe you want RedirectToActionPermanent:

if (myItem.Id != id)
{
    return RedirectToActionPermanent("EditItem", new { id = id })
}


Merge consecutive numbers in array into a range

Optimization review

Q1

  But I can see it looking ugly and not really optimized (code duplicating)

Ugly is somewhat subjective (2 spaced indents are ugly in my book), and sometimes unavoidable, as long as it is readable then looks don't matter.

Code duplication is not a code optimization problem, in fact it is often code duplication that creates the optimal performance. Duplication is a source code management / maintenance issue. Case in point 10th line the join string missing a space while the duplicated line 18 has the space. Duplication is a easy place to introduce a bug, it is a place where the brain will say "same" for what is just a little different

Duplication is simple to rectify using functions.

You have two identical blocks of code (lines 7-11 and 15-19). You can wrap those lines in a function and call the function rather than have the code inline. You may opt to pass the function the arguments or use closure to hold the variable and access them directly.

function collapseSequences(input){
   function pushResult(acc){
      const cs = acc.currSet;
      acc.out.push(cs.length > 2 ?
          `${cs.shift()}-${cs.pop()}` :
          cs.join(',')
      );
  }

  const output = input.reduce((acc, curr, i, arr) => {
      if (curr - 1 === arr[i - 1] || i === 0) {
        acc.currSet.push(curr);
      } else {
        pushResult(acc);
        acc.currSet = [curr];
      }
      if (i === arr.length - 1) {
        pushResult(acc);
      }
      return acc;
    }, { out: [], currSet: [] }
  );
  return output.out.join(', ');
}

Q2

  I would appreciate any suggestions on how to improve the code and make it look better and possibly work faster.

As a function

Always use a function to wrap any code. Code running in global scope is inherently slower due to how JS manages variables. The whole code should look more like

function collapseSequences(input) {
    ... the code

    // return the result
    return output.out.join(', ');
}

console.log(
    collapseSequences([ 12, 15, 16, 17, 19, 21, 22 ])
);

Use strict mode

Adding the run-time directive "use strict"; to the first line of a function or first line of a script allows the execution environment to make some assumptions and take some shortcuts improving performance (also forces you to write better Javascript)

Iteration

Loops are faster than iterators

const acc = foo;
for(const x of values) { ... code }

// or

const acc = foo;
for(let i = 0; i <values.length; i ++){ const x = values[i]; ...code }

will always be faster than

values.reduce((acc, x)=>{ ...code }, foo );

Strings

Strings are quicker than arrays. A common pattern is to use arrays when a string result requires a separator.

    // CPU benchmark 4.6 lower is faster
    function test(values){
        const res = [];
        for(const x of values){
            res.push(x * 10);
        }
        return res.join(", ");
    }

In terms of memory use GC impact, and CPU use the following can do the same in ~70% the time and much less memory.

    // CPU benchmark 3.8 lower is faster
    function test(values){
        var result = "";
        var join = "";
        for(const x of values){
            result += join + (x * 10);
            if (!join) { join = ", " }
        }
        return result;
    }

Growing a string is quicker than growing an array.
A string uses less memory than an array.
Array.join requires an additional iteration of items to build the string.

If you can, use a string rather than an array.

Benchmarking

If you want to write fast code then it is well worth investing time to learn how to correctly benchmark JS .

Bench-marking is one of the most difficult JS  coding skills to master.

Assuming code is faster based on time complexity is a common performance trap in JS . There is not always a 1 to 1 relation between bench-marked performance, and apparent time complexity. This is because complexity can be hidden in the native code.

JS performance is not always intuitive, nor can you assume that optimizations that worked yesterday still work today, or that slower code yesterday is still slower today. Browsers can update daily and updates do not always mean faster (New language features are particularly dynamic in terms of performance between updates)

Rewrite

Taking in the above performance points the function can be rewritten as

function collapseSequences(arr) {
    var i, val;
    var idx = 0;            // Array index
    var str = "";           // The result string
    const len = arr.length; // This is for readability not performance

    // The loop is terminated in its body to manage the seperator
    while (true) {
        i = 0;
        str += (val = arr[idx++]);

        // Look ahead for a sequence
        while(idx + i < len && arr[idx + i] === val + i + 1 ) {
            i++;
        }
        // Was here a sequence found ?
        if (i > 1) {        // add it to the string and skip over the sequence
            str += "-" + arr[(idx += i) - 1];
        }
        if (idx === len ) { // All done then return result
            return str;
        }
        str += ", ";        // add the separator
    }
}

Resulting in a 3 fold improved execution time.

Bench-marking details.

Tests results show mean execution time on same data sets

25,793µs ±1,853µs. Using strings
30,418µs ±1,346µs. Using arrays and array.join
79,534µs ±1,142µs. Your code

The test functions run on Win10 Firefox, run in strict mode.

//===============================================================
// Test 1 Using strings. 25,793µs ±1,853µs
function collapseSequences(arr){
    var i, idx = 0, str = "", val, len = arr.length;
    while (idx < len) {
        i = 0;
        str += (val = arr[idx++]);
        while(idx + i < len && arr[idx + i] === val + i + 1 ) { i++ }
        if (i > 1) { str += "-" + arr[(idx += i) - 1] }
        if (idx === len ) { return str }
        str += ", "
    }
}

//===============================================================
// Test 2 using arrays and array.join. 30,418µs ±1,346µs.
function collapseSequences(arr){
    var i, idx = 0, val, len = arr.length;
    const res = [];
    while (idx < len) {
        i = 0;
        val = arr[idx++];
        while(idx + i < len && arr[idx + i] === val + i + 1 ) { i++ }
        res.push(val +  (i > 1 ? "-" + arr[(idx += i) - 1] : "") );
    }
    return res.join(", ")
}

//===============================================================
// Test 3 OP original. 79,534µs ±1,142µs.
function collapseSequences(input){
    const output = input.reduce((acc, curr, i, arr) => {
      if (curr - 1 === arr[i - 1] || i === 0) {
        acc.currSet.push(curr);
      } else {
        if (acc.currSet.length > 2) {
          acc.out.push(`${acc.currSet.shift()}-${acc.currSet.pop()}`);
        } else {
          acc.out.push(acc.currSet.join(','));
        }
        acc.currSet = [curr];
      }
      if (i === arr.length - 1) {
        if (acc.currSet.length > 2) {
          acc.out.push(`${acc.currSet.shift()}-${acc.currSet.pop()}`);
        } else {
          acc.out.push(acc.currSet.join(', '));
        }
      }
      return acc;
    }, {
      out: [],
      currSet: [],
    })
    return output.out.join(', ');
}


Why does my implementation of the Sieve of Eratosthenes take so long?

The problem is that the way this is set up, the time complexity is (close to) \$O(n**2)\$. For each remaining prime, you run over the entire list.

In the last case, where you want to check for prime numbers up to 1,000,000 you end up iterating over your list 78,498 ** 2 times. 6,161,936,004 iterations is a lot to process.

Below is an approach that crosses off the numbers instead, editing the large list of numbers in-place. This makes for a \$O(n)\$ solution, which times as such:

range 10,000 : 549 usec per loop
range 100,000 : 14.8 msec per loop
range 1,000,000: 269 msec per loop
range 10,000,000: 3.26 sec per loop

def sieve_of_erastothenes(limit):
    """Create a list of all numbers up to `number`, mark all non-primes 0,
    leave all the primes in place. Filter out non-primes in the last step.
    """
    sieve = range(limit + 1)

    # There are no prime factors larger than sqrt(number):
    test_max = int(math.ceil(limit ** 0.5))

    # We know 1 is not a prime factor
    sieve[1] = 0

    # The next is a cheat which allows us to not even consider even numbers
    # in the main loop of the program. You can leave this out and replace the
    # current xrange(3, test_max, 2) with xrange(2, test_max)

    # All multiples of 2 are not prime numbers, except for 2 itself:
    sieve[4::2] = (limit / 2 - 1) * [0]

    for prime in xrange(3, test_max, 2):
        if sieve[prime]:
            # If the number hasn't been marked a composite, it is prime.
            # For each prime number, we now mark its multiples as non-prime.
            multiples_count = limit / prime - (prime - 1)
            sieve[prime * prime::prime] = multiples_count * [0]
    # Filter out all the zeroes, we are left with only the primes
    return filter(None, sieve)


Change text and styling of a form control when a slider value changes

You are duplicating a lot of code here. You said you wanted an array, so make an array containing all the values that change and then use the slideEvt.value to recall the values from the array at the correct index..

Something like this maybe.. no if() statements required (at least not for the slideEvt.value):

$("input#communication").on("slide", function(slideEvt) {
    var slideEvtVals = [
      {color: '#D0011B', css: {'border': '5px solid #fff', 'box-shadow': '0 0 0 2px #D0011B'}, text: 'Amir is a terrible communicator.'}
      {color: '#D0011B', text: 'Amir struggles, needs a lot of help to improve communication skills.'}
      {color: '#D0011B', css: {'border': '5px solid #fff', 'box-shadow': '0 0 0 2px #D0011B'}, text: 'Amir needs some help to improve communication skills.', handleBG: '#D0011B', selBg: '#D0011B'}
      {color: '#F47621', css: {'border': '5px solid #fff', 'box-shadow': '0 0 0 2px #F47621'}, text: 'Amir has below average communication skills.', handleBG: '#F47621', selBg: '#F47621'}
      {color: '#F47621', text: 'Amir has adequate communications skills.'}
    ];

    var index = slideEvt.value-1;
    $('#slider-val'+slideEvt.value).css('color', slideEvtVals[index].color);
    $('.slider-label').not('#slider-val'+slideEvt.value).css('color', '#ccc');
    if(slideEvtVals[index].css) $('.slider-handle').css(slideEvtVals[index].css);
    $("#desc").text(slideEvtVals[index].text);
    $("#desc").text(slideEvtVals[index].text);
    if(slideEvtVals[index].handleBG) $('.slider-handle').css('background', slideEvtVals[index].handleBG);
    if(slideEvtVals[index].selBg) $('.slider-selection').css('background', slideEvtVals[index].selBg);
});


How about

function move(field, player, dx, dy) {
    player.column = player.column + dx;
    player.row = player.row + dy;
    field[player.row][player.column] = 'P';
}

and instead of calling up(field, player), call move(field, player, 0, -1)? With your input, that would basically be

switch(input) {
case 'up':
    move(field, player, 0, -1);
    break;
case 'right':
    move(field, player, 1, 0);
    break;
case 'left':
    move(field, player, -1, 0);
    break;
case 'down':
    move(field, player, 0, 1);
    break;
}

I assume you'll have more code, like checking if the move is valid, resetting the field at the current player position, etc., which won't be duplicated this way. A more complete example might be

function move(field, player, dx, dy) {
    // Valid move?
    let newColumn = player.column + dx;
    let newRow = player.row + dy;
    if (newColumn < 0 || newColumn >= WIDTH ||
        newRow < 0 || newRow >= HEIGHT)
        return;
    // Player cannot hit wall
    if (field[newRow][newColumn] == 'X')
        return;

    // Make move
    field[player.row][player.column] = ' ';
    player.column = newColumn;
    player.row = newRow;
    field[player.row][player.column] = 'P';
}

  Edge cases will be implemented - if the next position is greater than the dimensions of the field, etc. So I'm not sure if this will impact making it more efficient

It might seem unnecessary to verify newColumn when you're making a move in the y (row) direction, but comparisons like that are extremely cheap and you shouldn't be worried about their performance.


Answers to Questions

  I want to have a thin wrapper (low overhead) around c-style string.

I am not sure this class is 'low-overhead' compared to std::string or even a C-String. Because it still has all the overhead of creating dynamic space and copying.

Low-overhead: To me this means the cost of creating the object. If you use this as you measurement then you have not achieved your goal. The cost is about the same as both a std::string and C-String.

Now. It has memory management abilities of std::string but has a smaller footprint. It is the same size as a C-String but the advantage of memory management.

So it has some extra advantages (just not low overhead).

  Also, with some additional features like == and < operators for map indexing.

Which is useful; like it.

  Can somebody comment on it?

Not a problem.

  From what I've gathered this class would take only as much memory as a pointer.

Probably.
But you can always test this by using sizeof() to find out for sure.

  so much less than std::string.

It's probably about one third the size of a std::string (you can't make a definitive statement because the standard does not specify how to implement it).

Now a third sounds like a lot. But if a pointer is 4 bytes then a std::string would probably be 12 bytes. Not a great saving. Especially since the std::string has several other advantages (small string optimization: if the string is less than 12 bytes there is no dynamic memory allocation).

  I also heard that this class has more overhead (execution-wise) than std::string and indeed that is the case for the constructor (char *), copy constructor and move constructor. Can somebody explain why?

I don't believe that. Your code is pretty optimal in those terms.

Review of Code

Not sure why this is a standalone function? Why not make it a private member of the class.

inline char * dupStr(const char * s){
    if(!s){return nullptr;}           // Sure. Why save the space
                                      //       Do this on multiple lines.
                                      //       The point is to make the code
                                      //       readable.
    size_t l = strlen(s) + 1;
    char * d = new char[l];
    memcpy(d,s,l);
    return d;
}

The move constructor. You should mark the move constructor as noexcept:

        CString_(CString_ &&that) noexcept
            : s_(that.s_)
        {
            that.s_ = nullptr;
        }

This is because the standard containers require this to do an optimal operations. If you don't specify this then they will fall back to using the copy constructor (note: only mark it as noexcept if it really is).

Sure you can do a get:

        const char * get() const {return s_;}

But it is sometimes also useful to define the cast operator:

        const char * operator() const {return get();}

This is useful so you can use CString_ in any location that you could use a C-String without having to change the code.

Low-Overhead.

If I was thinking low-overhead. Then I would make the class take ownership of the string object. That way there is no dynamic allocation or copying. But you get the advantages of RAII (so automatic destruction).

In addition I would get store the size. One of the largest cost of a C-String is repeatedly calculating the size of the string (we switched some old code from using C-String to std::string (a big job)). But we got a 40% speed increase.

The problem is how the C-String was created (malloc() or new). We can make the assumption that the user will only use string that come from C libraries. The problems are that you can't check and make that guarantee (one of the reasons std::string makes a copy).

 class CStringOwner
 {
      char*        data;
      std::size_t  size;
      public:
          CStringOwner(std::nullptr_t)
              : data(nullptr)
              , size(0)
          {}
          explicit CStringOwner(char* data)
              : data(data)
              , size(data ? strlen(data) : 0) // make sure null ptrs are correctly handled.
          {}

          // Copy.
          CStringOwner(CStringOwner const& copy)
              : data(reinterpret_cast<char*>(malloc(copy.size+1)))
              , size(copy.size)
          {
              if (data == nullptr) {
                  throw std::bad_alloc("CStringOwner::CStringOwner: Copy: Failed on Malloc");
              }
              std::copy(copy.data, copy.data+copy.size+1, data);
          }
          CStringOwner& operator=(CStringOwner copy)
          {
              copy.swap(*this);
              return *this;
          }

          // Move
          CStringOwner(CStringOwner&& move) noexcept
              : data(nullptr)
              , size(0)
          {
              move.swap(*this);
          }
          CStringOwner& operator=(CStringOwner&& move) noexcept
          {
              move.swap(*this);
              return *this;
          }

          // Destroy
          ~CStringOwner()
          {
              free(data);
          }
          void swap(CStringOwner& other) noexcept
          {
              using std::swap;
              swap(data, other.data);
              swap(size, other.size);
          }

          // Other shit goes here.
  };


Just about the only thing I could comment on is your indentation the last two brackets

        launcher.setLocation(dim.width/2-launcher.getSize().width/2, dim.height/2-launcher.getSize().height/2);
         }
    }

should be:

        launcher.setLocation(dim.width/2-launcher.getSize().width/2, dim.height/2launcher.getSize().height/2);
     }
}

Your variables:
VER, STATE, WIDTH, HEIGHT and SCALE could be set to final.

And last but maybe irrelevant. SCALE is not used, but maybe you're going to use it later. What do it know. :)


Transforming class names to method names

If this is Rails, you've got the #underscore mixin from ActiveSupport at your disposal, which'll at least take care of the last bit.

As for the naming in general, I'm wondering what purpose the full names serve, if so much of them is just dropped. I'm not saying it's wrong, I'm just wondering. Especially as it seems like the transformations are one-way.

What I mean is that the class OrderByBestValueFilter becomes just best_value, effectively "throwing away" a lot of information in the name. If said information can be thrown away, was it even necessary in the first place?

As for the transformations being one-way, it's just another indication that the class name → criterion* string rule is a little informal. The string best_value could come from a class called BestValue, ByBestValue, BestValueFilter, or some other combination. Yet I'd imagine an OrderByXyzFilter is semantically different than a ByXyzFilter: The former takes a collection and sorts its elements without removing anything, while the latter takes a collection and removes elements not matching some predicate. Yet despite being very different, both would just end being called xyz. I just find that a little suspicious.

My thinking is also that you can side-step the entire thing by, for instance, putting your classes in a Filters module. Within that namespace, they could just be called BestValue and so forth. Or each class can declare its "criterion name" in some explicit way, e.g. as a class method.

Again, I don't know your code. I'm just thinking out loud.

As for the way you're doing things now, it's not too bad, though using array subtraction is a bit much just to remove parts of a string. It could be made a little neater with a combined regexp:

name = self.class.name.split('::').last
name.gsub(/(^(Order)?(By)?|Filter$)/, '').gsub(/([a-z])([A-Z])/, '\1_\2').downcase

I've anchored matching to avoid something like ByFilterSizeFilter becoming just size.

*) it's criterion when it's singular; criteria is plural


Delete each character in one string that matches any character in another

What you have is an O(n^2) solution.

But lets look at tidying it up first:

Do you really need these macros.
If you must have them then why not name the variable copy and use the macros TRUE/FALSE

#define COPY   1
#define NOCOPY 0

Declaring variables using the comma is lazy and considered bad practice, but you should also use more descriptive variable names. i/j/k do not explain what they are being used for. Also if you function is longer and you need to change it looking for all instances of a variable 'i' may take a while longer because of all the false positives on a search so maintenance wise it is also a bad idea.
There are a couple of edge cases where the declaration can go wrong. So in general it is just best to stay clear.

int i, j,k, state;

You are using a while() loop. But a for(;;) loop would have been neater. It allows initialization test and increment in the same statement. This puts all work done on the k variable in the same place.

    while (f[k] != '\0' && state == COPY)

Are you sure you actually want to do this test?

        if (tolower(f[k]) == tolower(s[i]))

OK. The heart of the problem. Use of the state variable.
The reason you have this test is to break out of this while loop and then avoid doing the actual work in the next loop. You already have the failed state information implicitly by the place you are in the loop while testing so all you need to do is break out of the current loop. You do not need to do an explicit test in the condition but just use a break statement.

            state = NOCOPY;

So if we re-write your version taking into account my comments we get:

void multisqueeze(char s[], char f[])
{
    int i     = 0;  // Iterate over s[]
    int j     = 0;  // Iterate over s[] as elements are copied (this is the dst)

    for(i = 0; s[i] != '\0'; ++i)
    {
        int k     = 0;                    // Iterate over f[]
        for(k = 0; f[k] != '\0'; ++k)
        {
            if (tolower(f[k]) == tolower(s[i]))
            {
                break;
            }
        }

        if (f[k] != '\0') // Then we never reached the end of the loop
        {                 // This means we found a match in the f[] array
            s[j++] = s[i];
        }
    }
    s[j] = '\0';
}

But there is an O(n) solution.
What you need to do is convert the search of the second string into a single comparison.

Since char is a limited range (0-255) we can swap space for time.
Allocate an array that represents every character possible character. Then we can use this as a way to look-up the existence of a character.

So rather than doing this:

        for(k = 0; f[k] != '\0'; ++k)
        {
            if (tolower(f[k]) == tolower(s[i]))
            {
                break;
            }
        }

for each iteration of s[]. What you want to do is iterate over f[] once and save the state of each character. So that you can just look up the answer in one step rather than an iteration. To do this we hoist this loop out of the inner loop and allocate an array for all possible values of char, then mark any we find in f[] as true in our allocated array.

This is what mine would look like (actually mine would look slightly different as I would have written in the C++ style but I have translated into C to make it consistent with the question).

void squeeze(char s[], char f[])
{
    int   loopF;
    int   loopS;
    int   squeeze   = 0;
    int   test[256] = {0};            // One for each character. Default to false.
                                      // I would use bool here. But C does not have bool
                                      // Could use char to save space but that can be confusing
                                      // as not everybody considers a char as an integer type.

    for(loopF = 0; f[loopF] != '\0'; ++loopF)
    {    test[tolower(f[loopF])]  = 1;    // Mark every character in test that is in f as true.
         test[toupper(f[loopF])]  = 1;    // Thus we can test for existence just by looking it up
    }

    for(int loopS=0; s[loopS]; ++loopS)
    {
          if (test[s[loopS]])          // Test to see if the character in s is also marked true in test.
          {    squeeze++;
               continue;
          }
          // move characters down the squeezed amount
          s[loopS-squeeze] = s[loopS];
    }
}


Making my Rock, Paper, Scissors game shorter

You code looks unclear from point of view of parameter usage and ignoring case difference is case of "The result is a tie.", so ...

Try this :).

public class testik {
    // No throws clause here
    public static void main(String[] args) {
        // Paper < Rock < Scissors < Paper
        System.out.println("Comp:S vs User:R = " + determineWinnerOtherWay("S","R")); //user win
        System.out.println("Comp:S vs User:P = " + determineWinnerOtherWay("S","P")); // com win

        System.out.println("Comp:P vs User:R = " + determineWinnerOtherWay("P","R")); //com win
        System.out.println("Comp:P vs User:S = " + determineWinnerOtherWay("P","S")); // user win

        System.out.println("Comp:R vs User:S = " + determineWinnerOtherWay("R","S")); //com win
        System.out.println("Comp:R vs User:P = " + determineWinnerOtherWay("R","P")); // user win
    }

    public static String code2Title(String code){
        if ("R".equals(code)) {
            return "Rock";
        } else if ("P".equals(code)) {
            return "Paper";
        } else {
            return "Scissors";
        }
    }

    public static String determineWinnerOtherWay(String compChoice, String playChoice) {
        String winner = "";
        String playerChoiceN = playChoice.toUpperCase();
        if (playChoice.equals(compChoice))
            winner = "The result is a tie.";
        int diff = compChoice.charAt(0) - playerChoiceN.charAt(0);
        if ( diff == 1 || diff == 2 || diff ==-3) {
            winner = "User win bacause:"+code2Title(playerChoiceN)+" wins " + code2Title(compChoice);
        } else {
            winner = "Computer wins because:"+code2Title(compChoice)+" wins " + code2Title(playerChoiceN);
        }
        return winner;
    }

}


Performance for simple code that converts a RGB tuple to hex string

You seem to be jumping through some unnecessary hoops. Just format a string directly:

from timeit import timeit

def _channel_to_hex(color_val: int) -> str:
    raw: str = hex(color_val)[2:]
    return raw.zfill(2)

def rgb_to_hex(red: int, green: int, blue: int) -> str:
    return "#" + _channel_to_hex(red) + _channel_to_hex(green) + _channel_to_hex(blue)

def direct_format(r, g, b):
    return f'#{r:02x}{g:02x}{b:02x}'

def one_word(r, g, b):
    rgb = r<<16 | g<<8 | b
    return f'#{rgb:06x}'

def main():
    N = 100000
    methods = (
        rgb_to_hex,
        direct_format,
        one_word,
    )
    for method in methods:
        hex = method(1, 2, 255)
        assert '#0102ff' == hex

        def run():
            return method(1, 2, 255)

        dur = timeit(run, number=N)
        print(f'{method.__name__:15} {1e6*dur/N:.2f} us')

main()

produces:

rgb_to_hex      6.75 us
direct_format   3.14 us
one_word        2.74 us

That said, the faster thing to do is almost certainly to generate an image in-memory with a different framework and then send it to tkinter.


Well, the function kind-of sort-of violates SRP...but according to Uncle Bob, I think your class violates the SRP moreso than the function.

Your class above, has three functions within it: getArrayOfThemeNames(), loadUnfilteredDirectoryListing(), and loadThemeFiles(). One of them scans the directory, one of theme creates an array of theme names, and another loads the theme files. One of those methods should not be in there: loadUnfilteredDirectoryListing should be in its own class called DirectoryLister{} or something. Which means, by extension, that getArrayOfThemeNames() is in violation of SRP. To quote Atwood - SRP is about "choosing a single, clearly defined goal for any particular bit of code: Do One Thing ... But in choosing one thing, you are ruling out an infinite universe of other possible things you could have done. It also means consciously choosing what your code won't do.". So in the end, its up to you whether this violates SRP and whether you would choose to follow SRP so deeply that you violate OOP or DRY.

Perhaps someone with more experience can chime in or prove me wrong (heck, always good to learn something from someone else)

EDIT: See (http://www.oodesign.com/single-responsibility-principle.html) article as well for clarification.

REVISIT 01/26/2015: Revisiting this answer, I would rewrite the code as follows:

class Theme {
    public $theme_directory;
    public $theme_files;

    public function __construct($theme_directory){
        $this->theme_directory = $theme_directory;
    }

    public function get_theme_names() /* Array */ {
        $this->load_theme_files();
        return $this->theme_files;
    }

    private function load_theme_files(Directory $directory) /* Null */ {
        $directory->directory = $this->theme_directory;
        foreach($directory->load_unfiltered() as $file) {
            if($file != '..' && $file != '.') {
                $this->theme_files[] = $file;
            }
        }
    }
}

class Directory {
    public $directory;

    public function __construct() {
        $this->directory = $directory;
    }

    private function load_unfiltered() /* array */ {
        return  scandir($this->directory);
    }
}


Count cars passing in opposite directions

def solution(a)
  results = 0
  east_count = 0
  a.each do |el|
    if el == 0
      east_count += 1
    else
      results += east_count
    end
    return -1 if results > 1000000000
  end
  results
end

Note that you don't have to compare each car to every other car.  You just have to track how many are traveling east and each time you find someone going west, increment your results by the eastbound count.  I find this easier to understand than tracking the westbound cars backwards.

r | c
--+--
0 | 0
0 | 1
1 | 1 (0,1)
1 | 2
3 | 2 (0,3), (2,3)
5 | 2 (0,4), (2,4)

In the table, r stands for results and c stands for east_count.  The pairs found at any point are to the right.

This will not find the pairs that pass, but it does count them.  It maintains the required \$P < Q\$ by order of iteration.

I don't know much about Ruby, so I won't try to make syntactic comments.  Apologies if my own syntax is weak.

This iterates through the array once, so it's \$O(n)\$ in time.  It defines a constant number of scalar variables, so it's \$O(1)\$ memory beyond the input array.


How can I make only one if-else statement among all of these?

If each ID1 can only have one valid corresponding ID2, then I would recommend using a  dictionary object to store the valid combinations, like this:

Dictionary<string, string> validIds = new Dictionary<string,string>();
validIds[ValidationFields.FO.ToString()] = ValidationTypes.P.ToString();
validIds[ValidationFields.FW.ToString()] = ValidationTypes.P.ToString();
validIds[ValidationFields.UF.ToString()] = ValidationTypes.P.ToString();
// ...

Then, you can check to see if the currently selected values are valid by simply comparing them to the valid combinations in the dictionary, like this:

if (validIds[ddlBr1Type.SelectedValue.ToString()] != ddlBr2Type.SelectedValue.ToString())
{
    BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
    args.IsValid = false;
}

By doing it that way, you only need the single if statement.  Another side benefit is that you can now store the list of valid combinations somewhere else, outside of your code, such as in a configuration file or a database.  Then you could load the data from that data source into the dictionary at run-time.


The repository does not need to take responsibility for the errors - remove them from here. The flight repository should add CRUD operations to Flight Dto and not return a result - remove the result. Validation should be done before calling the methods. You are not an automapper, use a tool. You do not need to invent a bicycle every time you need a new repository, use generics. Additionally, you do not need to repeat Flight in every method name, they exist in the Flight repository you can infer that from context.
All error messages should be unique.

For example, implement an interface:

public interface IRepository<T> where T : EntityBase
{
    T GetById(int id);
    IEnumerable<T> List();
    void Add(T entity);
    void Delete(T entity);
    void Edit(T entity);
}

public abstract class EntityBase
{
   public int Id { get; protected set; }
}

For more info: https://deviq.com/repository-pattern/

The model that contains the list of flights should contain the validation rules and validate flights or the model of the Flight should validate itself.

What you get from the database is not a Flight model, but a dto. You should use a translator to create a model from dto. Dto's should not contain any business logic just data. Clear separation of concerns helps is needed for clear code.


Single class which holds response and error message

Is that error, or status, or both, or neither?

This API is a bit confusing.
You have ErrorCode and StatusCode enums. But ErrorCode contains things like:

OK(200, "NONE", "Response is success."),
NO_CONTENT(204, "No Content", "Response is success."),
CLIENT_TIMEOUT(1007, "Timeout", "Timeout has occured on the Client.");

So two of the "error codes" indicate success.

public enum StatusCode {
    SUCCESS, ERROR;
}

... And StatusCode can indicate success or error.

... The confusing nature of these elements make it difficult to understand the API, and the distinction of its building blocks.

Your error codes resemble HTTP status codes. Why not go a bit further in following HTTP practices, and have just one Status enum, that contains status codes like in the HTTP protocol, some of which are success, and others are error.

DataResponse

I like that the class is immutable.
But I'm concerned about the long parameter list of the constructor,
especially considering that the first 4 values are all of String type,
which can lead to errors such as mistaken ordering.

I would suggest to consider adding a builder,
that will have well-named setters to set the parameter values,
possibly allowing some sensible defaults.

Lastly, the type of the date field is a String.
It would be good to add a JavaDoc about the required format.
(For that matter, a JavaDoc for the other String parameters would be good too.)


Small nits from my side.

You are always using for (auto foo : bar). This involves a copy of foo. If you do not alter foo then you should use for (const auto& foo : bar)
As far as i know it is more idiomatic to check for existense of an element in a set via count. So rather than Visited.find(n) != Visited.end() you can check Visited.count(n) or the in my opinion way better Visited.count(n) != 1
Your code assumes every node is unique. You might want to adopt to a more robust approach utilizing a struct node that holds the data and then wr on pointers to that node


Occurrences (frequency count) - exercise 3 ch. 3 in "ansi common lisp"

Use primitive functions and operators as much as possible

You are defining remove-dups, and in this function you use the primitive adjoin, which adds an element to a list if not already present. But in Common Lisp the primitive function remove-duplicates is also available, that returns a list without duplicates.

Instead of (+ expression 1) use the primitive 1+ function: (1+ expression).

To iterate over a list there are convenient primitives iterative constructs, like dolist and loop (see below).

Alists

If you want to use alists, it can be more clean to use the primitive operators already defined on them, like acons, pairlis, assoc. For instance, the program could be simplified in this way:

(defun occurrences (lst)
  (let* ((elements (remove-duplicates lst))
         (alist (pairlis elements (make-list (length elements) :initial-element 0))))
    (loop for x in lst
          do (incf (cdr (assoc x alist))))
    alist))

Note that the counters inside the alist are incremented with incf; in fact another suggestion of mine is “don’t by shy to use modifying primitives”, when you are modifying things locally to some function and are sure no undesirable side-effects arise.

Hash tables

Another suggestion is: use the data structures for the task at hand. In Common Lisp there are hash tables, which are ideal for problems like yours. For instance:

(defun occurrences (lst)
  (let ((table (make-hash-table)))
    (loop for x in lst
          do (incf (gethash x table 0)))
    (loop for k being the hash-key of table
          using (hash-value v)
          collect (cons k v))))

This is of course the most efficient solution of all, since it is of O(n), and it scans only once the input list. At the end you could sort the elements returned by their car, and remember always that all the primitive functions that need to do comparisons use by default eql but can be called with an extra keyword parameter :test to chose another comparison predicate, as for instance equal to compare complex values as lists. This applies to remove-duplicates, assoc and make-hash-table.


Pascal's Triangle without using combinations

Someone already commented about not using recursion but if you still want to keep it, here are my comments.

There are quite a few style issues, if you install the pep8 command and run from the command line pep8 pascal.py (or whatever the filename is), you'll see them (multiple statements on one line, missing whitespace around operator, line too long).

Other than that, a few things:

I'd definitely check that the input is a number, you don't want to feed letters or other characters to your function.
The input_list parameter should be initialized properly. It's supposed to be a list, not an integer. But since it's not nice to initialize it to [], you can set it to None and check on that. (For an explanation why this is not nice, you can have a quick look here)
Your function name is pascal_t, to me that looks like it returns a pascal triangle, while it actually prints it. I'd say either rename it to print_pascal_t or make it return an object and print that.
A lot of comments. You can remove quite a few of them just by giving proper names. For example, count can be renamed to rows_number and you can remove the first line. You can be more explicit with the first check (if rows_number <= 0: ) and remove that comment, too. The other comments are simply describing what happens. I think good comment should be describing why things happen, otherwise it's either useless, or you need to write code more clearly.
The first check on if not index is useless, you can remove that part of code.
You also don't need to create an array with a single element so that you can map, cast and join it.
You exit() the program inside of your function instead of just returning. I'd check if input_list is None and just return in that case.
The formatting line can be converted to something much simpler using, well, format :-)
Just as a side note, this will not work properly in python3.

Modified code:

def pascal_t(rows_number, input_list = None):
    if rows_number <= 0:
        return

    if not input_list:
        print(rows_number * "   "), "1"
        pascal_t((rows_number - 1), [1])
        return

    created_array = []

    for index in range(len(input_list)):
        if (index + 1) == len(input_list):
            created_array.extend((input_list[index - 1] + input_list[index], input_list[index]))
        else:
            created_array.append(input_list[index - 1] + input_list[index])

    formatted_list = ['{0: <5}'.format(str(num)) for num in created_array]

    print rows_number * "   ", " ".join(formatted_list)
    pascal_t((rows_number - 1), created_array)

user_input = raw_input("Enter Number of Rows(1-20) for Pascal's Triangle: ")
try:
    rows_number = int(user_input)
except ValueError:
    print "Not a valid number"
else:
    pascal_t(rows_number)


Loading settings from a file to a dictionary

Pointless locking

You lock in two places:

When loading the configuration file, during construction. This lock will never be contested: no two threads will ever wait on this lock, because every object has its own, different, private lock
When getting a value from the dictionary. This lock may be contested in theory by multiple threads trying to get values, but there is no reason to lock for that. It would simply slow down high throughput of requests, with no benefits

You can safely remove the locking completely.

Exception handling

loadSettings catches exceptions during file loading, logs and returns a boolean. It would be simpler to not catch exceptions here, let them be thrown, and return void.

Since an instance of this class is unusable if an error happens during file loading, consider not catching any exceptions at all, let them be thrown, and let the caller handle the situation.

That will also allow you to remove the null check in the getSetting method, as the dictionary will never be null. Which is nice, as it's always easier to understand a class when you know it can never be in an invalid state.

Further improving loadSettings

Clearing the settings dictionary in this method is pointless. It would be better to create the dictionary here and return it.


1. Introduction

The only actual question you asked is about how to make the inverse Burrows–Wheeler transform go faster. But as you'll see below, that's plenty for one question here on Code Review. If you have anything to ask about your LZ77 and LZ78 implementations, I suggest you start a new question.

2. A bug

First, the output of the function ibwt doesn't match the example output in the question:

>>> from pprint import pprint
>>> pprint(ibwt('ssyxxiit'))
['iisstxxy',
 'xxiiysts',
 'stxxsiyi',
 'iystixsx',
 'xsiyxtis',
 'tixssyxi',
 'yxtiissx',
 'ssyxxiit']

You should always prepare your question by copying and pasting input and output from source files and from an interactive session, rather than typing in what you think it should be. It's easy to introduce or cover up mistakes if you do the latter.

So it looks as if there is a missing transpose:

>>> pprint(transpose(ibwt('ssyxxiit')))
['ixsixtys',
 'ixtysixs',
 'sixsixty',
 'sixtysix',
 'tysixsix',
 'xsixtysi',
 'xtysixsi',
 'ysixsixt']

3. Avoiding transpositions

With that bug fixed, let's see how long the function takes on a medium-sized amount of data:

>>> import random, string
>>> from timeit import timeit
>>> s = ''.join(random.choice(string.printable) for _ in range(1024))
>>> t = bwt(s)
>>> timeit(lambda:ibwt(t[1]), number=1)
49.83987808227539

Not so good! What can we change? Well, an obvious idea is to cut out all those calls to transpose. The function ibwt transposes the matrix in order to sort it, and then transposes it back again each time round the loop. By keeping the matrix in transposed form throughout, it would be possible to avoid having to call transpose at all:

def ibwt2(s):
    """Return the inverse Burrows-Wheeler Transform matrix based on the
    string s.

    >>> ibwt2('SSYXXIIT')[3]
    'SIXTYSIX'

    """
    matrix = [''] * len(s)
    for _ in s:
        matrix = sorted(i + j for i, j in zip(s, matrix))
    return matrix

That simple change results in a big improvement:

>>> s = ''.join(random.choice(string.printable) for _ in range(1024))
>>> t = bwt(s)
>>> timeit(lambda:ibwt2(t[1]), number=1)
0.9414288997650146

4. Aside on programming style

Something that's perhaps worth mentioning at this point is that you seem quite keen on transforming code so as to use a functional style (for example in this question, where you wanted to express a loop using reduce). Transforming code into pure functional form is an excellent intellectual exercise, but you have to be aware of two problems that often arise:

Pure functional programs can easily end up doing a lot of allocation and copying. For example, it is often tempting to transform your data into a format suitable for passing in to a function (rather than transforming your function so that it operates on the data you have). Thus in ibwt it is convenient to call sorted on the data in row-major order, but convenient to append a new instance of the string s in column-major order. In order to express both of these operations in the most convenient way, the function has to transpose the matrix back and forth, and since it do so functionally, each transposition has to copy the whole matrix.
Pursuit of pure functional style often results in tacit or point-free programming where variable names are avoided and data is routed from one function to another using combinators. This can seem very elegant, but variable names have two roles in a program: they don't just move data around, they also act as mnemonics to remind programmers of what the data means. Point-free programs can end up being totally mysterious because you lose track of exactly what is being operated on.

Anyway, aside over. Can we make any more progress on the inverse Burrows–Wheeler transform?

5. An efficient implementation

If you look at what the inverse Burrows–Wheeler transform does, you'll see that it repeatedly permutes an array of strings (by sorting them). The permutation is exactly the same at each step (exercise: prove this!). For example, if we are given the string SSYXXIIT, then at each step we apply the permutation SSYXXIIT → IISSTXXY, which (taking note of where repeated letters go) is the permutation 01234567 → 56017342.

This observation allows us to reconstruct a row of the matrix without having to compute the whole matrix. In this example we want to reconstruct row number 3. Well, we know that the final matrix looks like this:

I.......
I.......
S.......
S*......
T.......
X.......
X.......
Y.......

so the first element of the row is S. What's the next letter of this row (marked with *)? Where did this come from? Well, we know that the last step of the transform must have looked like this:

S0......         I5......
S1......         I6......
Y2......    ->   S0......
X3......    ->   S1......
X4......    ->   T7......
I5......    ->   X3......
I6......         X4......
T7......         Y2......

So the * must have come from row 1 (which is the image of 3 under the permutation), and so it must be I (which is element number 1 of the sorted string IISSTXXY).

We can follow this approach all the way along the row. Here's an implementation in Python:

def ibwt3(k, s):
    """Return the kth row of the inverse Burrows-Wheeler Transform
    matrix based on the string s.

    >>> ibwt3(3, 'SSYXXIIT')
    'SIXTYSIX'

    """
    def row(k):
        permutation = sorted((t, i) for i, t in enumerate(s))
        for _ in s:
            t, k = permutation[k]
            yield t
    return ''.join(row(k))

Let's check that works:

>>> ibwt3(3, 'SSYXXIIT')
'SIXTYSIX'
>>> s = ''.join(random.choice(string.printable) for _ in range(1024))
>>> t = bwt(s)
>>> ibwt3(*t) == s
True

and is acceptably fast:

>>> timeit(lambda:ibwt3(*t), number=1)
0.0013821125030517578

(If you compare my ibwt3 to the sample Python implementation on Wikipedia you'll see that mine is not only much simpler, but also copes with arbitrary characters, not just bytes in the range 0–255. So either I've missed something important, or the Wikipedia article could be improved.)


How to sort array by divisor sum faster?

Many elements of this code can be much faster.

Calculating the sum of divisors will be faster if you:

Iterate until sqrt(number) instead of number / 2, and include divisor pairs (i and number / i)
Change the type of number from double to int

(See also my review of your related question.)

Use a faster sorting algorithm, for example quicksort or merge sort.
And when you, avoid mistakes like if(( divisorSum( array[ i ]) > divisorSum( array[ j ])) || (( divisorSum( array[ i ] ) == divisorSum( array[ j ])) && ( array[ i ] > array[ j ]))), which recomputes the sum of divisors twice for array[i] and array[j].
You could store the results of expensive operations in a variable,
and then you can use that variable multiple times in conditions.


VBA script to add formulas to Excel is running slow

When working with Excel and writing to cells the most common performance issue come from the sheet being constantly updated in the background while the script is running. In order to gain more speed you should save the state of a few properties for as long as the script is running and restore their values when it finishes.

For example:

Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

Reference: Excel VBA Performance Coding Best Practices


Using method which return a String or creating wrapper for String

I think the first approach is the best; it uses more design-patterns:

You throw an IllegalArgumentExcaption but pk is not an argument of the method.

From JavaDoc:

  Thrown to indicate that a method has been passed an illegal or inappropriate argument.

You throw an IllegalArgumentExcaption because of a null. It should be a NullPointerException - it's more meaningful. Objects.requreNonNull() does it for you automatically. A NullPointerException would be automatically thrown in 2 lines later, so no need for a check except you would like to add a custom message to the NullPointerException. That would be a good idea.
The Class who has the .getPk()-method can have a null as a PrimaryKey; it looks like a design-flaw? Anyway, if this instance who has the .getPk()-method can have an illegal state, then an IllegalStateException should be thrown.
The toString() implementation is good.
OrganizationPrimaryKeyString is a good read-only object. Read-only objects are good for memory because you do not need to have two instances of the same organisation. But if you call getInformation() one million times for ibm, then every call to getInformation() returns one million equal ibm-objects that are not the same but require its own memory in the heap! A HashMap may help caching, so every call for ibm can return one of the same object.
The naming is good and meaningful. getInformation() should be named getInformations() and OrganizationPrimaryKeyString should only be named OrganizationPrimaryKey.
OrganizationPrimaryKey should be static because YDKJ: A subclass that is not static automatically has the wrapped-class as constructor-argument who internally is cached as a field of OrganizationPrimaryKey. Trust me, every Constructor of OrganizationPrimaryKey caches the OOP-Instance.


Is it ok to use Thread.Sleep and Thread.Interrupt for pausing and resuming Thread like this?

This is pretty bad.

Instead why not use BlockingCollection. Then the loop will be:

try
{
    while(true)
    {
        doSomethingWith(queue.Take());
    }
}
catch(InvalidOperationException e)
{
    // ignore and cleanup
}

And to stop the thread you need to call CompleteAdding() on the queue.