Is this the correct way to expose a setting for a vb.net class library?

I think it's a fairly verbose way of exposing app settings. How about this?

(taken from an answer on this SO question)

This essentially comes down to what @KonradRudolph's comment was saying - the reason you "need" your Settings module is probably because the settings' access modifier is set to Internal, which means it's not accessible to other assemblies.

If you need to expose app settings to other assemblies, you just change that access modifier to Public and you're done.

Doing this:

Public Module Settings
    Public Property AppSettings As Settings
        Get
            Return My.Settings
        End Get
    End Property
End Module

Is then totally redundant. Even more so, doing what you've done (exposing each setting individually) becomes more painful to maintain than it needs to be; if the settings are public then you expose the settings class itself and whatever you change is immediately available to client assemblies.


I suggest some optimizations:

Do not initialize columns with empty JSONArray - it will always be overwritten.
Do not iterate twice and do not create overhead ArrayList object you can iterate json object once.
Due to Android specific garbage collection it's better to reuse object than create a new one in each iteration (see where is declared ContentValues cv = new ContentValues(); and cleared then later).
Open database once not in loop -> be sure to close it (finally block).
Your error reporting is leaky - the next db.replace would clear off the former errCheck value - I added some simple handling but I did not know the requirements in that area.

private boolean prepReturnedData(String newString) throws JSONException {
    JSONObject jsonObj = new JSONObject(newString);

    if(jsonObj.length() > 0) {
        Iterator<?> tableKeys = jsonObj.keys();
        SQLiteDatabase db = null;

        try {
            db = getWritableDatabase();
            db.beginTransaction();

            ContentValues cv = new ContentValues();

            String table;
            JSONArray columns;

            String status;
            int columnsLength;
            JSONObject columnJson;
            Iterator<?> columnKeys;

            String tColumn;

            while (tableKeys.hasNext()) {
                table = tableKeys.next().toString();
                columns = jsonObj.getJSONArray(table);
                status = table == "Seizures" ? "timestamp" : "name";
                columnsLength = columns.length();

                for (int i = 0; i < columnsLength; i++) { // Loop through Array of Entries
                    cv.clear();

                    columnJson = columns.getJSONObject(i); // Creates a new JSONObject for retrieving column values.
                    columnKeys = columnJson.keys(); // Creates an Iterator containing Column names.

                    while (columnKeys.hasNext()) {
                        tColumn = columnKeys.next().toString();
                        cv.put(tColumn, columnJson.optString(tColumn, ""));
                    }

                    if(db.replace(table, status, cv) == -1L) {
                        throw new IllegalStateException(
                                "Insert failed for table: " + table +
                                ", contentValues: " + cv.toString());
                    }
                }
            }

            db.setTransactionSuccessful();
        }
        catch(Throwable e) {

            return false;
        }
        finally {
            if (db != null && db.isOpen()) {
                db.endTransaction();
                db.close();
            };
        }
    }

    return true;
}


Displaying a String array in tabular format

First you should use a Method for repeating a character/String (if there isn't one yet. Don't know, never need it so far). Like a repeat-Method ->

    public String repeat(int times, String str) {
        // Add some security checks ofc, just to show what I mean.
        String r = "";
        for (int i=0; i < times; i++) r += str;
        return r;
    }

So, since multible characters won't be a problem now anymore:

    // ...
    // Amount of columns you want to have
    int col = 3;
    // Maximal Length of a String you support
    int len = 20;
    for (int i=0; i < theArray.length; i+=col) {
        System.out.println(repeat(len+col+1,"-"));
        System.out.print("|");
        for (int c = 0; c < i; c++)
            // Add some checks to align it into the center when you want/need it
            System.out.print(i + repeat(len-(i+"".length()), " ") + "|");
        System.out.print("\n");
        System.out.println(repeat(len+col+1, "-"));
        for (int c = 0; c < i; c++)
            // Filling up the rest of the String with spaces so the table wont freak out
            System.out.print(theArray[i+c] + repeat(len-theArray[i+c].length(), " ") + "|");
        System.out.print("\n");
    }
    System.out.println(repeat(len+col+1, "-"));


YUV422 to RGB24 using Intel Performance Primitives

If your function is called with non-aligned memory, it will allocate two buffers, copy, do the simple fast thing, copy again, and free. That’s a whole lotta work for something simple and fast. And if the step sizes don’t match, the copy will be even slower.

If this the normal execution case, I can imagine this being a significant drain on resources.

You are processing video. Each frame will have the same size. You can keep the internal buffers in this function around from call to call, so you can reuse them and avoid the mallocs.

But even better would be to directly read your video into aligned memory, in the right format for the IPP library. Your functions should just error out if the input pointers are not aligned.

Furthermore, the output data is stored in memory newed. You should pass a data pointer from the caller to write in. If you don’t want to do that, why not directly allocate this output buffer with the right alignment?

I would recommend skipping all the step computations and worries, simply setting

size.width = width * height;
size.height = 1;

If the IPP function believes all pixels are on a single row, then you don't need those padding bytes at the end of odd-sized rows.

There is a bug: In the case that malloc fails, (imgYUV422_IPP == NULL), you free a NULL pointer. Here you probably intended to free the rgbImg buffer if it was allocated earlier.

Similarly, pBGR is never freed on error.


Check whether array is sorted recursively

Version 1:

Basically OK, but the copying of elements to another list is unnecessary. Have a look at List.sublist on how to create lists from a given index range.

Additionally, you should change the return statement to result && isSorted(left) && isSorted(right) so that the recursion does not take place if result is already false. (Look up short-circuiting in logical statements.)

Version 2:

NO. It is much better not to copy the elements and use indexes into the unmodified structure, but here you recurse for every element in the list, i.e. the recursion depth equals the list size. This is a total no-go, as it will definitely blow your stack if we are talking about serious data sizes.

Nevertheless, explore the option of using indexes (maybe a start-index AND an end-index) into the given structure some more and combine it to a divide and conquer-approach as in your first solution.

Happy coding!


Memoizing decorator with retries, part 2

Your code is broken:

__forget=False needs to be before **kwargs.
retry is undefined. (But is not used)
MappingProxyType is not hashable, and so you can't memoize it.

To fix the problem with MappingProxyType you can create a hashable dict, which seems kinda hacky, but is better than nothing. The other two are easy fixes.

I don't see why you're using a class,
the only benefit that you get from it is that you can hide implementation details in it.
However self. is an annoyance in your current implementation, in my opinion.

Design wise, I still don't get the name retry_times, let's actually retry that amount rather than try that amount of times.

And I'd split the memoizer away from the retry decorator.
Being able to use say functools.lru_cache would be nice.

And so I'd make the retry aspect a function,
removing where it currently adds to the cache.
changing the while loop to a for loop,
and will removing the cache.
This should get you:

def retry(retry_times=0, suppressed_exceptions=tuple(), capture_exceptions=False):
    def inner(function):
        @functools.wraps(function)
        def wrapper(*args, **kwargs):
            for _ in range(retry_times):
                try:
                    return function(*args, **kwargs)
                except suppressed_exceptions:
                    continue
                except Exception as e:
                    if capture_exceptions:
                        return e
                    raise
            else:
                return function(*args, **kwargs)
        return wrapper
    return inner

And now you can use the retry part without the memoizing part!
After this, I'd just make a generic memoizer, without caching the **kwargs.
Say:

def memoize(fn):
    cache = {}
    @functools.wraps(fn)
    def wrapper(*args, _forget=False):
        key = (args)
        if key not in cache or _forget:
            cache[key] = fn(*args)
        return cache[key]
    return wrapper


Calculating scores for predictions of football scores

Style

The first thing to do is to follow PEP 8: it's a style guide that says how you should indent your code, name your variables, and so on. For example, prefer results[0, i] = x.group(1) to results[0,i]=x.group(1).

Files

Opening files in Python should be done using the with idiom: your file is then guaranteed to be close correctly. takeFixtures now becomes:

def takeFixtures():
    with open('bplinput.txt') as file:
        for eachMath in file:
            x=re.match("(.*) ([0-9]+) ?- ?([0-9]+) (.*)", eachMatch.strip)
            results[0,i]=x.group(1)
            results[1,i]=x.group(2)
            results[2,i]=x.group(3)
            results[3,i]=x.group(4)
            i+=1

Data structures

I you didn't use numpy, you could have written results[i] = x.groups(), and then used zip(*results) to transpose the resulting matrix. More generally, as pointed out by Josay, you should use Python data structures, and only switch to numpy if you find out that this is where the inefficiency lies.

Formatting

The last thing that the other reviewers didn't mention is that concatenating strings is poor style, and format() should be preferred since it's more readable and more efficient:

for player in players:
    print("{} has scored {} points".format(players[player], score[player]))


Optionally creating a directory path based based on existence in NodeJS

There's one main issue I currently see with your code and that is that if the admin does not have a home configuration directory (admin.hasHomeConfigDir()) then it will be created asynchronously. The issue with this it that your second call won't wait for this, leading to a race condition where you're trying to make (and write to) a path that might not exist yet.

One solution for this is to have a function inside your function that handles the "second half" of your creation (i.e. the config location creation and file writing).

function createConfiguration(callback) {

    // Make the configuration directory and write to the configuration.
    var writeConfiguration = function() {
        fs.mkdir(admin.getConfigLocation(false), "775", function(err) {
            if (err) {
                callback(err);
                return;
            }

            // Write the configuration, either forwarding an error to the
            // callback if an error occurs or nothing at all on success.
            fs.writeFile(admin.getConfigLocation(true), JSON.stringify({blogs: {}}), function(err) {
                if (err) {
                    callback(err);
                    return;
                }

                callback(null);
            });
        });
    };

    // If the admin home configuration directory exists, don't attempt to
    // create it.
    if (admin.hasHomeConfigDir()) {
        writeConfiguration();
    } else {
        // Otherwise create the directory and write the configuration.
        fs.mkdir(os.homedir() + "/.config", "775", function(err) {
            if (err) {
                callback(err);
                return;
            }

            writeConfiguration();
        });
    }
}

I tidied up your code a bit, mostly renaming things (e.g. renaming the function to have a simpler name, renaming arguments to be more readable) and rewording the comments.

Another issue I have noticed with your code is that if the directory that admin.getConfigLocation(false) returns already exists, an error will be thrown. You should probably check whether or not the configuration location exists before creating it.

Overall it's rather good and well written code, although I don't really have much experience in the field of "JS standards" so to speak.


Made a simple gui string encrypter, just to obfuscate plaintext

import Tkinter
import base64

class crypt_mod(Tkinter.Tk):

Do you know about PEP8? It's a style guide for Python that lots of Python developers follow. One of the things it says is that class names should use the CapWords convention, eg. CryptMod. Note that Tkinter doesn't necessary follow those rules, as it's a really old module.

    def __init__(self, parent):
        Tkinter.Tk.__init__(self, parent)
        self.parent = parent
        self.initialize()

self.parent seems to be unused.

    def initialize(self):
        self.grid()
            ....

Not much to say here: the usual GUI building code.

    def encrypt(self):
        self.etxt.set(base64.b64encode(str(self.ptxt.get())))
        self.history.config(state='normal')
        self.history.insert(Tkinter.END, 'encrypt:\n' + base64.b64encode(str(self.ptxt.get())) + '\n')
        self.history.config(state='disabled')
        self.history.see(Tkinter.END)
        #print "encrypt click!"

Avoid creating twice your encrypted text: your code would be clearer if you had a encrypted variable. It's not terribly important here, but could be in future projects where you will have more lines of code. Consider using format() (recommended in Python 3) instead of building your strings by concatenation: "decrypt:\n {} \n".format(encrypted). (Those comments also apply to decrypt.)


Okay, let me get this right (I have no experience working with an LDAP): The Auth class you're first using for $attempt is actually the LDAP library you're implementing?

I don't think I understand the logic in your code. You attempt to log in to the user, and if they successfully login, you check to see if the user exists? I must be misunderstanding something.

Well, assuming you know how exactly this works, I'll just point out a couple refactor points I can see:

In terms of breaking this apart into responsibilities: your method handles both authentication and registration. I can imagine registration being handled in another method.
I doubt you need to flash forward this entire parameter: 'welcome, ' . $un. Have your Blade file check for the flash and display "welcome, ". Since you're only sending one, just pass through $un. Either that or make it an array and pass two values: type of flash, and message.
Speaking of $un. There are better variable names, give yours some meaning and quality to them.
You can manage to un-nest your code a little:

if ($attempt) {
    ...
} else {
    return Redirect...
}

This piece could really just be:

if (!$attempt) {
    return Redirect...
}

// *What used to be inside the if*


Checking for balanced brackets in JavaScript

The function must not operate on brackets inside strings and comments.
If that's the case then why not just compare the number of opened vs closed symbols?
Example:
var haveSameLength = function(str, a, b){
    return (str.match(a) || [] ).length === (str.match(b) || [] ).length;
};
var isBalanced = function(str){
    var arr = [
        [ /\(/gm, /\)/gm ], [ /\{/gm, /\}/gm ], [ /\[/gm, /\]/gm ]
    ], i = arr.length, isClean = true;

    while( i-- && isClean ){
        isClean = haveSameLength( str, arr[i][0], arr[i][1] );
    }
    return isClean;
};

Simple Testcases.
console.log( isBalanced( "var a = function(){return 'b';}" ) === true );
console.log( isBalanced( "var a = function(){return 'b';" ) === false );
console.log( isBalanced( "/*Comment*/var a = function(){ \n // coment again \n return 'b';" ) === false );
console.log( isBalanced( "var a = function(){return 'b';" ) === false );

Here's a demo:
http://jsfiddle.net/9esyk/
Update
Your code is optimal if performance is the main consideration, but the complexity is too high.
Here are a few tips.
1)
Split up your function into smaller methods to reduce the complexity. One way to do this would be to have functions to filter your string so that you only analyze the meaningful characters.
2)
Avoid using the keyword char since it's a java reserved keyword.
Final Result:
var removeComments = function(str){
    var re_comment = /(\/[*][^*]*[*]\/)|(\/\/[^\n]*)/gm;
    return (""+str).replace( re_comment, "" );
};
var getOnlyBrackets = function(str){
    var re = /[^()\[\]{}]/g;
    return (""+str).replace(re, "");
};
var areBracketsInOrder = function(str){
    str = ""+str;
    var bracket = {
            "]": "[",
            "}": "{",
            ")": "("
        },
        openBrackets = [],
        isClean = true,
        i = 0,
        len = str.length;

    for(; isClean && i<len; i++ ){
        if( bracket[ str[ i ] ] ){
            isClean = ( openBrackets.pop() === bracket[ str[ i ] ] );
        }else{
            openBrackets.push( str[i] );
        }
    }
    return isClean && !openBrackets.length;
};
var isBalanced = function(str){
    str = removeComments(str);
    str = getOnlyBrackets(str);
    return areBracketsInOrder(str);
};

Testcases
test("test isBalanced for good values", function(){
    var func = isBalanced;
    ok(func( "" ));
    ok(func( "(function(){return [new Bears()]}());" ));
    ok(func( "var a = function(){return 'b';}" ));
    ok(func( "/*Comment: a = [} is bad */var a = function(){return 'b';}" ));
    ok(func( "/*[[[ */ function(){return {b:(function(x){ return x+1; })('c')}} /*_)(([}*/" ));
    ok(func( "//Complex object;\n a = [{a:1,b:2,c:[ new Car( 1, 'black' ) ]}]" ));
});
test("test isBalanced for bad values", function(){
    var func = isBalanced;
    ok(!func( "{" ));
    ok(!func( "{]" ));
    ok(!func( "{}(" ));
    ok(!func( "({)()()[][][}]" ));
    ok(!func( "[//]" ));
    ok(!func( "[/*]*/" ));
    ok(!func( "(function(){return [new Bears()}())];" ));
    ok(!func( "var a = [function(){return 'b';]}" ));
    ok(!func( "/*Comment: a = [} is bad */var a = function({)return 'b';}" ));
    ok(!func( "/*[[[ */ function(){return {b:(function(x){ return x+1; })'c')}} /*_)(([}*/" ));
    ok(!func( "//Complex object;\n a = [{a:1,b:2,c:[ new Car( 1, 'black' ) ]]" ));
});

Demo: http://jsfiddle.net/9esyk/3/


I would argue that the code in the top should not be moved to Controller.

This of course depends on how you define responsibilities for View, Controller and Model, but I would leave the code in the View because Controller and Model should not have knowledge about CSS if it can be avoided.

More about responsibilities in ASP.NET MVC


Adding a List to SQL database (Entity Database)

You're doing a lot of unnecessary iterating with your nested for loops. I would suggest using CONTAINS over a list of ints for your SQL query, this will eliminate your outer loop. Your inner loop is adding each individual item whereas you can use AddRange to just add them all.

//Generate a List of Integers from your Indices:
int[] indexes = myCheckedListBox.CheckedIndices.Cast<int>().ToArray()

//Use that list of Integers to get your list of Sports Objects
var queryResult = from sp in context.Sports
                  where indexes.Contains(sp.sportnr)

//Add your results.
myMember.Sports.AddRange(queryResult);


State machine for handling Telnet sequences for an FTP server

As suggested by @m_x, This solution uses a parser of sorts, driven by the StringScanner built-in class.  This is very compact, pretty readable, and gets rid of the state machine altogether:

Some methods to handle actions:

def accept(scanner)
  @plain << scanner[1]
end

def reply_dont(scanner)
  @reply << IAC + DONT + scanner[1]
end

def reply_wont(scanner)
  @reply << IAC + WONT + scanner[1]
end

def ignore(scanner)
end

A list of telnet sequences:

# Telnet sequences to handle, and how to handle them

SEQUENCES = [
  [/#{IAC}(#{IAC})/, :accept],
  [/#{IAC}#{WILL}(.)/m, :reply_dont],
  [/#{IAC}#{WONT}(.)/m, :ignore],
  [/#{IAC}#{DO}(.)/m, :reply_wont],
  [/#{IAC}#{DONT}(.)/m, :ignore],
  [/#{IAC}#{IP}/, :ignore],
  [/#{IAC}#{DM}/, :ignore],
  [/(.)/m, :accept],
]

And the parser that uses them:

# Parse the the command.  Sets @plain and @reply

def parse_command(command)
  @plain = ''
  @reply = ''
  scanner = StringScanner.new(command)
  while !scanner.eos?
    SEQUENCES.each do |regexp, method|
      if scanner.scan(regexp)
        send method, scanner
        break
      end
    end
  end
end


Generate a unique numeric identifier for each instance of a class

A few remarks:

The biggest obvious issue is the violation of encapsulation. All methods which allow you to modify the id set are public which means that outside code can change it and break the inherent assumption that each instance will have a unique id.

The only code which should be able to modify the id set are the constructor and destructor.

If you now say "ah, that won't matter it's just my code and I know not to do this" - programming is a skill and like any skill you get better at it through practice. Which typically means writing code. Therefore you should take any opportunity to practicing writing good code since that helps to form good habits. There is no excuse for being sloppy.
This:

return s_usedID.count(id) == 1 ? true:false

can be written more succinctly as:

return s_usedID.count(id) == 1;

The implementation is obviously not thread-safe. Just something to be aware of.
One way to improve it, is to just use a variable to store the current maximum id and return the next one higher if you need a new one. If an id gets freed up then you could just not worry about it.
If you really want to re-use returned id's then store them in a returnedIds set. The basic logic then becomes:

If returnedIds has any elements pop first element from set and return it
Else new id becomes current_max_id + 1


Extracting coordinates file that are inside a bounding box

First of all, note that you can always use Point2D.Double for representing points in a plane.

Next, I would split your program into two methods: the first one for pruning points that are not within a specified bounding box, and the second one for reading the points from the standard input, and putting them into the first one.

What comes to coding conventions, I would have a blank line before the if statement. Also, you should surround the condition of an if statement with a single space. So, instead of

String[] values = data.split(",", 3);
if(Double.parseDouble(values[0])){ ...

you should write

String[] values = data.split(",", 3);

if (Double.parseDouble(values[0])) { ...

All in all, I had this in mind:

import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

public class CoordinateUtilities {

    public static List<Point2D.Double>
        getPointsWithinBoundingBox(final List<Point2D.Double> pointList,
                                   final double lowX,
                                   final double highX,
                                   final double lowY,
                                   final double highY) {
        Objects.requireNonNull(pointList, "The list of points is null.");
        checkXBounds(lowX, highX);
        checkYBounds(lowY, highY);
        final List<Point2D.Double> ret = new ArrayList<>(pointList.size());

        for (final Point2D.Double point : pointList) {
            final double x = point.x;
            final double y = point.y;

            if (lowX <= x && x <= highX && lowY <= y && y <= highY) {
                ret.add(point);
            }
        }

        return ret;
    }

    public static void main(final String... args) {
        final Scanner scanner = new Scanner(System.in);
        final double lowX  = 50.0;
        final double highX = 100.0;
        final double lowY  = 30.0;
        final double highY = 60.0;

        final List<Point2D.Double> allPoints = new ArrayList<>();

        while (scanner.hasNextLine()) {
            final String line = scanner.nextLine();

            if (line.trim().equals("quit")) {
                break;
            }

            final Point2D.Double point = parsePoint(line);

            if (point != null) {
                allPoints.add(point);
            }
        }

        final List<Point2D.Double> boundedPoints =
                getPointsWithinBoundingBox(allPoints, lowX, highX, lowY, highY);

        boundedPoints.forEach(System.out::println);
    }

    private static Point2D.Double parsePoint(final String line) {
        final String[] tokens = line.trim().split("\\s*,\\s*");

        if (tokens.length < 2) {
            return null;
        }

        try {
            final double x = Double.parseDouble(tokens[0]);
            final double y = Double.parseDouble(tokens[1]);
            return new Point2D.Double(x, y);
        } catch (final NumberFormatException ex) {
            return null;
        }
    }

    private static void checkXBounds(final double lowX, final double highX) {
        if (Double.isNaN(lowX)) {
            throw new IllegalArgumentException(
                    "The lower bound of the x-coordinate is NaN.");
        }

        if (Double.isNaN(highX)) {
            throw new IllegalArgumentException(
                    "The upper bound of the x-coordinate is NaN.");
        }

        if (lowX > highX) {
            throw new IllegalArgumentException(
                    "The lower bound of the x-coordinate (" + lowX + "is " +
                    "larger than the upper bound of the x-coordinate (" +
                    highX + ").");
        }
    }

    private static void checkYBounds(final double lowY, final double highY) {
        if (Double.isNaN(lowY)) {
            throw new IllegalArgumentException(
                    "The lower bound of the y-coordinate is NaN.");
        }

        if (Double.isNaN(highY)) {
            throw new IllegalArgumentException(
                    "The upper bound of the y-coordinate is NaN.");
        }

        if (lowY > highY) {
            throw new IllegalArgumentException(
                    "The lower bound of the y-coordinate (" + lowY + "is " +
                    "larger than the upper bound of the y-coordinate (" +
                    highY + ").");
        }
    }
}

Hope that helps.


Filtering index using has_many through relationships

In models/job.rb, you can add scopes and use them chained on the controller:

class Job < ActiveRecord::Model
  scope :with_cities, ->(city) { includes(:cities).where(cities: { id: @city })  if city }
  scope :with_positions, ->(position) { includes(:positions).where(positions: { id: @position }) if position }

  # rest of the code ...
end

For JobsController, you can:

Add a before_filter to load all the data, and if you need to use that data on other actions, you just need to append the name of that action too.
Use memoization to load the city and the position.

In controllers/jobs_controller.rb:

class JobsController < ApplicationController
  before_filter :load_data, only: [:index]

  def index
    @jobs = Job.with_cities(city).with_positions(position).paginate(page: params[:page], per_page: 5)
  end

  # ...

  protected:

  def load_data
    @cities = City.all
    @positions = Position.all
  end

  def city
    @city ||= City.find(params[:city_id]) unless params[:city_id].empty?
  end

  def position
    @position ||= Position.find(params[:position_id]) unless params[:position_id].empty?
  end

On the view:

Use try, so instead of:

    - if current_user && current_user.admin?
      == render 'shared/dashboard_header'

you could write:

    == render 'shared/dashboard_header' if current_user.try(:admin?)

Use include_blank and prompt options in select_tag.
This not only simplifies the views, but also allows to use params[city_id].empty? on the controller.

select_tag :city_id,
  options_from_collection_for_select(@cities, :id, :name, params[:city_id].to_i),
    include_blank: true, prompt: "all cities...", class: "basic"

Finally, you could extract ul.jobs into a partial:

= render partial: 'jobs', locals: { jobs: @jobs }

Or even the .job_search div, especially if you'll be needing this somewhere else.


The first 'problem' I notice is what I call a roocky mistake (been there, done that) is the way you route a request.

If a person requests ?page=mypage.php you check or that file exists if so, you include it.
this means that your filesystem is hardcoded with your routing. Everytime you change a file-name, your routes also change. Also, some file-systems are case-sensitive (oh oh!)

A better would be to have a Router script that handles routing, it recieves a request, and it simply calls the correct method. Routes can be stored in a database table, local file or even written in PHP (as in laravel)

Another thing that really bugs me is all the $_ variables in your code. A better thing to do is to wrap them somehow (e.g. a Class or a set of functions). These functions would then have some validation in them. E.g. CSRF protection when _POST data is given, or instead of using the default php session handler, have your own that stores all session data in a database, ...

You talk about MVC and that your php files are always a Model, controller and view in one. So you didn't use MVC, you simply started coding everything together. And that is simply not how you should begin.

When designing an API, make your own (web)-inteface use the same API as your smartphone-apps. This way, you only have to work on one single API instead of having an API for apps and a completly different one for the web.


The ´var´ keyword:

From the C# Programming Guide:

  The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code.

So lines like:

int threshold = 7;
Bitmap bitmap0 = (Bitmap)imag.Clone();

would become:

var threshold = 7;
var bitmap0 = (Bitmap)imag.Clone();

Variable names:

Names like bitmap, bitmap0, Sqdistance don't have a useful meaning, not for you, nor for others reading/reviewing your code. Use meaningful names for your variables, better for readability and maintainability.

Curly braces:

Although you're not writing "wrong" code by omitting the braces on the outer loops, it seriously decreases readability. Following is only 2 lines longer and is much easier to understand:

for (row = 0; row < rows; row++)
{
    for (col = 0; col < cols; col++)
    {
        //Code...
    }
}

Other:

if (count >= threshold)
    outmap.SetPixel(col, row, Color.FromArgb(255, 255, 255));
else
    outmap.SetPixel(col, row, Color.FromArgb(0, 0, 0));

can be rewritten to:

var colorBit = count >= treshold ? 255 : 0;
outmap.SetPixel(col, row, Color.FromArgb(colorBit, colorBit, colorBit));

Following code contains too much braces in my opinion:

private int SQ(int a) { return ((a) * (a)); }

Rewrite it as follows:

private int Square(int a)
{
    return a * a;
}

or a different approach:

private int Square(int a)
{
    return (int)Math.Pow(a, 2);
}

Also for those two last methods, don't make them upper case. Method names in .NET are Pascal case (Capitalization Conventions).

Performance:

Regarding the performance. I didn't take a deep dive in the code or test it, but is there a reason why you perform the loops twice? Isn't there a possibility to execute all the code inse the double for-loop?

I did a performance analysis on your method and it is indeed the GetPixel method that is slowing things done. I did a Google search and apparently a lot of people are dealing with this. Here's an interesting question on StackOverflow that has a possible solution: C# - Faster Alternatives to SetPixel and GetPixel for Bitmaps for Windows Forms App.

Seems that an important part of this approach is the LockBits() method call. More reading about it on MSDN: Bitmap.LockBits Method (Rectangle, ImageLockMode, PixelFormat)


Here I will discuss only about your API, I think something may also be changed in your domain model but I don't see enough code to suggest anything really meaningful.

You have some code duplication you can avoid, extract this:

private async (string UserId, IEnumerable<string> Roles) GetCurrentUserAndRole()
{
    if (!User.Identity.IsAuthenticated)
        return ("", Enumerable.Empty<string>());

    var username = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
    var user = await _userManager.FindByNameAsync(username);
    var roles = await _userManager.GetRolesAsync(user);

    return (user.id, roles);
}

Let's introduce an helper method to determine if user is an administrator:

private static bool IsAdministrator(IEnumerable<string> roles)
    => roles.Contains("Admin");

Now API methods might be simplified:

[HttpGet]
public async Task<IActionResult> GetArtists()
{
  (var userId, var roles) = await GetCurrentUserAndRole();
  var artists = _artistsService.GetAllArtists(userId, IsAdministrator(roles));

  return Ok(new { artists = artists });
}

Exactly same thing may be applied to all the other methods. Note that names can be simplified, the list of artists does not need to be artistCardDtoCollection when simply artists is enough.

Now we have a problem. I don't know how you setup your tests but I usually like to test different things in different layers, controllers are easy to test if I can simply create an instance of an object, call a method and assert about its result. In this way I can verify all the controller logic (that should be pretty small) in simple unit testing and then check for HTTP related stuff in integration tests (slower and often tedious to write). Can I do it here? No, because GetCurrentUserAndRole() needs HttpContext and User and they're not available when I manually created an instance of ArtistsController. It's also hard to try this logic because I need the whole authentication thing to try both code paths. Let's move this logic into a separate IPermissionsService (or similar name). You get an instance of this service from your favorite DI framework and you can mock it as you prefer:

[HttpGet]
public async Task<IActionResult> GetArtists()
{
  var permissions = await _permissionsService.GetPermissions(HttpContext);

  var artists = _artistsService.GetAllArtists(permissions.UserId,
      permissions.IsAdministrator);

  return Ok(new { artists = artists });
}

Now you can test it:

[TestMethod]
public async void IfUserIsAdministratorThenXyz()
{
    var artistsService = ...;
    var userManager = ...;
    var permissionsManager = new MockPermissionsManager(...);

    var controller = new ArtistsController(artistsService,
        userManager, permissionsManager);
    var response = await controller.GetArtists();

    // Check result and HTTP status code...
}

This is not the only (or the best) way to solve the problem but definitely something you should think about.

We're creating an anonymous object here, I strongly suggest to add a proper model object such as ArtistListModel. In .NET Core default naming conversion
 for serialized JSON objects changed, now you can name properties with PascalCase and they get serialized in camelCase.

When you create a new artist and AddNewArtist() fails you're returning 404 Not Found, it's not exactly the expected HTTP status code if something went wrong.

You're not catching any exception. I do not think that this code won't ever fail in any circumstance (and a generic 500 Server Error is somehow unprofessional if it can be avoided with a more meaningful error message).

To create an object you might consider to use PUT instead of POST. I say consider because it's an opinionated guideline which I won't discuss here. Also a redirect as result of an API call isn't completely clear to me, leave this design decision to Presentation. An API call should return 201 Created and caller has the responsibility to read the object content (if interested); this is presentation logic, not domain logic. If you want to inform the client about the location of the newly created object then you can manually add Location HTTP header in your response (even if it has been originally intended to be served only with 3xx responses, it is somehow common in API interface):

201 Created
Location: http://example.com/api/v1/artists/1234

As I said I won't discuss these issues here but someone suggests to return resource content in the body of the request when returning 201 Created (in this case you do not even need to add Location header) or an empty body when returning 202 Accepted. Think about it and stick to one convention everywhere.

For documentation purposes I'd also add [ProducesResponseType] attributes to your API methods. It will help you to understand the code later and it'll make automatically generated documentation (for example with Swagger) much more complete and useful.


I think instead of looping indefinitely over the queue you should only start it when the first popup is queued via the DisplayPopupmessage and loop only as long as there are any popups. After you've shown everything you should exit the loop and  start agian when something arrives.

For this job you should have a dedicated service that knows how to handle it. Currently it looks like the logic is within the popup-message.

I used these models for testing:

interface IPopupMessage
{
    string Message { get; }
    TimeSpan Timeout { get; }
}

class PopupMessage : IPopupMessage
{
    public string Message { get; set; }
    public TimeSpan Timeout { get; set; }
}

A simple service could be implemented like this one to handle the queue:

class PopupMessageService
{
    private bool _started;
    private readonly Queue<IPopupMessage> _popupMessageQueue = new Queue<IPopupMessage>();

    public void DisplayPopupMessage(IPopupMessage popup)
    {
        Console.WriteLine($"Equeued \"{popup.Message}\".");
        _popupMessageQueue.Enqueue(popup);
        Start();
    }

    private async void Start()
    {
        if (_started) { return; }
        _started = true;
        Console.WriteLine("Service started.");
        while (_popupMessageQueue.Any())
        {
            await Task.Run(async () =>
            {
                var msg = _popupMessageQueue.Dequeue();
                Console.WriteLine($"Showing \"{msg.Message}\".");
                await Task.Delay(msg.Timeout);
            });
        }
        _started = false;
        Console.WriteLine("Service stopped.");
    }
}

The real message should have a method like Show(CacellationToken token) that you use to display the message and to hide it via the token.IsCancellationRequested and token.ThrowIfCancellationRequested(). You should handle the OperationCanceledException in order to proceed to the next popup.

It's just for demonstration purposes so I left the Console.WriteLine there.

And here's one more example how to use the above service:

void Main()
{
    Messages();
}

static async void Messages()
{
    var popupMessageService = new PopupMessageService();

    var messages = new IPopupMessage[]
    {
        new PopupMessage { Message = "Foo", Timeout = TimeSpan.FromSeconds(3) },
        new PopupMessage { Message = "Baz", Timeout = TimeSpan.FromSeconds(5) },
        new PopupMessage { Message = "Qux", Timeout = TimeSpan.FromSeconds(1) },
        new PopupMessage { Message = "Bar", Timeout = TimeSpan.FromSeconds(2) },
    };

    foreach (var msg in messages)
    {
        popupMessageService.DisplayPopupMessage(msg);

        // For test purposes assuming a message arrives every 3 seconds.
        await Task.Delay(TimeSpan.FromSeconds(3));
    }
}

The output is:

Equeued "Foo".
Service started.
Showing "Foo".
Service stopped.
Equeued "Baz".
Service started.
Showing "Baz".
Equeued "Qux".
Showing "Qux".
Service stopped.
Equeued "Bar".
Service started.
Showing "Bar".
Service stopped.


Efficiently creating a list of formatted hex values

The shortest and most readable way to do it would probably be

hexlist = [hex(x) for x in range(256)]

Time

Your first : 0.1  ms per loop for \$10^5\$ loops

Your second: 1    ms per loop for \$10^5\$ loops

The above  : 0.02 ms per loop for \$10^5\$ loops

I'm unable to com up with a worse example, but there is always a worse way to do it, exactly as there is always preferable way to do it.

Edit
To do this with filled zeros I would suggest to treat the first 10 numbers as a special case.

hexlist = [hex(x) if x > 15 else "{:#04x}".format(x) for x in range(256)]

new time: 0.04 ms. Even if it isn't as pretty.

Edit:

And when considering that format can format binary numbers, why not hex?

hexlist = ["{:#04x}".format(x) for x in range(256)]

I guess that this is hard coded for this range, but anyway.

Time: 0.1ms for per loop for \$10^5\$ loops.

And more edits

Using old style:.

hexlist = ["0x%02x" % n for n in range(256)]

Time: 0.08ms per loop for \$10^5\$ loops.

And specifically generating what we want.

hexlist = ["{:#04x}".format(x) for x in range(16)] + \
              [hex(x) for x in range(16, 256)]

Time: 0.03ms per loop for \$10^5\$ loops.


Looks very good. And, as far as I know, your colour generator is fair.

For efficiency

you don't need to generate a random number for every hex character. You are choosing among 256^3 (16 777 216) colours, labeled with every number from 0x0 (0 in decimal) to 0xFFFFFF (256^3-1 in decimal, or 16 777 215).

So you can:

generate a random number let randomNum = Math.floor(Math.random() * 16777216) // 256^3
use an inherent function for JavaScript Numbers, toString, to convert it to a string with an arbitrary radix:
let hextest = randomNum.toString(16)

By design, randomNum is a natural number (non-negative or 0) so you don't need code for validation).
pad it with zeros. This question was asked a million times in Stack Overflow (this is only an example).

For your example, where you don't need validation, hextest = ('00000' + hextest).substr(-6) will do. (After padding with all the zeros you'd ever need, picks only the last 6 characters.)
convert to uppercase and decorate: hextest = '#' + hextest.toUppercase(). Reference for toUpperCase()

This way you can get rid of the hexChars constant.

For functionality

I don't have any good idea on how to add functions. But I can suggest an improvement:

in the code you have to capture spacebar presses, add the line e.preventDefault(). This will prevent the default behaviour for the space key (which is scrolling a screen down).

That way, you can add all the content you want to your page without fear of accidentally scrolling down (and it won't scroll down Code Review when I try your embedded snippet, either).


Access Modifiers & Variables

Firstly, I would recommend you only declare one variable per line. This improves readability and also encourages & facilitates commenting the declarations.  It can however have the disadvantage of having an ugly wall of declarations at the start of your classes, though ordering your variables properly can help alleviate this problem.

I personnally like to order class & instance variables like so :

- first, `static final` variables, with a name written in capitals snake_case, e.g. THIS_IS_A_CONSTANT

- then, other `static` variables

- `final` instance variables

- within those, I like placing objects & composite types first, followed by variables of primitive types (`int`, `boolean`, `char` and so on)

- finally, I like having all `public` variables first, then `protected` and finally `private` variables, although I like to put constants at the top whether they are `public` or `private`

Of course, this is only one way of doing it, and some people may think mine is strange or doesn't suit their personal style. I'd recommend you find or come up with one that you like and stick to it in the future.

In practice, it would look something like this :

public class MyClass {
    private static final int SOME_CONSTANT = 25;
    public static final int SOME_OTHER_CONSTANT = 25;
    public static int aaa;
    public final int A;
    public List<Integer> integers;
    public Object object;
    public int x;

    ...

    public void someMethod() { ...  }

    private void aPrivateMethod() { ... }

    public static void someOtherMethod() { ... }

    ...

    public int getX() {
        return x;
    }
}

Obviously, the names given to the variables in my example are terrible and I only chose them because I couldn't be bothered to come up with a unique name for each one.

You should also keep all you variable declarations together, and not mix them with method declarations. public variables should be avoided as they can be modified by anyone or anything; instead, you can declare them as private and add getters and/or setters to access them. This can also allow you to add logic inside the getter or setter methods, to check or validate the value provided for example.

For methods, I again like placing all public methods first, followed by protected and then private ones; I generally put static methods at the bottom if there are any. And finally, I like to keep all getters & setters together, somewhere I can easily forget about them after they've been implemented.

Naming and Comments

Your code has a lot of comments, although most of them are superfluous and sometimes even wrong (e.g. run till queue is not empty followed by while (!q.isEmpty())). I personnally don't like comments very much and try to avoid them as much as I can, as they can require a lot of effort to maintain and are often not necessary in well-written code (which I can't claim to write yet, as much as I may want to); I also find that they make the code harder to read when too abundant, and my first instinct when looking at heavily-commented code is often to get rid of all the redundant comments -but that's just me.

But that doesn't mean you shouldn't write comments! However, rather than explaining what the code is doing (which the code itself already does), comments should be used to explain things that cannot be inferred or understood simply by reading the code; for example, telling why one method or technique was used in this particular case rather than another.

As an example, in the snippet below, the comment is only really useful because of how the variable n is named. If it were named nbSteps, or maybe currentValue (I'm not very good with names either, but I'm trying to improve), the comment would then be completely unnecessary. But if you see a reference to n somewhere else is the code, you might think "mmmh, what was n again? was it the size of the matrix? the number of steps I can take? or maybe the number of elements in the queue? who knows!".

// value of current cell
int n = matrix[i][j];

Similarly, the comment // The function returns false if is not a valid position doesn't tell us anything that we don't already know from simply reading the method's name.

This takes us to variable names, and naming in general. Giving your variables, classes and methods meaningful names (that actually tell you what they are or what they do) is probably the most essential thing to making code easy to read. Again, most of your comments simply tell the reader what one things or another is or does, which accomplish very little.

Shortened or abbreviated names like curr or q don't really have any benefit over longer, clearer ones, other than making the very first time you type the name a tiny bit shorter. Renaming them to current and queue for example will make the code easier to read later, and you shouldn't be worried about typing a few more characters each time; let you IDE help you and do its job!

There is probably a lot more to say about comments and maybe JavaDoc, but I think the above outlines enough of the basics to improve your code commenting habits.

I've rewritten your Node class using the above guidelines while keeping its functionality, structure and meaning as close to the original as possible :

Node.java

// queue node used in BFS
public class Node {
    private final int x; // x-coordinate of a cell in matrix
    private final int y; // y-coordinate of a cell in matrix
    private final Node parent; // maintain a parent node for printing final path

    public Node(final int x, final int y, final Node parent) {
        this.x = x;
        this.y = y;
        this.parent = parent;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public Node getParent() {
        return parent;
    }

    @Override
    public String toString() {
        return '(' + x + ", " + y + ')';
    }
}

I've made all the fields in Node.java private final and added getters, as you don't ever change them after setting them in the constructor. You also used both single and double quotes for characters in your toString() method, which I've corrected.

While trying to refactor and make improvements to your Solution class, I found I was having a hard time understanding how it's meant to be used; at first, I thought it was a static class, from which you call findPath(), which would return... a Node? But you have a mix of static and non-static methods and variables, and use them within one another, but have no constructur...

Also, getShortestPath() returns a list that will only ever contain the node added to it by findPath(), which is simply the lower-right node (or destination, as you call it), so you only ever get the destination and never the actual full path.

I would maybe suggest you refactor this portion of your code and submit it for another review, as -unless I'm mistaken- I do not believe it is actually functional right now.

Some additional things...

I strongly recommend you use the final keyword everywhere you can; method arguments, local variables... it indicates that the value you're assigning to the variable should not and will not change after it's been assigned. In other words, a final variable can only be assigned once, e.g. you can't do final int x = 45; x = 25;.

Again, there's more to say about the use of final, but if you'd like to know more I recommend you take a look at this answer : https://softwareengineering.stackexchange.com/questions/98691/excessive-use-final-keyword-in-java.

I also notice that you didn't include imports in your questions; you should add those next time you ask a question on CodeReview.

You declared an overload for toString() in your Node class, why not use it for the value provided to key? That way, if you ever want to change that key, you can simply change the toString() method instead of having to change it in two places. Or you could create another method just for this purpose, to keep the toString() for displaying a nicely formatted string, while the other one would be a simplified version of your toString(), used solely for generating the 'keys'.

Another thing; you declare shortestPathList as a LinkedList<String>, and getShortestPath() returns a List<String>. I'd suggest you either change shortestPathList's type to a List<String>, or change the method's return type, as it will only ever return shortestPathList. You can find more information about this topic here : https://stackoverflow.com/questions/12321177/arraylist-or-list-declaration-in-java.

If I've made any mistakes or if you disagree with anything I've said, please refrain from throwing your keyboard at me but do point them out to me so that I can improve my own skills and knowledge!


Four things come to mind:

You're mixing object oriented programing with the more 'traditional' way PHP was written.  You don't need to use both.  If you will use the older memcache_connect, memcache_get and memcache_get functions, you don't need to instantiate an object with new Memcache.  Checkout the bottom of the connect page for the two side by side. Instantiating gives you more flexibility though (see point 3 below).  You tend to call memcache_connect even though the rest of your code is object-oriented; be consistent and use $memcache_obj->connect(...)
memcache_get returns FALSE when the object is not in the cache. So there is no need in your getCache function to do if(empty($res)){$res=false} because $res will already be false.
Consider closing the connection to the cache when you're done with it. Otherwise you may have a large number of active connections as you create a new instance and connect every time getCache and setCache are called. I would call Memcache::close before returning from either function.  Alternatively, if these functions are called often within one request-response cycle, you could have a Cache class that you instantiate; the Memcache instance would be a property of the class. Then in the class constructor, you can call new Memcache and Memcache::connect, and use the same connection for all operations. Then in the class destructor (the __destruct function, you can close the connection.
Your _getData indiscriminately uses caching. No matter what data is sought, it gets cached. You may have to be a bit more surgical because if you have fast changing DB data, _getData will soon start returning obsolete information (for instance, one would not seriously consider serving current stock prices or currency conversion rates from a cache). You may want to apply caching only to a subset of your DB, depending on the nature of your data


Cracking the Coding Interview - 4.1 Graph Traversal

Your worst case performance (every node is connected to each other node but node2) is \$\mathcal{O}(n^2)\$, up from the "normal" \$\mathcal{O}(n)\$, because nodes can be added to the queue multiple times. This should also increase the average runtime. This gets even worse if multiple edges between any 2 nodes are allowed.

Note that adding another check q.contains(node) would still result in a runtime of \$\mathcal{O}(n^2)\$ as those checks add a factor of \$\mathcal{O}(n)\$. The Visiting state prevents this.
visited is never reset to false (in the presented code). This will lead to errors in subsequent calls.
The definition of Queue is missing.


Is there a better way to achieve this rather than an If statement?

Yes. You could have an enumeration of the container types and their capacities, in increasing order by capacity,
loop over in order,
and as soon as you find one that's big enough, return it.

It's perhaps easier to see after you simplify the if-else chain,
by removing redundant conditions, for example:

 if (qty <= 300)
 {
     return CartonType.SMALL_PASCAL;
 }
 if (qty <= 600)
 {
     return CartonType.SMALL_PASCAL;
 }
 if (qty <= 1200)
 {
     return CartonType.BABY_BOX;
 }
 // ...


Some notes:

url_replace( '/news' ): Each language has its formatting rules. In Ruby almost nobody inserts spaces after and before parens.
hash = args.last.kind_of?(Hash) && args.last: I'd strongly discourage this kind of positional arguments, the method signature is severely impaired. Use an options hash instead (note that Ruby 2.0 finally provides keyword arguments).
query.delete(k.to_s). If you check my other answers you'll see I tend to favour functional programming, so I'd rewrite this using expressions instead of statements. Code is much more clean when they say what things are instead of how you change their value.
Uses of args.first in the middle of the code: Strive for declarative code, give names to things before you use them when it's not clear what they are.
I'd accept only strings as keys for the query string, or, if Activesupport is at hand, I'd call stringify_keys or Hash[h.map { |k, v| [k.to_s, v] }] at some point. This way I'd avoid mixing symbols and strings.

I'd write:

require 'uri'
require 'cgi'

def url_replace(url, options = {})
  uri = URI.parse(URI.encode(url))
  hquery = CGI::parse(uri.query)
  components = Hash[uri.component.map { |key| [key, uri.send(key)] }]
  new_hquery = hquery.merge(options[:merge_query] || {}).select { |k, v| v }
  new_query = URI.encode_www_form(new_hquery)
  new_components = {path: options[:path] || uri.path, query: new_query}
  new_uri = URI::Generic.build(components.merge(new_components))
  URI.decode(new_uri.to_s)
end

puts url_replace('/news?a=b&c=d', path: '/bar', merge_query: {"c" => nil})
#=> /bar?a=b


It would have been a good idea to link to the problem statement in your question.
Please run gofmt on your code, typically have your editor automatically format your files every time you save your source file.
Your naming conventions aren't very Go-like.

Solutions is too vague, BinaryGap would be better.
convertNumberToBinary is really long; this isn't Java — toBinary would largely be enough
stringArray is very wrong: this variable is a byte slice, plus, it doesn't give you extra information from its type
TestBinryGap should probably be TestBinaryGap
testObjects is weird and slightly misleading; Go test files usually name this variable test or tc, and expected is pretty much always called want

When you want to append repetitively to a string like in convertNumberToBinary, use string.Buffer. But here, why not just use a []bool that you can name isOne or something?
I think the function is simple enough that you can just put it in one function, and compute the binary representation at the same time you compute the binary gap. This would make your memory complexity $(1) instead of O(log(n)) (no need to allocate a slice or a string anymore) and simplify your code.
You don't need to convert your string (or your []bool) into a []byte later on; you can just iterate on it directly.
You should probably test that the input is a nonnegative number and return an error if that's the case (although maybe this isn't necessary in a competitive programming setting).
On the positive side, your test is a good idiomatic example of struct-based tests =)


Parallel computing and asynchonous computing are two separate things. While they might be similar in some cases, the two terms have two very distinct meanings in C#-land:

Asynchronous computing is used for the async/await and Task<T> idioms.
Parallel computing is what you are doing here, using plinq: processing streams of data in different threads in parallel.

With that said, you're not using the features of Plinq to the fullest. Instead of passing the (incorrectly named) asynchronous to each of the methods, count.MakeIntArray().AsParallel() would have sufficed to make the entire thing parallel.

I think you went a bit overboard with the amount of extension methods you created, while gaining little for it in return. What if a new request would come to say something new on every number modulo 10? Now you have to make changes in 4 methods (or more accurately, create 4 more methods) to account for these changes!

Instead you could have made the Fizz and Buzz methods two versions of a more generic Substitute method:

public string Substitute(int number, Func<int, bool> when, string with);


TranslateIt class using the Yandex translation service

Some ideas:

If the arguments are a fixed list, don't use **kwargs. I find **kwargs is only really useful if you have some middleware code which needs to forward an arbitrary set of arguments to another piece of code. That way people don't need to rely on your documentation (or when the documentation inevitably gets out of date, the code) to understand which parameters the method takes. Using named parameters you can also get rid of loops over **kwargs.
IMO attributes and constants shouldn't be documented at all. Any IDE will be able to auto-complete them, and their names should be sufficiently self-explanatory that you don't need extra documentation.
Starting a method name with check implies an assertion is happening. Use get when that is what you're doing.
This is a personal style item, but I prefer that the interesting/important code is at the top of the file. _checkEncoding is not that interesting.
If key is a secret it should not be hard-coded.
Don't second guess TranslateIt's API. For example, don't verify the max size on the client side. Instead you should rely on the API to tell you when the size is too large and forward the information to the user. This way your implementation is simpler and more importantly doesn't get out of sync with the API.
You should use the with open() pattern in _checkEncoding.
Use pep8 to fix style issues like method names.
Your script is not usable from a command line.
Why make yandex_string a field? It is only used once, and is never changed, so you might as well treat it as a constant.
The code is not testable as it stands. This is too big a subject to expand much on here, but suffice it to say that translateIt does much more than one thing.


So I had a look at your code and I got confused to what you were trying to do with find. So I had to test it out for myself. If I understand it correctly you are using it to figure out if a string contains the value you are looking for. If it does you continue processing if not you skip it.

However, this can be done by fetching the cell value and performing InStr <> 0 to do the same thing.

I wrote a quick VBA to see the performance of find in relation to InStr. The results of this was (as you can test yourself now) that the .Find method took aproximately 5 seconds to compute, whereas the InStr one finishes instantly. When running on 100000 lines it takes almost a minute to complete, whereas the InStr one finishes instantly. So since you perform the Cells(x,y).Find for 4 separate columns in thousand of files I would say that this is your main culprit for timeloss.

Sheet1.Cells(1, 2).Value = TimeValue(Now)

For i = 0 To 10000
Dim x
Set x = Sheet1.Cells(1, 1).Find(What:="12", LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
    If Not x Is Nothing Then
        Sheet1.Cells(1, 4) = "Yup"
    End If
Next i
Sheet1.Cells(1, 3).Value = TimeValue(Now)
Sheet1.Cells(2, 2).Value = TimeValue(Now)
For i = 0 To 10000
Set x = Sheet1.Cells(2, 1)
    If InStr(x, "12") <> 0 Then
        Sheet1.Cells(2, 4) = "Yup"
    End If
Next i
Sheet1.Cells(2, 3).Value = TimeValue(Now)

On top of that you are running Cells(x,y).Replace which is about twice as slow as just setting the value of the Replace as seen below.

wks.Cells(BlankRow, 1) = Replace(wks.Cells(BlankRow, 1),"string to remove","")

The methods you are running for Find and Replace are supposed to be executed on Ranges for the maximum efficiency. Say if you instead running replace on each cell one by one you execute it on the entire column straight away like this:

wks.Columns(1).Replace What:="testtest         : ", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

Then you will notice that the Replace is performed in less than a second for all rows. Making it a lot faster if you have massive files.


Return the amount of Quarters, Dimes, Nickels, and Pennies that you would get from the total amount of change

Your loop only adds one coin to the change every repetition, which can be done faster: you don;t need the else if.

You don't want to set your Text properties inside your loop, but only when you're finished.

Also, you want to check if change > 99 before starting, otherwise your loop never ends.

Instead of

something = something + x;

you can use

something += x;

Once you're down to pennies, the number of pennies is your remaining change.

Instead of adding one coin every time, simply add all the quarters possible, then all the dimes, etcetera:

if (change > 99) throw new ArgumentOutOfRangeException("Too much change!");

while (change > 24)
{
    change -= 25;
    quarters++;
}
while (change > 9)
{
    change -= 10;
    dimes++;
}
while (change > 4)
{
    change -= 5;
    nickels++;
}

pennies = change;

Now, you can actually do away with all the loops very simply, by dividing the remaining change by the size of your next coin. The resulting integer is the amount of coins.

Then you get:

int quarters = change/25;
change -= quarters*25;
int dimes = change/10;
change -= dimes*10;
int nickels = change/5;
int pennies = change - nickels * 5;

Even shorter, using the % (modulo) operator:

int quarters = change/25;
change %= 25;
int dimes = change/10;
change %= 10;
int nickels = change/5;
int pennies = change%5;


A program that prints the longest substring of s in which the letters occur in alphabetical order

if second>=len(s):
    break

This is not necessary. You have just checked that in the loop condition.

first=0
second=1
strang1=''
strang2=''

Consider renaming these variables to say what they do more clearly. Even "begin" and "end" would be clearer than "first" and second, but do not be afraid of longer variable names.

As a rule of thumb, be wary of variable names which you have numbered. They often mean either that they do sufficiently the same thing and you could simplify the code by putting them in a list and looping, or they do not do the same thing and you should name them appropriately. (As is the case here)

strang1+=s[second]
if len(strang1)>len(strang2):

Constructing strings, especially one character at a time, is an expensive operation. You could do this more efficiently by just storing the location in the input string. You can compare sizes just by subtracting the start of that location from the end. At the end of the loop, you can assign the result in one go using s[start:end] notation.

  Assume s is a string of lower case characters.

When you have assumptions like this, it is generally prudent to check them. Coding challenges won't tend to require it. When you have a larger code base and are trying to work out where something went wrong, you'll thank your past self if the first thing that was given input it wasn't designed for is screaming about it so you know where to look.


Building off of Danny's answer, if you have access to the HTML, you can add a class to each of your span tags and bind an event to that class:

1
2
3

The event call can become more generic by using the event's local context 'this'. From the .bind() documentation:

  Within the handler, the keyword this refers to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal $() function.

'this' inside of the click event will be the DOM element that was clicked on that caused the event to fire. Then you would need only the following to setup the click event for all of the elements with the class 'spanval':

$(".spanval").click(function(){
    $('#hourvalue').val($(this).text());
});

And with the rest of the script:

$(document).ready(function() {

   $(".spanval").click(function(){
       $('#hourvalue').val($(this).text());
   });

   $('.hour_dropdown').hide();

   $("#more").click(function() {
       $('.hour_dropdown').fadeToggle(200);
   });

});


You should indent your code properly to make it more readable.

Posting PHP on JSFiddle is apocalyptic insanity a bad idea. JSFiddle is for JavaScript.
Use IDEOne for PHP Instead.

Your use of whitespace could be improved.

 for ($z=0;$z<$firstrow2;$z++)

into: for ($z = 0; $z < $firstrow2; $z++)

Your variable naming is shortened, sometimes confusing, and flat out bad practice in places.
Transform them from lowercase to camelCase.

You don't even use $firstrow1, remove it.

$getRagearr sounds like a pirate themed narcotic. Perhaps $getRangeArray would be much clearer.

$j=intval($getRagearr[1]): what's wrong with good ole' fashioned int()?'

This is the result of all my suggestions:

$handle = fopen("php://stdin", "r");
$getFirstRow = fgets($handle);
$firstRowArray = explode(" ", $getFirstRow);
$numOfTestCases = int($firstRow[1]);

$getString = fgets($handle);
for ($i = 0; $i < $numOfTestCases; $i++) {
    $getRange = fgets($handle);
    $getRangeArray = explode(" ", $getRange);
    $arrayWidth = int($getRangeArray[0]);
    $arrayLength = int($getRangeArray[1]);
    $arrayResult = array();
    $lane = explode(" ", $getString);
    for ($currentPos = $arrayWidth; $currentPos <= $arrayLength; $currentPos++) {
        array_push($arrayResult, $lane[$currentPos]);
    }
    $result = min($arrayResult);
    echo $result.PHP_EOL;
}

Other than that, your code looks well-structured.


Displaying comments and replies retrieved from a database

It seems you wish to batch the posted messages together into threads.  In other words, create a "parent - children" relationship.  This can be achieved simply by using one loop to generate the new data structure and one smaller loop (I use array_map()) to display the text.

Code: (Demo)

foreach ($comments as $data) {
    if ($data['reply_id']!='') {
        $threads[$data['reply_id']][]="{$data['user']} reply: {$data['message']}";   // append element
    } else {
        if (!isset($threads[$data['id']])) {  // prevent Notice
            $threads[$data['id']] = [];
        }
        array_unshift($threads[$data['id']], "{$data['user']} comment: {$data['message']}");  // prepend element
    }
}

// display data (with no unwanted line breaks):
echo implode("

", array_map(function($v){return implode("
",$v);}, $threads));

Output (same as your posted code provides):

Jan comment: hello
Jul reply: hello7
Jun reply: hello6

Mar comment: hello3
May reply: hello5

Feb comment: hello2
Apr reply: hello4

Some additional notes:

Using ORDER BY date DESC will place newer replies above older replies, be sure that this makes sense in terms of discussion "flow".
There appears to be data redundancy with id and comment_id.  If there is a difference between these two columns of data that doesn't present itself in your posted task, then they both can stay, otherwise you should omit one of these columns from your database.
A final consideration... when dealing with thread-based messages/posts/data, it simplifies tasks like these to assign a thread_id, then you can GROUP BY and/or ORDER BY the column in your SQL and spare much of the php handling.


I think the trick is trying to vectorise this as much as possible:

By the look of it, the code is trying to threshold at 0 and count pixels under 255.

We can change the first part of the loop to:

counter = np.sum(image_in < 255) # Sums work on binary values
counter2 = np.sum(np.bitwise_and(image_in < 255, image_in2 != 0))

And the second to:

# This is 0 or 1 depending on whether it is == 0
image_new[:,:] = (image_in2 != 0) # image_new[i,j] = (image_in2[i,j] != 0)

# So scale the values up with a simple multiplcation
image_new = image_new*255 # image_new[i,j] = image_new[i,j]*255


Is this correct way to use cookies from a syntax point of view?

At the expense of having a little more code, I would use a localStorage polyfill [2].

With that code in place you no longer need to keep the create and read cookie methods. You also don't need the code wrapping get_data and set_data. Your resulting code would look something like this:

set_last_page = function(cluster) {
    if (!localStorage.getItem("Page")) {
        if (!localStorage.setItem("Page", JSON.stringify(cluster))) {
            log("Current Page: Stored");
        } else {
            log("Current Page: Store Failed");
        }
    } else {
        localStorage.removeItem("Page");
        if (!localStorage.setItem("Page", JSON.stringify(cluster))) {
            log("Current Page: Stored");
        } else {
            log("Current Page: Store Failed");
        }
    }
}

get_current_page = function() {
    if (localStorage.getItem("Page")) {
        var last_page = JSON.parse(localStorage.getItem("Page"))
        log("Last Page: " + last_page);
        return last_page;
    } else {
        log("Last Page: Inexistent");
        return 1;
    }
}

From here I would make a few changes:

You don't need to check for existence or remove an item from storage to change it.
The logging code is unnecessary.
Using JSON.stringify and JSON.parse is considerable overkill for converting between a string and a number.

Taking care of these would leave me with this code:

set_last_page = function(cluster) {
    localStorage.setItem("Page", cluster+'');
}

get_current_page = function() {
    return +(localStorage.getItem("Page") || 1);
    //localStorage.getItem("Page") will return either
    // a number >= 1 (as a string), undefined or null
    //so '|| 1' will take care of the latter cases
}

Finally, I dislike the fact you are initializing these variables as function expressions (statements) and don't end them with semicolons (either add the semis or make them function declarations). I would also rename things to be more consistent and in line with my preferred naming conventions for javascript:

function setPage(page) {
    localStorage.setItem('page', page+'');
}

function getPage() {
    return +(localStorage.getItem('page') || 1);
}


Normalize video filenames and move files to destination directory

Get-ChildItem -include *.ext1, *.ext2 instead of Where
Use pipelining via | (in direct fashion, that is without storing the results in intermediate variables) instead of foreach statement so that the processing starts immediately without waiting for the entire directory to be enumerated first (or use the advanced method of non-blocking IO.DirectoryInfo enumeration in a foreach statement).
Join-Path 'dir' * to construct the path for Get-ChildItem instead of relying on the trailing backslash
-LiteralPath instead of -Path, otherwise PowerShell will fail on paths that contain square brackets as it treats [] as a wildcard specifier.
string concatenation instead of switch

And my personal preferences:

Use regex to split the file name - it'll make the structure more obvious (if you know regex)
Use mkdir instead of New-Item -ItemType Directory (I think it's overly verbose to the point of being obfuscatingly so)
Simply create the directory without checking its existence: the operating system does it anyway, and the code is less "noisy" this way.

$fileDirectory = "C:\Test"
$ParentDir = "c:\TV Shows"

Join-Path $fileDirectory * | Get-ChildItem -include *.mkv, *.avi, *.mp4 | ForEach {
    if ($_.BaseName -notmatch '^\s*(.*?)\s*\.S(\d\d)E(\d\d)') {
        return
        # return is used because we're in a function-like ScriptBlock context
    }
    $ShowDir = Join-Path $ParentDir ($matches[1])
    $SeasonDir = Join-Path $ShowDir ('Season ' + $matches[2])
    # $matches is an internal object set automatically by -match or -notmatch operator

    mkdir $ShowDir -Force >$null
    mkdir $SeasonDir -Force >$null
    # mkdir outputs the directory object so we ignore it

    Move -LiteralPath $_.FullName -Destination $SeasonDir
}


This mostly looks OK, but I really don't like

*self = self.root
            .take()
            .map(|mut x| {
                if x.left.empty() {
                    x.right
                } else if x.right.empty() {
                    x.left
                } else {
                    x.data = x.right.pop_min();
                    Tree {
                        root: Some(x),
                        size: self.size,
                    }
                }
            })
            .expect("Can't delete None");

You can shift up the expect to get

let mut node = self.root.take().expect("Can't delete None");
*self =
    if node.left.empty() {
        node.right
    } else if node.right.empty() {
        node.left
    } else {
        node.data = node.right.pop_min();
        Tree {
            root: Some(node),
            size: self.size,
        }
    };

which is already much nicer. Then deal with the error and naming:

fn delete_root_node(&mut self) {
    let mut root = self.root.take().expect("Empty tree has no root");
    *self =
        if root.left.empty() {
            root.right
        } else if root.right.empty() {
            root.left
        } else {
            root.data = root.right.pop_min();
            Tree {
                root: Some(root),
                size: self.size,
            }
        };
}

Then I'd flatten it back out

fn delete_root_node(&mut self) {
    let mut root = self.root.take().expect("Empty tree has no root");

    if root.left.empty() {
        *self = root.right
    } else if root.right.empty() {
        *self = root.left
    } else {
        root.data = root.right.pop_min();
        self.root = Some(root);
    };
}

Rust's tools are great, but they shouldn't be abused. In this case, a simple imperative style reads much nicer than the semi-functional transformations, so should be preferred.

More rightward drift can be dealt with in find_rank:

fn find_rank(&mut self, rank: u32) -> &mut Tree {
    let right_offset = self.as_mut().left.size + 1;

    self.size -= 1;
    match rank.cmp(&right_offset) {
        Ordering::Equal => self,
        Ordering::Less => self.as_mut().left.find_rank(rank),
        Ordering::Greater => self.as_mut().right.find_rank(rank - right_offset),
    }
}

Now, find_rank is doing something really horrible:

self.size -= 1;

This breaks the Tree's invariants. Much better would be to call this pop_rank and move pop_rank inside of it. You can make this a bit nicer by having pop_root return a u32 and just depending on that, though.

Then we have a nice chain of functions

fn pop_rank(&mut self, rank: u32) -> u32 {
    let left_size = self.as_mut().left.size;
    self.size -= 1;

    match rank.cmp(&(1 + left_size)) {
        Ordering::Equal   => {
            self.size += 1;
            self.pop_root()
        },
        Ordering::Less    => self.as_mut().left.pop_rank(rank),
        Ordering::Greater => self.as_mut().right.pop_rank(rank - 1 - left_size),
    }
}

fn pop_root(&mut self) -> u32 {
    let mut root = self.root.take().expect("Empty tree has no root");
    let data = root.data;

    if root.left.empty() {
        *self = root.right
    } else if root.right.empty() {
        *self = root.left
    } else {
        root.data = root.right.pop_min();
        self.root = Some(root);
        self.size -= 1;
    };

    data
}

fn pop_min(&mut self) -> u32 {
    if self.as_ref().left.empty() {
        let data = self.as_ref().data;
        *self = self.root.take().unwrap().right;
        data
    } else {
        self.size -= 1;
        self.as_mut().left.pop_min()
    }
}

The restoring of self.size in pop_rank before calling pop_root might slightly increase computational burden but it means that each function only relies on the data structure's basic invariants to work properly.

Note that pop_min doesn't actually need to panic! as that's captured by self.as_ref's auto-panic.

as_ref and as_mut are misleading names since they actually give handles to root; better would be get_root and get_root_mut. I'd also swap pop_min for pop_first for clarity.

I'd also change m to step in permutation.

I've been transfixed by this problem for a while now, so I'm going to introduce my thoughts about it. Very little of what follows has anything to do with your implementation, but hopefully someone at least finds it a little interesting.

It's worth noting that Box-heavy structures tend to be slow. A much more efficient tree structure to work with could be a Vec<Vec<usize>> like so:

tree[0]               13
tree[1]        8               5
tree[2]    4       4       4       1
tree[3]  2   2   2   2   2   2   1
tree[4] 1 1 1 1 1 1 1 1 1 1 1 1 1

tree[0..3] are used to guide you to an index in the bottom. "Using" the fifth value would result in the tree modified like so

tree[0]               12
tree[1]        7               5
tree[2]    4       3       4       1
tree[3]  2   2   1   2   2   2   1
tree[4] 1 1 1 1 0 1 1 1 1 1 1 1 1

Then it's worth noting that you never actually need to read the right branches on traversal, so those can be discarded:

tree[0]               13
tree[1]        8               .
tree[2]    4       .       4       .
tree[3]  2   .   2   .   2   .   1
tree[4] 1 . 1 . 1 . 1 . 1 . 1 . 1

Then move the size into the data structure itself, since that needs to be read frequently in the algorithm and not actually during traversal.

tree[0]        8               .
tree[1]    4       .       4       .
tree[2]  2   .   2   .   2   .   1
tree[3] 1 . 1 . 1 . 1 . 1 . 1 . 1

I've found that just this gives a noticeable but underwhelming speed-up factor of 3-4x; I was expecting with all the Boxing for that to be closer to 10. The problem seems to be that the branches are still unpredictable and the behaviour is still cache-thrashing; the main improvement came not from the change in format but from not writing to the right branch (not the eliding step but just not writing to it). Plus, allocators are likely to put all those boxed values next to each other, and the lack of space efficiency doesn't really hurt when doing psuedo-random access anyway.

Then note that with something like a (14345577, 15347)-permutation, \$\log 14345577\$ is much greater than \$\log 15347\$. You can use this to your advantage by ignoring the top of the tree:

tree[ 0]             8388608 ...
tree[ 1]           4194304 ...
...
tree[ 8]       32768 ...
tree[ 9]     16384 ...
...
tree[22]   2 ...
tree[23] 1 ...

You can actually discard tree[0..8]; jumps are normally going to be no greater than steps of 15347 times the "sparsity" of the data. When the sparsity gets so large that you are taking jumps that large, you can "recompact" the whole array in \$O(n)\$ time. Since you only need to do this when density drops somewhere below 50%, this is a relatively cheap way of moving from a total \$O(n \log n)\$ to \$O(n \log m)\$ time complexity (resizing each time capacity halves results in only \$O(n)\$ extra work).

Note that the top level then becomes a bunch of roots into sub-trees, not a single tree. Thus you can't ignore the right-nodes, or you'll be losing the size of the tree. Conceptually, those right nodes are calculated from the node above, so if there's no node above you aren't able to drop the value.

An extreme example would be a (10000000, 3)-permutation, where the entire tree is clearly overkill. This tree trimming works well there.

Then it's worth looking at those bottom rows, to see if we can do something more intelligent about them:

tree[X]                            64   ...
...
tree[X]    4       4       4       4    ...
tree[X]  2   .   2   .   2   .   2   .  ...
tree[X] 1 . 1 . 1 . 1 . 1 . 1 . 1 . 1 . ...

Despite the elided right branches, this is still a ton of data to express 64 bits of data. In fact, it uses 63 times that amount of data even after elision. Much more effective is to have an actual 64 bit integer.

0b1111111111111111111111111...

This can still be efficiently binary searched by utilizing a specialized routine, bit shifts, masks and u64::count_ones. In fact, on newer x86 processors you don't even have to; Jukka Suomela points out that it's as simple as

pub fn position_nth_set_bit(value: u64, mut bit: u32) -> u32 {
    // Holy smokes
    bmi_pdep_64(1 << bit, value).trailing_zeros()
}

Sadly I think right now I need to use asm!, but that's no show-stopper. If pdep isn't available, the binary search with count_ones is still pretty fast - but it's certainly not nearly as fast.

In fact, this also makes the compacting step that we need to elide the top of the tree much simpler; the bit-set acts as a mask over our values that we can just iterate.

Let's quickly calculate what the overhead is. Our entire tree looks like

roots           x              x
tree[X]     x       .       x
tree[X]   x   .   x   .   x   .
tree[X]  x . x . x . x . x . x .
masks    bbbbbbbbbbbbbbbbbbbbbbbb
values   VVVVVVVVVVVVVVVVVVVVVVVV  ← We don't need this until after compacting

values costs a usize per output value, but can actually be ignored until the first compaction as before then it's an identity map (values[k] == k at first).

masks introduces one further bit per value.

If you look at tree and roots the right way, you can see you can "slide" the xs down the right branches to fill exactly one row (I'll re-use this property later). The bottom-most tree[X] is at the 128 level (since masks.count_ones() works at the 64 level), so that's a usize of bits spent per 128 values.

Ergo we have 1-2 extra bits per value, and only half of the values actually need to be stored. So our space complexity is pretty close to n * usize::BITS / 2. If m is expected to approach n in size or space matters more than the move from \$O(n \log n)\$ to \$O(n \log m)\$, you can instead use masks without trimming the top of the tree, so no values array is needed, to get a space cost of roughly just 2 * n bits.

A pleasing hybrid might be obtained by making tree a little bit taller, so one has to resize slightly less frequently. Two extra layers means two extra branches per iteration but delays resizing until the density is about 1/8, leaving memory consumption of about n * usize::BITS / 8 while still having \$O(n \log m)\$ operations. Plus, doing the first resize early hurts as before it values is not used and the later resizes are smaller. On the other hand, a few extra branches is expensive when the branches are unpredictable, so it actually makes sense to keep the tree shallow and do a linear search over the roots. It's worth noting that resizing can make the tree smaller and isn't actually expensive, so the trade to do it later isn't so clear-cut. The precise parameters are tunable.

This is starting to feel optimal, since \$\log m\$ is about the smallest cost for a jump one can normally reasonably expect and we're approaching a small number of bits of overhead. However, we might be able to make the data structure more optimal. One possible improvement is to take the "compact" view of the tree we used to calculate its size: slide each value down the "right-hand slide":

roots           a              b
tree[X]     c       ↘       d
tree[X]   e   ↘   f   ↘   g   ↘
tree[X]  x ↘ x ↘ x ↘ x ↘ x ↘ x ↘
masks    bbbbbbbbbbbbbbbbbbbbbbbb
values   VVVVVVVVVVVVVVVVVVVVVVVV

to get

tree     x e x c x f x a x g x d · · · b
masks    bbbbbbbbbbbbbbbbbbbbbbbb
values   VVVVVVVVVVVVVVVVVVVVVVVV

Note that traversal is now just a binary search over a sub-range of the array. This might look tough to traverse, but it's actually a fairly mechanical transformation.

Generating this is more tough, but it does have the lovely property that each modulo is

1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, ...

which you can take the \$\log_2\$ of to get

0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, ...

OEIS helpfully adds that,

  a(n) is the number of 0's at the end of n when n is written in base 2

and then you note that n >> (n.trailing_zeros() + 1) gives how many times you've seen this value before, which lets you deal with the leftover parts.

Note that the modulo is for a "cropped" root, and so you need to take the min against the top-level modulo you're using, and you also need to add 7 before then to multiply all the modulos by 128 (because the bottom groups of 64 are dealt with in masks).

With my implementation, for very large \$m\$ (same order of magnitude as \$n\$), the tree pruning is entirely ineffective (and is just pointless overhead), so the only performance gains come from the change in how iteration happens, the move to iteration over a contiguous vector and the masks array removing the last few layers of the tree. The move to a contiguous vector is actually rather ineffective as a speed enhancer since the Boxes are probably contiguous anyway and the major overhead is in the unpredictable branching. There's roughly a factor 6 improvement over your code here.

For "medium"-sized \$m\$ (eg. \$n\$ is 14345577, \$m\$ is 15347), tree pruning comes into play and speed improves 3-fold. Your code does not, so the speed advantage increases. There's roughly a factor 20 improvement over your code here.

For small \$m\$ (eg. 3), the tree pruning pushes further increases speed significantly, resulting in massive decreases in time. Further, the BMI instructions at the bottom of the tree end up improving speed significantly. However, your code also becomes very predictable, since branches repeat frequently, so the cost there actually falls too and the overall relative speed improvement is not as great as the time reduction alone would imply. There's roughly a factor 32 improvement over your code here.

Honestly I was hoping for more, but I can see why the improvements were only this good. It should be possible to improve this a lot by using a B-tree instead of a binary tree, by effectively replacing

roots           x              x
tree[X]     x       .       x
tree[X]   x   .   x   .   x   .
tree[X]  x . x . x . x . x . x .
masks    bbbbbbbbbbbbbbbbbbbbbbbb
values   VVVVVVVVVVVVVVVVVVVVVVVV

with

roots       x       x       x       x
tree[X]       .       .       .
tree[X]  x x x . x x x . x x x .
masks    bbbbbbbbbbbbbbbbbbbbbbbb
values   VVVVVVVVVVVVVVVVVVVVVVVV

which should improve branch predictability by using intermittent unrolled linear searches. However, the reduction from doing this the "obvious" way is slight as you still end up with poorly predictable branches over spread-out locations.

Ideally, one should reorganize the values as

roots                      x x x x
tree[X]  x x x|x x x|x x x|
masks    bbbbbbbbbbbbbbbbbbbbbbbb
values   VVVVVVVVVVVVVVVVVVVVVVVV

instead.

Another oversight I've been purposefully ignoring is SIMD. Small SIMD vectors for usize-sized data makes this relatively weak, but lower down the tree a u16x8 vector is likely extremely useful, and basically makes an 8-wide B-tree optimal. Newer AVX instructions would do far better, and allow the whole tree to be heavily vectorized. I'm going to continue to ignore this, though, 'cause SIMD with Rust is not ideal right now.


Well, you need some sort of mapping between the parameters and the enum values, so you can't actually avoid having three almost same pieces of code. But you can make your code shorter by using ifs and |= instead of ternary operators:

private UserContactPreferences GetContactPreferences(bool email, bool phone, bool sms)
{
    var preferences = UserContactPreferences.None;

    if (email)
        preferences |= UserContactPreferences.Email;
    if (phone)
        preferences |= UserContactPreferences.Phone;
    if (sms)
        preferences |= UserContactPreferences.SMS;

    return preferences;
}

If you had more parameters (though that would be a code smell), it might be worth considering something like using a dictionary. But I'm not sure it's a good idea, it's certainly longer than the previous version:

private UserContactPreferences GetContactPreferences(bool email, bool phone, bool sms)
{
    var dictionary = new Dictionary<UserContactPreferences, bool>
    {
        { UserContactPreferences.Email, email },
        { UserContactPreferences.Phone, phone },
        { UserContactPreferences.SMS, sms }
    };

    var preferences = UserContactPreferences.None;

    foreach (var kvp in dictionary)
    {
        if (kvp.Value)
            preferences |= kvp.Key;
    }

    return preferences;
}


Loop through folder names on a server directory

Performance

If you really want to squeeze out every ounce of performance, I recommend early binding the FileSystemObject and related classes. From the "What form of binding should I use" from this MSDN article:

  Early binding is the preferred method. It is the best performer
  because your application binds directly to the address of the function
  being called and there is no extra overhead in doing a run-time
  lookup. In terms of overall execution speed, it is at least twice as
  fast as late binding.

Beyond that, there's not much more you can do in the way of performance. Most of the time here is going to talking to the remote file system. You could remove the ability to cancel or not update the status bar, but it's my belief the UX would suffer too much.

One thing you could do though is alter how often you update the status bar based on how many subfolders are found. Instead of having IterationsToUpdate be a constant, make it a variable and figure out a way to calculate how often the status bar should be updated using the SubFolder's Count property. Perhaps update at each 5%.

    IterationsToUpdate = CInt(Subfolders.Count * 0.05)

Update:

I changed my mind. There is something more you can do to make the performance better. Several things actually, but I'll let you decide if the second one is really worth it or not.

Stop Re-dimensioning the array. You already know how big it should be, so Dim it once and only once.

Dim MyArr(1 To objFolder.Subfolders.Count, 1 To 2) As Variant

This removes a lot of overhead inside of the loop. When you ReDim Preserve, you're effectively making a copy of the array at each iteration. There's no reason to do this when you know how big the array should be up front.

2. You could unroll the loop. Be aware, that doing this will cause a maintenance headache, but it *could significantly speed up the loop through the subfolders. This works by setting multiple "positions" of your array during each iteration.

*I do mean could. There's no way of knowing if it will actually perform better or not until it is tried and benchmarked.

Unfortunately, you can't access items in the Folders collection by integral index, only by key, so unrolling the loop is not an option.

Misc

Why delete the entire range here? Are all of those rows always filled? Could there ever be more?

wsOutput.Rows("2:1048576").Delete

It would be better to find the last non-empty row.
Why are you activating here? Smells like an unintended side effect to me.

 wsOutput.Activate

Perhaps you meant to select the range for the user? If so, the correct way to do that is this.

 wsOutput.Select

You don't need parenthesis here.

MsgBox ("Done")

You're wasting at least a few cycles telling the runtime to evaluate the default property of... a literal. I recommend reading over this StackOverflow Q & A that details the rules about using parenthesis in a routine call for more information.

It would also be nice to display the "Information" icon on the message box. It's a nicer UX.

 MsgBox "Done", vbInformation

Consider using another constant here instead of the literal 18.

If Err.Number = 18 Then

It's pretty clear what's going on from the context, but if I want to know exactly what that error is, I'd have to look it up. A (well named) constant keeps the maintainer in the IDE as it removes any ambiguity.


Answering your specific questions:

  Have used slow version of palindrome check assuming string is not going to be too long. Hope it doesn't affect performance that much.

You made a very good choice. This solution is simpler and more readable, you may switch to a new faster implementation later iff performance becomes a problem and you are sure is_palindrome is the problem.

  Approached problem via functional style, could have done all the computation in the same loop but is it a good practice?

To be precise on terminology, you used an imperative style with subroutines. I think that the use of subroutines ("functions") like you do greatly improves readability, so well done.

You may re-factor into functions further by writing a function to return pairs from a list and calling it from create_difference_list


Loading dictionary using trie in C very slow with large data set

A few notes:

typedef struct names are commonly written in PascalCase today.

Node* current = NULL;

Initialize your variables on the lowest scope as possible.  Therefore, declare your variables within your for loops. (C99)

for(int c = fgetc(dict); c != '\n'; c = fgetc(dict)) //iterate through word

Also, I feel as if you should be checking c for EOF, and then check for \n within the for loop.
The statements inside of your for loop look fishy to me:

if(current->children[c-'a'] == NULL)
{
    current->children[c-'a'] = calloc(27,sizeof(node))
    current = current->children[c-'a'];
}
else
{
    current = current->children[c-'a'];
}

No matter what, you are going to set children equal to current->children[c-'a'], so you can move that statement out of both branches of the conditional (DRY). Also, you should not be allocating 27 elements for every single Node.  Here is how I would write it:

if (!current->children[c-'a']) current->children[c-'a'] = calloc(1, sizeof(node));
current = current->children[c-'a'];

You can remove the != NULL part in your if conditional statements.
Avoid global variables: root and nwords.
Avoid magic numbers.

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

Use a #define instead at the top of your code.

#define NUM_NODES 27

But where does the number 27 even come from?  Documentation would go a long way here to help developers understand what it is.
Set your Node values to NULL after you free them.  This is so that you do not try to access the data again after it has been freed.


Don't mix a "library" class and input/output that is a bad style. If you really need to output some debug output, use a logger.
In push(), in case the a stack is full, you need to throw an exception or return an error code. Don't just silently ignore the error.
Same problem with the pop() method. Don't just ignore the error, notify the caller. And do not simply return 0, because it is a valid value that can be stored in a stack, so caller will not be able to distinguish error from successful call.
isFull() can be rewritten as a one-liner:

isFull() { return top == MAX_SIZE - 1; }

Don't use #define to define a constant. Use const int. #define works as a simple text substitution and is a very old and very outdated way to define constants.
Add templates to your stack to support not only a stack of ints, but a stack of any type.
Is it a feature that your stack has a limited size? If yes, consider specifying max size through the constructor. If not, extend your internal array when the limit is reached.
The top variable is pointing to the last set element. Why not to change invariant to "point to the first free element" and replace this awkward top = -1 initialization with top = 0?
print() should not be in your stack class. Provide a generic way to iterate though your stack (read about how STL iterators are implemented or implement your own iterator) and let a user decide what to do with each value from a stack while iterating it.
You can replace top++; A[top] = x; with A[++top] = x. You are using similar style in other place of your class anyway.
Consider renaming array A. The name is not descriptive at all.
Well... "Mystack" name is awkward, rename it to "Stack" :)