Optimal algorithm to move a a rope from one position to another

Your bolded question What is the optimal algorithm is off-topic for Code Review. If you're really interested in original-research answers to that question, I think it might plausibly be on-topic for Puzzling SE or Computer Science SE.

Certainly if you post in either of those places, looking for "optimal" algorithms, you will have to define what you mean by "optimal." The simplest way of doing that would also be useful on CodeReview — and also in general in your programming career! Provide test cases.

assert solve([2, 4, 6, 3], [-2, -4, -6, -3], 3) == 42

This test case was constructed by looking at your sample program and then filling in an utterly random number 42 in the one place that matters. When you post the question elsewhere (and/or here again), make sure to have that number filled in.
And then give some other test cases!

assert solve([2, 4, 6, 3], [-2, -4, -6, -3], float('inf')) == 4
assert solve([1, 1, 1], [0, 0, 0], 1) == 3

And then consider what should happen in cases of "invalid input":

assert solve([1, 1, 1], [0, 0, 0], 0) is None
assert solve([1, 2, 1], [1, 3, 1], 1) is None
assert solve([1, 3, 1], [1, 2, 1], 1) is None
assert solve([1, 3, 1], [1, 3, 1], 1) is None

On your code itself, try to write out full identifiers instead of abbreviations: index (index of what?) instead of ind, for example.

When writing a "predicate" function that returns bool, give it a name that indicates the predicate, rather than an action verb: instead of check_legal (which should really be check_legality), prefer is_legal, so that you can write

assert is_legal(init, max_dist)

Notice that max_dist has no reason to be a keyword argument, and no reason to be optional. Instead of passing None and special-casing it, just pass float('inf') and don't write any special cases.

pos_options = [final[ind]]\
                  +[n+sign*max_dist for n in neighbors]

This line of code is impenetrable, due to the lack of whitespace and the backslash in the middle. I'd at least recommend

pos_options = [final[ind]] + [n + sign * max_dist for n in neighbors]

and then look for a way to refactor that or at least put a code comment explaining the logic behind the expression.


Recursive brute-force approach to maximum points you can obtain from cards

RE60K has already critiqued your algorithm, so I'll just leave some minor comments on the code style. These comments won't help you beat the time limit, but they are good habits to get into if you're going to take a coding interview someday, for example.

Your class Solution has only public members. Classes with all public members are frequently defined as structs instead.

In fact, your class has no data members! Classes with no data members should probably just be free functions. See The "OO" Antipattern.

Alternatively, you could keep the class as a sort of "namespace" for these two functions, but mark both functions static, so that you don't waste CPU cycles passing around a this pointer that you'll never use. In this case, you should also mark maxScoreUtil as private because it should never be called by anyone outside the class itself.

Alternatively, notice that your current code is paying for a this pointer and also paying to pass dp as the last argument to maxScoreUtil! It should only ever pay for one or the other. If dp always points to the same vector, maybe dp should be a data member of class Solution.

In all of these cases, the elements of cardPoints are not intended to be modified, so you should mark that parameter as const.

To summarize: Right now your code's skeleton is

class Solution {
public:
    int maxScoreUtil(int left, int right,vector<int>& cardPoints, int k,vector<vector<int>>& dp);
    int maxScore(vector<int>& cardPoints, int k);
};

but it should probably be either

class Solution {
    static int maxScoreImpl(int left, int right, const vector<int>& cardPoints, int k, vector<vector<int>>& dp);
public:
    static int maxScore(const vector<int>& cardPoints, int k);
};

or

static int maxScoreImpl(int left, int right, const vector<int>& cardPoints, int k, vector<vector<int>>& dp);
int maxScore(const vector<int>& cardPoints, int k);

or arguably

class Solution {
    vector<vector<int>> dp;
    vector<int> cardPoints;
    int maxScoreImpl(int left, int right, int k);
public:
    static int maxScore(vector<int> cardPoints, int k) {
       int n = cardPoints.size();
       Solution s{ vector<vector<int>>(n+1, vector<int>(n+1, -1)), std::move(cardPoints) };
       return s.maxScoreImpl(0, n-1, k);
    }
};

Notice that I've quietly changed your maxScoreUtil to maxScoreImpl (for "implementation"); that's the usual convention for an internal implementation function. "Util" (for "utilities") is more often used as a namespace or class name for general-purpose utility functions.

    if(k == 0 || left == cardPoints.size() || right < 0)
        return 0;

Surely this should say ... || right < left. Also, here and on the next line, you should get in the habit of curly-bracing any time you indent. It'll save you a lot of debugging someday. Consider the difference between

if (failed) {
    puts("oops, exiting");
    exit(0);
}

and

if (failed)
    puts("oops, exiting");
    exit(0);


I understand that you are asking from a parallel point of view, but I am unable to provide feedback on that, as I have never worked with this system before. But from my point of view, creating a parallel solution is has been done premature.

Prior to creating a parallel solution to speed up your solution, you should improve the efficiency of the algorithm. At present you consider all numbers in the range of [1, 10N), whereas you only need to evaluate numbers where the number of digits in the number is equal to N. In which case you only need to evaluate numbers in the range of [10N-1, 10N).

You could further improve this via considering permutations and combinations. This would allow you to calculate all the different combinations of the digits for the given range. Once you have these you can then check which of the combinations digits sum to the required total.

If X combinations sum to a given total then you can quickly calculate how many numbers within the require range have N digits and sum to the goal. By computing X * (N Perm N) where N is the number of digits and where permutations are calculated without replacement. Representing just the N digits in the solution.

At this point you would be using a parallel solution to calculate the combination hits, but you may find the bottle neck of data transfer to a GPU causes the parallel solution to perform slower than the non-GPU enabled solution.


Part 1: Create or update record via HTTP request

Can the script be improved?

Jython is somewhat of a horror show, so improvements are limited but still possible.
List comprehensions
params = list( param for param in request.getQueryParams() if param.startswith('f_') )

can be
params = [
    param for param in request.getQueryParams()
    if param.startswith('f_')
]

Dict comprehensions
This just squeaked into Python 2.7:
paramdict = {
    p[2:]: request.getQueryParam(p)
    for p in params
}

Factor out common code
Factor out common code from these blocks:
if woMbo is not None:
    for k,v in paramdict.items():
        woMbo.setValue(k,v,2L)
    resp = 'Updated workorder ' + request.getQueryParam("f_wonum")
    woset.save()
    woset.clear()
    woset.close()
else:
    woMbo=woset.add()
    for k,v in paramdict.items():
        woMbo.setValue(k,v,2L)
    resp = 'Created workorder ' + request.getQueryParam("f_wonum")
    woset.save()
    woset.clear()
    woset.close()

For example,
if woMbo is None:
    woMbo=woset.add()
    verb = 'Created'
else:
    verb = 'Updated'

for k,v in paramdict.items():
    woMbo.setValue(k,v,2L)
resp = verb + ' workorder ' + request.getQueryParam("f_wonum")
woset.save()
woset.clear()
woset.close()

Guaranteed closure
Wrap your code in a try/finally:
woset = MXServer.getMXServer().getMboSet("workorder",request.getUserInfo())
try:
    # ...
finally:
    woset.close()

Named constants

the constant 2L tells the system to override any MBO rules/constraints

Fine; so it should get first-class treatment:
IGNORE_RULES = 2L


Any use for this kind of self invoking function?

Wow. Basically you wrote Code A but in a cool functional programming style.

Code A:

(function(){
    function foobar(id) {
        var element = document.getElementById(id);
        element.style.color = 'red';
        element.style.textIndent = '10px';
    }
    for(var i = 0, len = arguments.length; i < len; i++){
        foobar(arguments[i]);
    }
}('foo', 'bar'));

Self invoking functions are good for three situations.

To perform some startup functions onload. (Most likely your case)
To save results from a expensive operation into a loop up table.

Example:

var primeTable = (function(){
    var primeObject = {}
    // calculates and stores primes from 100 to 1000 in primeObject
    return primeObject;
})();

3. To create private variables, which is normally called a Module Design Pattern.

Example:

var box = (function () {
    var key = Math.floor(Math.random() * 1e5).toString(16);
    return {
        open : function(val){
            return (val === key) ? "Box has opened." : "Wrong Key";
        },
        setKey : function (oldKey, newKey) {
            if (oldKey === key) {
                key = newKey;
            }
        }
    }
})();

Overall, if you want to follow KISS philosophy then I think you should wrap everything in a closure and call the function traditionally.

(function(){
    function foobar(id) {
        var element = document.getElementById(id);
        element.style.color = 'red';
        element.style.textIndent = '10px';
    }
    foobar('foo');
    foobar('bar');
})();


public IEnumerable<object> Build(Project project, IServiceBusResolver serviceBusResolver, TIncoming incomingMessage)
{
    TOutgoing outgoingMessage = BuildOutgoingMessage(project, serviceBusResolver, incomingMessage);

    return outgoingMessage != null ? new[] { outgoingMessage } : null;
}

Why should this return an IEnumerable<T> ? This just doesn't make sense at all. BuildOutgoingMessage() is only building one object.

The BuildOutgoingMessage() method doesn't use the serviceBusResolver parameter. If this is because it is only for overriding in a derived class, you should consider to add some documentation for this case.

The MessageBuilder class states that it implements IMessageBuilder<TIncoming> but it doesn't implement its method.


Filtering on an array of object literal properties and their nested array values

First, and I can't emphasize this enough, use meaningful variable names. What is argOne? argTwo? The same goes for all of your single letter variable names. They make it harder to look at your code and figure out what's going on.

To help you see where the code you provided might be difficult to understand, I've copied it and commented what came to mind when reading each line, hopefully this can help with writing code that self-documents.

// It looks like this will filter arrObjLit based on pattern.
// But what is argOne, argTwo? Do I need both? What if I include argThree?
function sift(arrObjLit, pattern, argOne, argTwo) {
  // Filtering as expected, but why is the index y needed?
  return arrObjLit.filter(function(x, y) {
    // Where did result come from? Right now it declares a global variable.
    // What is q? Is the index of it, i, needed?
    // Does this need to be wrapped in parenthesis?
    // The above line used function, here there's an arrow function. Why?
    return (result = Object.entries(x).some((q, i) => {
      // Okay, q[1] is the value, but q[0] isn't used, maybe
      // Object.values() should be used above?
      // What happens if q isn't an object?
      for (let [key, v] of Object.entries(q[1])) {
        // This is clear, but what is special about argOne?
        // Why not check argTwo here too?
        if (key.startsWith(pattern) && Array.isArray(v) && v.includes(argOne)) {
          // Why is [x.data][0] used instead of just x.data?
          // x.data == q[1]? What happens if q[1] != x.data?
          for (let an of Object.values([x.data][0])) {
            // Why don't we check that the key for the an array starts
            // with key like we did for argOne?
            if (Array.isArray(an) && an.includes(argTwo)) {
              return true;
            }
          }
        }
      }
    }))
  })
}

In chat, you mentioned that ideally, every array contained within the object should be searched, if it matches the pattern. With this in mind, here is how I would solve your problem. (It might be a good idea to rename pattern to prefix, with pattern I would expect that I can pass in a regular expression)

function sift(entries, pattern, ...filters) {
  return entries.filter(entry => {
    // Copy the filters array into a set
    let toMatch = new Set(filters);

    let searchForMatches = root => {
      for (let [key, value] of Object.entries(root)) {
        if (Array.isArray(value) && key.startsWith(pattern)) {
          // The key for the array matches the pattern, so remove all of these
          // items from the required items to match, if they are found
          value.forEach(item => toMatch.delete(item));
        } else if (typeof value == 'object' && value) {
          // This item isn't null, and is an object.
          // It may contain an array, recurse
          searchForMatches(value);
        }
      }
    };

    searchForMatches(entry);

    // If the set is empty, all matches were found
    // and this object should be included in the result.
    return toMatch.size == 0;
  });
}


Random array of numbers without repeating - oojs practice

Your check method is inefficient for large datasets. I'd recommend using a hash instead. This will eliminate the need of iterating over the array every time you want to check if a number is there.
It is possible for your code to enter an infinite loop if count is greater than max - min. You need to test for this.
The code can be simplified a bit as well.
The recursion slows down the generation dramatically.

I've take then liberty of performing some optimizations: http://jsfiddle.net/FMSpG/2/

function Randoms(c, l, h) {
    var count = c,
        min = l,
        max = h,
        nums = {},
        out = [],
        r, len = 0;

    if (max - min < count) count = max - min;

    var getRand = function() {
        return Math.floor(Math.random() * (max - min) + min);
    },  check = function(a) {
        return nums[a];
    },  add = function(a) {
        nums[a] = 1;
        out.push(a);
        len++;
    };

    (function init() {
        while (len < count){
            if (len == 0) r = getRand();
            else while (check(r = getRand()));
            add(r);
        }
    })();

    this.get = function() {
        return out;
    };
}

And here's a jsPerf showing the huge difference in performance for large datasets:

http://jsperf.com/unique-randomization


Running xinput to change touchpad settings

There's no need for a redundant pass after your if; these can be deleted:

else:
    pass

xinput --list and xinput --list-props aren't long-running commands.  It's simpler to subprocess.run() them, with standard output redirected to a variable:

get_device_id = subprocess.run(["xinput", "list",
                                "SynPS/2 Synaptics TouchPad"],
                               capture_output=True)
if get_device_id.returncode != 0
    sys.exit(get_device_id.returncode)
gdi_str = get_device_id.stdout

I don't believe that first command is actually required - xinput --list-props is quite happy to accept a device name instead of a property:

xinput --list-props 'SynPS/2 Synaptics TouchPad'


Validate a string for positive number and normal string

If all negative and zero number strings are invalid, you do not necessarily have to parse it to a long. You can use java regex (regular expressions) to test if the code is negative or zero:

string.matches("-\\d+") // Matches all negative integers, even if they are less than `Long.MIN_VALUE`
string.equals("0") // If the string is zero
string.matches("0+") // If the string consists of a bunch of zeroes, nothing else, or even better
string.matches("0*") // If the string contains nothing except zeroes, meaning this will also match an empty string

So, other than that, this code looks fine to me, but parsing values is fairly expensive and catching exceptions is very expensive, so using regular expressions is probably better.


permutations[count] = Arrays.copyOf(array, array.length);
        return count + 1;

Here you are copying the array into the permutations array after permuting the array itself.  This is why you have to keep making copies of the array.

        return count;

If you instead do nothing in this case, you can change

    else
    {
        for (int i = midStart; i < array.length; i++)
        {
            T temp = array[i];
            array[i] = array[midStart];
            array[midStart] = temp;
            count = permute(permutations, array, midStart + 1, count);
        }
        return count;
    }

to copy the array before recursing instead.

        count = permute(permutations, array, midStart + 1, count);
        for (int i = midStart+1; i < array.length; i++)
        {
            permutations[count] = Arrays.copyOf(array, array.length);
            permutations[count][i] = array[midStart];
            permutations[count][midStart] = array[i];
            count = permute(permutations, permutations[count], midStart + 1, count + 1);
        }

        return count;

Now you never change the original array and you don't have to do any extraneous copies.  A side effect of this is that you don't need a temporary variable to do the swap either.

Note that I also changed the for loop not to do the no-op swap at the beginning.  This was necessary since we don't want to copy in that case.

We're now one copy short, so change

public static void <T> permute (T[][] permutations, T[] array)
{
    if (permutations.length != factorial(array.length))
        throw new IllegalArgumentException();
    permute(permutations, array, 0, 0);
}

to

public static <T> void permute (T[][] permutations, T[] array)
{
    if (permutations.length != factorial(array.length)) {
        throw new IllegalArgumentException();
    }

    permutations[0] = Arrays.copyOf(array, array.length);
    permute(permutations, array, 0, 1);
}


SQL Query - records within the last year

The following are a few suggestions on how I'd write your view.
Source Control
If you don't already have a database project, create one in Visual Studio. Then check it in to source control. Microsoft Azure DevOps Services is free & private for teams of 5 or less (this is per project, so 5 developers per project). Then you'll be able to track changes you make to your stored procedures, views, tables, etc.
Formatting
I would download the following tool for SSMS and Visual Studio, Poor Man's T-Sql Formatter and on GitHub. I use it when I have to edit other developer's code. It's a great way to standardize your SQL. I find it does most of the formatting for me, but I'll still make a few changes after.
Here are the settings I used:

Commas
I would put the commas in front to clearly define new columns. Versus code wrapped in multiple lines. It also makes trouble-shooting code easier.
Where Clause
If you put 1=1 at the top of a WHERE condition, it enables you to freely change the rest of the conditions when debugging a query. The SQL query engine will end up ignoring the 1=1 so it should have no performance impact. Reference
Common Table Expressions (CTE)
CTE's in your SQL help with documentation. The expression name can then let other developers know why you used that expression e.g. current_suppliers or active_projects.
Schema Names
Always reference the schema when selecting an object e.g. [dbo].[SalesTable].
Estimated Execution Plan
It's a good idea to check the Estimated Execution Plan. The shortcut in Microsoft SQL Server Management Studio (SSMS) is Ctrl + L. You can even run 2 queries in the same tab to compare the plans.
Keywords
Avoid using keywords as object names. Microsoft Reference

Also check out the book Clean Code. It will change the way you think about naming conventions.

Revised SQL
Without table definitions and sample records I was unable to test this, but it should give you a good start.
WITH
earliest_interaction
AS
(
    SELECT
          [min_createdate] = CAST(MIN(r.[CreateDate]) AS DATE)
        , r.[Email]
    FROM
        [dbo].[Results] AS r
    WHERE
        1=1
        AND (r.[Email] IS NOT NULL AND r.[Email] != '')
    GROUP BY
        r.[Email]
)
,
log_files
AS
(
    SELECT [Email] FROM [dbo].[LOG1] WHERE [Source] = 'LOGGED'
    UNION
    SELECT [Email] FROM [dbo].[LOG2] WHERE [Source] = 'LOGGED'
)
SELECT
      ei.[min_createdate]
    , ei.[Email]
FROM
    earliest_interaction AS ei
    INNER JOIN log_files AS lf ON lf.[Email] = ei.[Email]
WHERE
    1=1
    AND (ei.[min_createdate] >= DATEADD(YEAR, -1, GETDATE()))


Convert Improper Fraction to Mixed Number with JavaScript

What you're doing with i = (n / d) >> 0 is a sign-propagating right shift. The interesting this is, you're doing a right shift by 0 (I'd imagine because you'd otherwise get NaN. Your method of doing so is a cheap version (read: performance hack?) of doing i = parseInt(n / d). Here's your function with the SPRS removed and replaced with parseInt() instead. I've also implemented simplification.

function improperFractionToMixedNumber(n, d) {
    i = parseInt(n / d);
    n -= i * d;
    return [i, n, d];
}

Here is the same function, but also implementing simplification via a helper function reduce:

// Improper fraction to mixed number
// n = numerator
// d = denominator
// i = number
function improperFractionToMixedNumber(n, d) {
    i = parseInt(n / d);
    n -= i * d;
    return [i, reduce(n,d)];
}

function reduce(numerator,denominator){
    if (isNaN(numerator) || isNaN(denominator))
      return NaN;
    var gcd = function gcd(a, b){ return b ? gcd(b, a%b) : a; };
    gcd = gcd(numerator, denominator);
    return [numerator/gcd, denominator/gcd];
}


Russian Peasant Multiplication Algorithm

It looks to me that you're being too literal.  When trying to convert an analog process to code it's easy to fall into that trap.

Presently you're using 2 loops to make 2 lists.  This is unnecessary.  You can do everything including calculate the answer in one loop.

You're also not checking for which number is the lesser one and which is the greater one.  This is integral to the base algorithm, that you're trying to emulate.

A simplified version could look something like this:

int PeasantMultiply(int num1, int num2)
{
    auto pair = std::minmax(num1, num2);
    int min = pair.first;
    int max = pair.second;
    int total = 0;
    if (min != 0)
    {
        do
        {
            if (min % 2 == 1)
            {
                total += max;
            }
            min /= 2;
            max += max;
        } while (min > 0);
    }
    return total;
}

After looking at this code again, I came upon an optimization.  Instead of using the modulus operator(%), I could accomplish the same thing with and extra int variable and use subtraction instead:

int PeasantMultiply(int num1, int num2)
{
    auto pair = std::minmax(num1, num2);
    int oldMin = pair.first;
    int max = pair.second;
    int total = 0;
    int newMin = 0;
    if (oldMin != 0)
    {
        do
        {
            newMin = oldMin / 2;
            if (oldMin - newMin != newMin)
            {
                total += max;
            }
            oldMin = newMin;
            max += max;
        } while (oldMin > 0);
    }
    return total;
}

In my tests this saves about 10% in time.


Statement checker c# using forms and frontend

Review
It seems that you are trying to make a simple calculator with number comparison in C#. There are some problems in this implementation.
ToInt32:
Do you expect the input of calculation is always in int format? How
about floating numbers?
Nah method:

Naming:
I have no idea how's the name Nah imply the operation in the method. Something like run or perform are better than Nah.

Integer Division:
Notice that the execution of 3 / 2 in this implementation is 1.
It is a kind of integer division. Is the integer division result
the correct output you expected?

MessageBox.Show Part:
In C# 6, you can use string interpolation and make MessageBox.Show("Sum of thenumbers entered is: " + (a + b)); into MessageBox.Show($"Sum of thenumbers entered is: {(a + b)}");. Interpolated strings are useful in string displaying and it's commonly used with Console.WriteLine or MessageBox.Show.

Error Handling

Null or empty string:
You use textBox1.Text and textBox2.Text as a way to read numbers from user input. How about the case of empty strings (user click button Check directly without type any character)? If textBox.Text passes in Convert.ToInt32 directly and the content is empty, System.FormatException will occur. Maybe String.IsNullOrEmpty check can be used here.

DivideByZeroException
DivideByZeroException Class can be used to handle an attempt to divide an number by zero.


Place div's of different heights in a responsive parent div

Introducing... CSS Flexbox (Tada)!

The markup.

<?php include('topics/t1.php'); ?>

<?php include('topics/t2.php'); ?>

<?php include('topics/t3.php'); ?>

<?php include('topics/t4.php'); ?>

We'll set #topics-wrapper to be our flexbox container. Put space between children when necessary, and allow wrapping.

#topics-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
}

Hide the ghost element for now, it'll come in handy later.

.flex-ghost { display: none; }

Normally, we want children to be 32% in width.

#topics-wrapper > div {
    flex-basis: 32%;
}

On medium screens, switch to 49%.

@media (...) {
    #topics-wrapper > div {
        flex-basis: 48%;
    }
}

Go all out on small screens.

@media (...) {
    #topics-wrapper > div {
        flex-basis: 100%;
    }
}

Now, we want column 4 on the left on medium screens, so in your medium media query, allow the ghost to fill the space it would take.

.flex-ghost { display: block; }

You'll never completely be able to imitate Masonry, but hopefully I've given you a good start. Especially experiment with flex-direction and flex-wrap. Learn Flexbox, it'll change the way you write CSS forever!


Loading components on startup, with timing measurements

You need a generic method like this:

static T createInstanceOf<T>() where T : new() {
  var stopwatch = Stopwatch.StartNew();
  T result = new T();
  stopwatch.Stop();
  Logger.Trace("Loaded "+ result.GetType().Name +" [took " + packetManagerStopwatch.ElapsedMilliseconds + "ms]");
  return result;
}

Now you can simply use it like this:

_packetManager = createInstanceOf<PacketManager>();
_achievementManager = createInstanceOf<AchievementManager>();
_talentTrackManager = createInstanceOf<TalentTrackManager>();
_badgeManager = createInstanceOf<BadgeManager>();
// and so on...


Dynamically create array with nested objects/array

I can propose more functional approach. I don't have arguments to say that it's better, it's just how I prefer to write code for generating two-dimensional arrays filled with some initial values.

function createRow(rowLength: number) {
    return Array(rowLength).fill(null).map(() => ({
        isChecked: true,
        src: ''
    }))
}

function updateTileEditor(length: number, height: number) {
    this.tiles = Array(height).fill(null).map(() => ({
        row: createRow(length)
    }));
}

Explanation:

Array(height) creates an empty array of fixed size height - we want to create height rows.
.fill(null) is used to fill the array with any values, so you can map these values to new ones. Any other value can be used instead of null. Mapping empty array would return us new empty array.
.map(() => createRow(rowLength)) creates new array in which each value is a new row. () => createRow(rowLength) gets called for each value in the array, so you can be sure that you will have new row for each value.

I also renamed x to length and y to height - these names are more descriptive, which I think can help new readers with figuring out the purpose of these variables.

I will write it here, because I don't have enough reputation to comment:
you could also use arrays for rows instead of objects that have one property called "row".
If you have only one value then maybe you don't need to wrap it in an object? - I guess I would need more details about the problem to say that.


Better way to display list of categories

Here's how I might try to clean things up:

refer to object properties without bracket notation where possible
e.g. data.categories.length
create a loop variable for the current category, which allows you to reference it nicely without data.categories[i]

for (var i = 0; i < data.categories.length; i++) {
    var category = data.categories[i];
}

don't look up the container on every iteration, move that outside the loop:

var container = document.getElementById('js--journal__categories');
for (...loop...) {
    ...create your node...
    container.appendChild(link);
}

same for creating the comma node, create it outside the loop.
you don't need to wrap i + 1 in parenthesis, and this is just my preference, but you should be consistent with spaces. You could also use < instead of != which is more consistent with the for loop. (These are fairly minor nits)

if (i + 1 < data.categories.length)

Why are you using double dashes and underscores in your element IDs?
Comments are helpful to explain what your for loop and if statement is doing, since it's probably easier/quicker to understand the comment than figure out the for loop.
Maybe I'm getting overkill at this point, but a way to write really descriptive, easy to read code is to break it into functions whose name makes sense:

function createCategoryElement(name, url_title) {
    ...create your anchor element here...
    ...set its attributes and content, etc...
    return element;
}

I ended up with something like this:

var data = {
  categories: [
    {name: 'one', url_title: 'oneUrl'},
    {name: 'two', url_title: 'twoUrl'}
  ],
};

var container = document.getElementById('container');
var comma = document.createTextNode(', ');

function createCategoryElement(name, url) {
  var urlBase = '#journal-category-';
  var cssClass = 'js-page-link';

  var el = document.createElement('a');
  el.setAttribute('href', urlBase + url);
  el.setAttribute('class', cssClass);
  el.innerHTML = name;
  return el;
}

// Create HTML elements for each category and append them to the DOM.

for (var i = 0; i < data.categories.length; i++) {
  var category = data.categories[i];
  var categoryElement = createCategoryElement(category.name, category.url_title);
  container.appendChild(categoryElement);

  // Join categories with a comma
  if (i + 1 < data.categories.length) {
    container.appendChild(comma);
  }
}

        for (...loop over categories...) {
            ...
            var categoryElement = createCategoryElement(category.name, category.url_title);
            container.appendChild(categoryElement);

            if (i + 1 < data.categories.length) {
                containenr.appendChild(commaElement);
            }
        }


Using goto to wait on the result of a database query to change

Besides the unjustified use of goto, I also object to the use of the number 4 for an operation that you try up to 6 times.

Counting loops are usually best written as for loops.

public function wait_lock() {
    for ($tries = 0; $tries < 6 && !($lock = $this->is_enabled('cache-lock')); ++$tries) {
        sleep(1);
    }
    if (!$lock) {
        // the following method is a short cut for throwing an exception.
        $this->e('cache error. wait a few moments and try again. if the problem persists, contact the administrator.');
    }
}


Dynamically update attribute of a same name in different classes

For one thing, getCurrentSectionStatus(entity) is duplicated multiple times. It would be better to put that in a local variable and use that variable instead.
That way if at some point you change the way you get the current section status,
you can make the change in one place.

However,
there are clearly deeper problems with this code.
Most noticeably,
field names such as StatusPI1, StatusPI2, ..., and StatusSI1, StatusSI2, ..., stink, as variable names containing numbers usually do.

Translated to pseudocode, the method looks like this:

if the TransactionLine contains a HorsePurchase: update a field in it depending on the section field of the line
or else, if the TransactionLine contains a HorseSale: update a field in it depending on the section field of the line
or else, if the TransactionLine contains a HorseDivideProfit: update a field in it depending on the section field of the line

At the minimum, it would be better to have separate TransactionLine subclasses to handle each type, for example HorsePurchaseTransaction, HorseSaleTransaction, HorseDivideProfitTransaction.
Then you could have an HorsePurchase.update method that takes a HorsePurchaseTransaction as parameter and apply the necessary changes,
and do similarly for the other types too.

This is still not enough to treat the odd StatusPI1, StatusPI2, and other fields, but just based on the posted code, I don't think there is enough information to propose an alternative approach. After splitting the TransactionLine as I described above, you could post the revised version and some more of the rest of the code in a new question,
so that we can address these issues and suggest further improvements.


LPTHW - ex48 - Handling exceptions and unit testing

lword = string.lower(word)

There is no need to import the string module for this, you can use:

lword = word.lower()

As for this:

elif int(lword):

Probably better as

elif lword.isdigit():

As for your exception handling

     except:
         action.append(('error', word))

You should almost never use a bare except. You should catch a specific exception, and put a minimal amount of code in the try block. In this case you could have done something like

try:
   actions.append( ('number', int(word) )
except ValueError:
   actions.append( ('error', word) )


Random C++ STL-only password generator for education

The code looks good. May be argument parsing could be done better, but in general this is solid simple password generator. There are things to mention though, but they mostly apply on reusability and expandability

Separate concerns

At the moment the main() function does quite a lot of things:

Setup random number generator
Parse program arguments
Generate password
Output it to the user

Encapsulate

I'm not saying reduce usability, but the password generator is very much like random number generator, it just gives out strings with random elements instead of bit blocks.

So, in my opinion, the following code would have sound design:

class random_password_generator
{
    //random engine and distribution
public:
    random_password_generator()
    {
        //initialize
    }

    //random engine will decide rule of 5

    std::string operator()()
    {
        //create password
    }
}

Parsing arguments can be just a plain function. For complex cases may be using Boost.program_options would be better.

Code Review

atoi(argv[++i]);

atoi is a C standard library function. stoi is a C++ function standard library. In general, C++ library is more compatible with concepts of C++ itself, whereas C library usually needs some wrappers to be usable with the rest of C++.

int length = 16;

My personal preference is to use unsigned int or std::size_t for things that cannot have negative values.

Do not use bind unless necessary

std::bind() might have problems that lambda can't solve, but I'm yet to encounter such problems. In general: use lambda for function objects unless you can't. The reason is that std::bind does heap allocation, type erasure, and possibly other stuff, whereas lambda is just anonymous object with operator().

Range loops

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

The above also has a chance to fail in case you'll change the resizing part of the string. It is better to use range for loop:

for (char& c: password)
{
    //assign
}

It will also remove the need to use at(), which does bounds checking, and in general frowned upon in release code.

Even better

Use standard algorithms. Since the functor generates random characters, code could just use std::generate(password.begin(), password.end(), generator).

Do not use std::endl

std::endl is not only a platform independent way to print newline. Printing newline is achieved with streaming '\n'. Even on windows ostream will deal with it. std::endl prints newline and flushes stream, which might cause detrimental performance hit in tight loops.

Don't use C style casts

(int) charset.size()

C style casts are much more dangerous, and compiler will not warn you if it does something dangerous. On the other hand, using one of C++ style casts will ensure compilation error in case something fishy is going on, except reinterpret_cast<>, which is fishy by definition.


Yes there is. As KeyEvent is an enumeration type, you can instead use a switch-statement:

char key;
boolean isSpecialKey = false;
SpecialKey specialKeyValue;
switch(key.getKeyCode()){
    case KeyEvent.VK_UP:
       key = '';
       isSpecialkey = true;
       specialKeyValue = SpecialKey.ARROW_UP;
       break;
    case KeyEvent.VK_W:
       key = 'w';
       break;
    //Continue...
}

I took the liberty of creating a new SpecialKey enum that is supposed to handle special keys when pressed.  For these, there is also the isSpecialKey flag. You simply wouldn't create a case for Keys that you don't handle. Instead, do nothing in the default case.


java if `String` begins with "red" or "blue"

Why aren't you using String.startsWith(prefix)?  This should be a one-liner.

return str.startsWith("red")  ? "red"  :
       str.startsWith("blue") ? "blue" : "";


Checking for a palindrome in any sub-range of a range

Well, especially with templates, the devil is in the details.

Yes, the template has the desired behavior, if it works. Your code expects a readable bidirectional range knowing its size which is not a raw array.

You really don't need to ask for the ranges size, compare iterators instead.

Asking for the previous position is inexcusable if you don't need it.
Instead of checking curr vs curr+1 and curr vs curr+2 in the loop and finally end-1 vs end-2 after, check begin vs begin+1 before the loop and curr vs curr+2 and curr+1 vs curr+2 in the loop

Until the Ranges TS is incorporated into the core standard, making a range from an iterator-pair is uncomfortable, while getting a start- and end-iterator from a range is easy. So, go with the common interface using two iterators.

Also consider adding a specialization for single-pass-ranges. Allow requesting it manually, as it should be more efficient if dereferencing an iterator is expensive.

See the answer to question 2 about .cbegin() and co.
Calling the "c versions" of the member-functions restricts your codes generality.

They aren't part of the core range-interface, being just convenience-functions for non-generic code, so not all types have them. See std::initializer_list<T> for a common one.

Even though raw arrays are perfectly fine, they lack member-functions.

In summary, always use the free functions, especially in generic code.
Using iterators instead of the indexing-operator allows you to efficiently use a type without cheap random-access, like lists, files, and so on.

The aim is to require the minimum interface you can get away with without compromising efficiency, so your algorithm is as generally useable as possible.

Some algorithms will take advantage of additional capabilities to provide more efficiency or other additional guarantees.


Plotting a graph of survey answers in Laravel

I think my main criticism of this code would be that it is asymmetric in terms of where ownership of instantiating your different object dependencies lives.

For example, in the first conditional around whether Dataset exists on the Chart, why does this code need to own the logic to create and attach a new Dataset?  If the Chart object "owns" the datasets, I would think that perhaps all this code would do is call a Chart::createNewDataset() or similar method to handle the work building a new dataset and setting it on the Chart.

This same concern exists for me with regards to creating Category objects.

I would also strongly recommend using type hinting for the parameter to enforce that you are getting passed a valid survey object.


vector<int> sa, pos, tmp;
int n, gap;

Surely you could come up with better variable names than these? Also, tmp and sa are only used inside the constructor, so they should be local variables, not struct members.

SuffixArray(string s)

This should be const string & s to avoid unnecessary copying of the string.

for (int i=0; i<n; i++) sa[i] = i, pos[i] = s[i], tmp[i] = 0;

The comma operator has a few legitimate uses, but this is not one of them. Coding it this way will lead to problems if you need to modify the loop body at all. The right way to do this is to make a multi-statement loop the usual way: curly braces surrounding multiple lines with one statement on each line.

 for (int i=0; i<n; i++)
 {
   sa[i] = i;
   pos[i] = s[i];
   tmp[i] = 0;
 }

     for (gap = 1;; gap *= 2) {

Why do you have a for loop with an empty termination condition?


Calculating positions along the edges of a rectangle

I would suggest that since only 2 of the procs are close enough to identical, just "combine" those:

set padWidth 95

proc setNumberedRightPins {x yTop pins} {
    foreach {number name index} $pins {
        set yOffset [expr {max(0, $number * $::padWidth - 2.5)}]
        setPin $name $x [expr {$yTop-$yOffset}] Right $index
    }
}

proc setNumberedTopPins {args} {
    setNumberedTopOrBottomPins {*}$args Top
}

proc setNumberedBottomPins {args} {
    setNumberedTopOrBottomPins {*}$args Bottom
}

proc setNumberedTopOrBottomPins {xRight y pins side} {
    foreach {number name index} $pins {
        set xOffset [expr {$number * $::padWidth + 2}]
        setPin $name [expr {$xRight-$xOffset}] $y $side $index
    }
}

Notes:

always brace your expressions, gain a big performance boost
constants can live in the global namespace, and you access them with a fully qualified variable name


Preferred implementation of `Array::operator=(const Array & rhs)`

template <typename T>
bool JKArray<T>::operator=(const JKArray<T> & rhs)

template <typename T>
void JKArray<T>::operator=(const JKArray<T> & rhs)

Neither of them have the correct signature for a copy assignment. The correct signature for that operator is class_name & class_name :: operator= ( const class_name & ).

That already rules out abusing the return value to signal success or failure. If you want runtime errors, you got to do it with exceptions.

If you violate that signature, it makes common patterns such as chained assignment (a = b = c = {...};) impossible. This may break other templated libraries depending on your datatypes to adhere to the standards.

Especially returning a bool may cause rather unexpected side effects.

  Pro

  Most of the time, the array is often thought of as a static container (there are std::vector, etc. for dynamic containers).
  It's more efficient, because I do not have to reallocate; rather, I overwrite each element of the LHS.

  Con

  It's a hassle for the user to do the work himself if he does intend to have a variable-length Array, plus it would be inefficient.

That list is by no means complete. There are more aspects to cover:

Iterator invalidation

When you have to re-allocate the backing data structure, it would be trivial to keep all existing iterators valid for same-size copies, while the same feat is problematic for different sizes.
Heap vs stack allocation

For fixed size arrays, it's not even necessary to allocate them on the heap, sufficiently small arrays may as well be allocated straight on the stack. This is obviously impossible to do with the dynamically sized ones.
Array or Vector?

While you call it Array, if you make it re-sizable it behaves more like an std::vector rather than an std::array.
Size as part of the type?

As @Olzhas mentioned, it's an option to include the size of the backing array as a template parameter. This provides compile time checks for compatible or incompatible sizes. Whereby compile time checks - if applicable - are obviously to be preferred.

This would actually be how std::array does it.


I see some things that may help you improve your program.

Break up the code into smaller functions

This is a very short program, so it's not critical here, but generally, rather than having everything in the main() function, it would be easier to read and maintain if each discrete step were its own function.  For instance, I'd separate out the token splitting function so that main looks like this:

int main(int argc, char **argv) {
    for (int i = 1; i < argc; i++) {
        split(argv[i]);
    }
}

Eliminate work that does not need to be done

The final j = 0 has no practical effect and should be eliminated.  Think carefully about what your program is doing so that you don't have the computer do more work than is necessary.

Eliminate "magic numbers"

The code is mostly free of "magic numbers' (that is, hard-coded values for which there is no obvious meaning), but I'd suggest that it would make sense to have the delimter string be an assigned variable.

Use a for loop instead of while

Because both pt and the j variables are only used within the while loop, consider again reducing scope and turning that into a for loop with one of those variables.

Use a single call to printf where practical

Instead of calling printf twice for each parsed value, it would simplify the program to simply call printf once instead of twice.

Sanitize user input better

The code doesn't quite work as posted, as you apparently already know.  It doesn't really take much more time or code to make the program not crash with malformed input, so I would strongly suggest doing so to make your program robust.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.

Results

Here's a reworked version of your program incorporating all of these suggestions:

#include <stdio.h>
#include <string.h>

void split(char *arg) {
    static const char* label[] = { "item", "quantity", NULL };
    static const char *delim = ":";
    const char **lbl = label;
    for (char *pt = strtok(arg, delim); pt != NULL && *lbl != NULL; ++lbl) {
        printf("\t%s: %s\n", *lbl, pt);
        pt = strtok(NULL, delim);
    }
}

int main(int argc, char **argv) {
    for (int i = 1; i < argc; i++) {
        printf("\nInput: %s\nOutput:\n", argv[i]);
        split(argv[i]);
    }
}

Some notes

The revised code includes two static const variables.  This means that they are initialized at compile time and do not change during the course of the program.  Further, every invocation of the split function has those variables set to the exact same values.  The advantage is that the compiler can turn this into very efficient code requiring little or no runtime execution and minimal code size.

The lbl variable simply points to the first label "item" first, and then steps through the labels in label until it encounters NULL at which point the routine will end whether or not there are more delimiters in the input string.

Finally, I'd recommend creating test code that runs a number of test cases and compares the actual output to the desired output.  By creating such a test program, you can be assured that if you change the program later (e.g. for more efficiency or to add additional features), you will be able to assure that the function still operates as intended and that no new unintended behavior (bugs!) have been introduced.

Sample run

  ./splitter foo:bar toes:10 Edward: nocolon two:colons:here :: : smoo

Input: foo:bar
Output:
        item: foo
        quantity: bar

Input: toes:10
Output:
        item: toes
        quantity: 10

Input: Edward:
Output:
        item: Edward

Input: nocolon
Output:
        item: nocolon

Input: two:colons:here
Output:
        item: two
        quantity: colons

Input: ::
Output:

Input: :
Output:

Input: smoo
Output:
        item: smoo


There's a number of things going on here, but the first thing that comes to mind is that you're placing an object on the heap that you simply discard (the entire class) for no apparent reason (speaking logically, not in terms of objects created).  Given that you don't appear to keep the object at all, this is unnecessary - do this all with static methods.  Additionally, this is not threadsafe, and the basic design cannot be adjusted to execute on multiple threads.  Furthermore, you're returning a Set<List<E>>, but your results are logically Set<Set<E>> (because you don't have repeats) - You probably ought to either adjust your results, or change your return results.

There's also a compile error in your code since you switched to the generics version, because of type inference (and this took me a while to figure out).

Most of the disconnect is occurring because of the odd blend of static and instance methods.  Additionally, you're attempting to use a builder pattern for something that doesn't really call for it - as near as the caller of your method knows, your SetPermutations class is never instantiated (which is false).  Also, you add object to permutationSet... and then almost immediately remove it.  Regardless of the performance implications of that, it's a terrible thing to do to a developer's mind.

Here's my (intial) take on the issue.  Note that this version is threadsafe (so long as T is an immutable object), and amenable to (easier) threading.  There are a few areas that could maybe be tweaked, especially as I'm creating a few more objects than I actually need (notably, my termination condition in permute), but this should be a better starting place.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public abstract class SetPermutations {

    private SetPermutations() {
        // no state.
    }

    public static <T> Set<Set<T>> getSetPermutations(final Collection<? extends Collection<T>> input) {
        if (input == null) {
            throw new IllegalArgumentException("Input not provided!");
        }
        final List<Set<T>> saved = new ArrayList<Set<T>>();
        for (Collection<T> c : input) {
            Set<T> s = new HashSet<T>(c);
            c.remove(null);
            if (c.size() >= 1) {
                saved.add(s);
            } else {
                throw new IllegalArgumentException("Input includes null/empty collection!");
            }
        }

        return permute(new HashSet<T>(), saved);
    }

    private static <T> Set<Set<T>> permute(final Set<T> initial, final List<Set<T>> itemSets) {

        if (itemSets.isEmpty()) {
            return Collections.singleton(initial);
        }

        final Set<T> items = itemSets.get(0);
        final List<Set<T>> remaining = itemSets.subList(1, itemSets.size());
      final int computedSetSize = initial.size() * items.size() * remaining.size();
        final Set<Set<T>> computed = new HashSet<Set<T>>(computedSetSize, 1);

        for (T item : items) {
            if (!initial.contains(item)) {
                Set<T> permutation = new HashSet<T>(initial);
                permutation.add(item);
                computed.addAll(permute(permutation, remaining));
            }
        }

        return computed;
    }

}

And here's the (revised) JUnit test to prove behaviour:

@Test
public void setPermutationsTest() {
    List<List<String>> data = new ArrayList<List<String>>();
    data.add(Arrays.asList("A", "B"));
    data.add(Arrays.asList("A","B","C","D"));
    data.add(Arrays.asList("D","E"));
    Set<Set<String>> expected = new HashSet<Set<String>>();
    expected.add(new HashSet<String>(Arrays.asList("A", "B", "D")));
    expected.add(new HashSet<String>(Arrays.asList("A", "B", "E")));
    expected.add(new HashSet<String>(Arrays.asList("A", "C", "D")));
    expected.add(new HashSet<String>(Arrays.asList("A", "C", "E")));
    expected.add(new HashSet<String>(Arrays.asList("A", "D", "E")));
    expected.add(new HashSet<String>(Arrays.asList("B", "C", "D")));
    expected.add(new HashSet<String>(Arrays.asList("B", "C", "E")));
    expected.add(new HashSet<String>(Arrays.asList("B", "D", "E")));
    Set<Set<String>> result = SetPermutations.<String>getSetPermutations(data);
    assertTrue(result.containsAll(expected));
    assertTrue(result.size() == expected.size());
}

(I removed "F" from the last collection, as it wasn't adding anything in terms of conditions - it fufilled the same function as "E").

EDIT:

The main reason why this is (more, and as much as can be reasonably coded for) threadsafe is the fact that you're not (completely) operating on a 'saved' copy:

You save off maxDepth before copying the 'exterior' collection.  If the size of that collection changes, maxDepth's value is now incorrect (results undefined).
You copy (and work from) the 'exterior' collection, but don't copy the 'interior' collections (The copy constructors might be deep for existing collections, but I doubt it, and won't be for custom collections).  This means that if any of the interior collections are modified during process run, you won't get correct results.

As for the static method instantiating a version of itself - there's no problem with that.  In fact, that generally forms the basis of a Factory Pattern.  The catch is that the instantiation is being returned - that is, the desired result is the instantiation.  Here, the only result is that you end up with a confusing use of instance variables.  The permutationSet methods end up being unwanted noise (It would have been better to explicitly just use the constructors), and are misleading to boot (you're returning a LIST).  Additionally, because of the use of the instance variables, it becomes non-trivial to reason about the state of the various collections.  NONE of the work done by instance methods benefits significantly from working on instance variables.  The only (theorhetical) benefit gained is that you work with a single copy of a result HashSet (because I define intermediate ones) - however, if it's an issue, the necessary collection should be passed in (as in a load() method.
Also, by permorming the instantiation as you have, you've completely eliminated any potential hope of threading the process (a potential concern, given that this is basically an O(n ^ m) process, where n is the number of collections, and m is the size of the collections, assuming roughly equal collection sizes).  With a thread pool and using futures, a non-instantiated version (or at least, not instantiated like this) can be threaded fairly trivially.


Sanitize Functions

First of all, note that your class does two very different things:

It checks if data is valid, returning either true or false (name, email).
It changes the data so that it is valid (sanitize).

Combining both of these functionalities in the same class can get confusing quickly.

construct

Why does the constructor do sanitation? You already have basicSanitize, shouldn't that be responsible? And where is the result actually checked?

basicSanitize

The name alone already suggests that this isn't a great function. It's so generic, this function could be doing anything.

Let's look at what it is doing (adapted from my answer here, as these kinds of functions are quite often combined, even though they shouldn't be):

trim: removes whitespace from beginning and end of string. This might be useful in some situations, and doesn't hurt in too many situations. It doesn't really affect security.
stripslashes: as the name suggests, it removes slashes. This is only useful if magic quotes is on (which is the functionality that adds slashes), so you should check that first, as otherwise you may corrupt your data. If magic quotes is on (it shouldn't be), using stripslashes is recommended, as otherwise you will have corrupted data.
htmlspecialchars again, this might corrupt your data (as in, you are not saving your original data in the database, but changed data). It is proper defense against XSS in most (but not all) situations (see here for exceptions, and use ENT_QUOTES), but it really should not happen before inserting data into the database, for two reasons: 1. corrupted data 2. This approach makes it easy to introduce XSS vulnerabilities. XSS is a vulnerability that is introduced when echoing data, so that is when it should be prevented. Otherwise, it will be hard to remember which data is secure and which is not.

To summarize: Your approach changes input data before it is inserted into the database, which could impact usability. This doesn't even add that much security, and is certainly not considered a best practice approach to security.

name

This functions doesn't really have anything to do with names. I'm glad that you are not too restrictive, but really, this is nothing more than a length check, so it might as well be called checkLength($data, $min, $max).

email

This is fine. FILTER_VALIDATE_EMAIL doesn't follow any email specs, but as it's PHPs inbuilt filter, it seems ok to use it.

Style / Coding Standards

I'm glad that you asked about this, as there are a couple of issues:

Your indentation is off, making your code difficult to read.
use curly brackets for all statements, even one-line statements.
Your spacing is off.
Your function level comments could be PHPDoc comments.

Use any IDE to fix most of these issues automatically.

Structure

Your class has state, but doesn't really need it, as your private fields are never used across functions. So they are just making your class unnecessarily complex.

You can just make your functions static. For example, your email function could just as well look like this:

public function email($data) {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
         return "Invalid email format";
    }
    return true;
}

And your name function:

public function name($data) {
    if(strlen($data) < 3) {
        return "Name too short.";
    } else if(strlen($data) > 100) {
        return "Name too big.";
    }
    return true;
}

API

Your class is very awkward to use. I imagine it works something like this:

$validate = new Validate($_GET); // this seems to make sense, but actually will not do anything
$validatedName = $validate->name($_GET['name']);
if (!$validatedName) {
    // handle $validatedName, which contains an error message
} else {
    // everything is fine
}

You'll notice that this doesn't actually work!

The reason for this is that strings as well as true evaluate to true with weak comparison. So instead, I'll need $validatedName !== true. And I will need to remember to use strict comparison each time, as I will otherwise have a - possibly quite serious - bug in my code.

The main problem is that you are sending error messages via the same mean as your return value, which just complicates things.

There are three different solutions that come to mind:

get rid of the error message and just return true or false. For many filters this will make perfect sense (if the email filter failed, it's because the input isn't an email, no need to explain).
store the error message in a field, which can later be accessed if needed.
throw an exception containing the error message on failure.


All exceptions in python should
inherit from an Exception class.
WindowsError only works on Windows, its better to use the more general OSError
You twice have a very long line to transliterate a string. Put it in a function and call it
You should put any code that is part of the script proper in a main function.
You shouldn't throw exceptions that you know won't be caught.
The way you collect errors by throwing them up the stack is ugly.
If you split the walking logic from the file operation logic the code will be clearer.

My updates (completely untested and probably wrong):

#!/usr/bin/python
# coding=utf-8

import os
import argparse
import shutil

class CommandError(Exception):
    """
    Thrown when the user has made a mistake in the command line
    """

def transliterated_walk(encoding, src, dst):
    """
    A generator which will walk over src producing them
    along with the transliterated versions in dst
    """
    files = []
    for filename in os.listdir(src):
        src_path = os.path.join(src, filename)
        dest_path = os.path.join(dest, transliterated(encoding, filename))

        if os.path.isdir(path):
            for entry in transliterated_walk(encoding, src_path, dest_path):
                yield entry
        else:
            files.append( (src_path, dest_path) )
    yield src, dest, files

def copytranstree (encoding, src, dst):
    errors = []

    for src_path, dest_path, filenames in transliterated_walk(encoding, src, dest):
        try:
           os.makedirs( dest_path )
        except WindowsError:
           pass

        for src_filename, dest_filename in filenames:
            try:
                shutil.copy2( src_filename, dst_filename )
            except (IOError, os.error) as why:
                errors.append( (src_filename, dest_filename, str(why) )

        try:
           shutil.copystat( src, dst )
        except OSError as why:
           errors.append( (src_path, dst_path, str(why) ) )

TRANSLIT = dict(zip(u"абвгдеёзийклмнопрстуфхьъ", "abvgdeeziyklmnoprstufh'~"))
TRANSLIT.update({u'ц': 'tz', u'ч': 'ch', u'ш': 'sh', u'ы': 'yi',
                u'э': 'ye', u'ю': 'ju', u'я': 'ja', u' ': '_'})

def transliterate(encoding, string):
    decoded = string.decode(encoding).lower()
    transliterated = ''.join(translit.get(x, x) for x in decoded)
    return transliterated.encode(encoding).lower()

def main():
    try:
        parser = argparse.ArgumentParser(description='Copy directory tree with transliterated pathnames')
        parser.add_argument('-e','--encoding', help='File system encoding', default='utf-8')
        parser.add_argument('-s','--src', help='Source folder name', default='./' )
        parser.add_argument('-d','--dst', help='Destination folder name', default='./')

        input_parametres = parser.parse_args()

        src = os.path.abspath( input_parametres.src )
        dst = os.path.abspath( input_parametres.dst )

        if not os.path.exists( dst ):
           dstname = transliterate(dst)
           os.makedirs( dstname )
           dst = os.path.abspath( dstname )

        if not os.path.exists( src ):
            raise CommandError('%s does not exist' % src)
        if os.path.isfile( dst ):
            raise CommandError('%s is a file' % dest)

        copytranstree( encoding, src, dst )
    except CommandError as error:
        print error

if __name__ == '__main__':
    main()


Find the majority element, which appears more than half the time

If it is known that a majority element exists, then the efficient algorithm to use is the Boyer-Moore majority vote algorithm, which requires only O(1) space.


Filtering numeric vectors by proximity to any elements of another vector in R

I do quite similar stuff.   I find your approach quite lengthy.  Especially the construction of the boolean matrix might be a bottleneck.

First I would consider to write a second function - say filter_by_mz_ which just does the filtering and have filter_by_mz just take care of the input and call the new function - just to keep things modular.

In your algorithm you basically compare all masses pairwise.  A simpler approach might be to use expand.grid(q=query_mzs, t=target_mzs) this will calculate all pairs.  This list can be then easy checked (let's call it gr) using abs(gr$t-gr$q) < ppm * gr$t - that would be fully vectorized.

A bool vector can usually be easy constructed using %in%.

Just FYI  I find it much easier to write with dplyr - especially since it is possible to keep much additional info in the table.  I often have the constraint that one mz can only be assigned once - extra data is often required to make such decisions.

Typically it looks like this:

Just the setup and some test data:

library(dplyr)

peaks <- data.frame(mz=c(21.01,28.00,30,30.1,35, 21.02), val=c(1,2,3,4,5,6))
info <- data.frame(mz=c(21.008, 28.003, 30.002, 32.02), str=c('wat', 'n2', 'aa' , 'bb'))

The magic happens here:

keyfun <- function(x) sprintf('%.1f',x)
peaks <- mutate(peaks, key=keyfun(mz))
info <- mutate(info, key=keyfun(mz))

inner_join(peaks, info, by='key') %>% filter( abs(mz.x - mz.y) < 0.0005 * mz.x)

Basically I create an temporary key that is too wide - just that I only get to work on combinations that could be.  The inner_join will create all the permutations.  And in a second step I filter out the ones that actually match.

Of course usually I give more informative names and spend some time labelling stuff.  But this should suffice to give an idea of the method.

addition

It came to me that you could avoid the matrix if you could rewrite such that inside the loop you check for all query_mz instead of target_mz - then you could also put the any inside the loop.  I suppose it would come down to just switching the variable names in a number of lines.
After this transformation the for loop should be replacable by an sapply.

As R stores logicals quite expensive with 4 bytes per logical. That shoud give you extensive savings. (For me these numbers would go into the 100s so I would have >99% less memory usage)


Making complex array initializations more readable

First, magic constants are bad, you should name them

int const N = 53;
double result[N];

Second, magic patterns are even worse, you should also name them along with documentation comments

// explain where the pattern comes from
int const pattern[] = { 13, 21, 12, 25, /* 49 more constants */ };

Third, manually loop unrolling can sometimes help, but only after you benchmarked

for (int i = 0; i < N; ++i) {
    result[i] = ((var1[pattern[i]] * (i+1)) + (var2[7] * (i+2))) / var3[i];
}

For your second part, rinse and repeat:

double var1_new[N];

Fourth, use the Standard Library for standardized algorithms

#include <algorithm>
std::copy_n(var1, N, var1_new);

Again, rinse and repeat the loop unrolling

for (int i = 0; i < N; ++i) {
    var1_new[pattern[i]] += result[i];
}

Finally, you might want to give your variables meaningful names: var1, var2, var3 do not explain their intended use very well. Think about what they mean in your application (it was unclear from the code fragment alone).


Your code is well structured and quite easy to read and understand: this is a very good point about it.

However, there are some things that may be improved, but very few of them seem to be really critical.

main(arg)

Variables int x, int y and int n are treated separately, but indeed they are semantically related, because they describe a "FizzBuzz" to produce. A dedicated class may be created, for example:

public class FizzBuzz {

  private final int x;
  private final int y;
  private final int n;

  public FizzBuzz(int x, int y, int n) {
    this.x = x;
    this.y = y;
    this.n = n;
  }
  // getters, if needed
}

Moreover, your fizzBuzz method may then go directly into this class, named something like processInput(). The loop in main() would look like this:

for (String line : lines) {
  int[] arguments = getFizzBuzzArguments(line);
  FizzBuzz fb = new FizzBuzz(arguments[0], arguments[1], arguments[2]);
  sb.append(fb.processInput()).append('\n');
}

FizzBuzz may also have a constructor taking directly the array of input data as argument.

fizzBuzz(args)

Three points concerning the modulo divisions and the booleans isX and isY.

First, the divisors (x or y) must be validated to be different from 0, if you want to avoid ArithmeticException .

Second, they should be extracted into a dedicated method, which is easier to read:

private static boolean isMultipleOf(int dividend, int divisor) {
  return dividend % divisor == 0;
}

Third, the booleans are named poorly. They'd better sound as isFizz and isBuzz: these are their meanings.

Finally, the conditionals can be simplified:

if (isFizz || isBuzz) {
  if (isFizz) {
    sb.append("F");
  }
  if (isBuzz) {
    sb.append("B");
  }
} else {
  sb.append(i);
}

getFileLines()

Since you underline that the code in Java 7, then its facilities should be used.

Replace File with java.nio.file.Path.
Use a try-with-resources block in order to close automatically the streams opened with BufferedReader and FileReader.


Extracting min and max salary from string

The , commas are a nice twist.
I feel you are stripping them a bit late,
as they don't really contribute to the desired solution.
Better to lose them from the get go.
Calling .findall seems to be overkill for your problem specification --
likely .search would suffice.

salary_text = re.findall("[\$0-9,\. ]*-[\$0-9,\. ]*", input1)

The dollar signs, similarly, do not contribute to the solution,
your regex could probably just ignore them if your inputs are fairly sane.
Or even scan for lines starting with $ dollar, and then the regex ignores them.

range_list = re.split("-", salary_text[0])

There is no need for this .split -- the regex could have done this for you already.
Here is what I recommend:
def find_range(text):
    if text.startswith('$'):
        m = re.search(r'([\d\.]+) *- *\$?([\d\.]+)', text.replace(",", ""))
        if m:
            lo, hi = m.groups()
            return float(lo), float(hi)
    return None, None

print(find_range('$80,000 - $90,000 per annum'))
print(find_range('$20 - $24.99 per hour'))

The raw string regex r'[\d\.]+' picks out one or more numeric characters,
which can include decimal point.
And putting ( ) parens around a regex makes it a capturing group --
we have two such groups here.
Finally,  *- *\$? lets us skip a single - dash with optional whitespace
and at most one optional $ dollar sign.


The time complexity is \$O(\text{listLength} * \text{numberOfLists}^2)\$ because the check of which node is the smallest? is looking at one element of each list every iteration (so each iteration's complexity is \$O(\text{numberOfLists})\$, and there are \$\text{listLength} * \text{numberOfLists}\$ iterations.

You can get to \$O(\text{listLength} * \text{numberOfLists} * \log(\text{numberOfLists}))\$ by using a sorted list of the ListNode elements that you are checking in each iteration, instead of the unsorted array listNodes. Let's call this list sortedNodes. You can avoid checking each element of sortedNodes every iteration because you know the first one is the smallest, and once you take this first value into the merged list and advance the node - do a binary search to decide where to move the first element after its value has changed. (Or remove it if it got to a null.)


Combining two 32-bit integers into one 64-bit integer

You should return unsigned long long and let the user decide what they want to do with the cast, especially if you want this to be generic.

I'd prefer a name such as u32tou64, uinttoull, or something more descriptive than combine.  A lot of this will depend on your own naming standards, though.

Also, I'd consider being more pedantic:

return (((uint64_t) high) << 32) | ((uint64_t) low);

It's unlikely to make a difference because the code is essentially the same as yours, but it's easier to read and avoids extremely rare (but very troublesome to debug) casting issues.  It may require a custom types header if your compiler doesn't support this type notation.

Also, consider making it a macro.  There's little benefit to having it as a function - the operation itself will take far less time than the function call setup, call, and return, so the performance of a macro will be much higher.  Further, it isn't going to take up much more program space than a function call, so there's little to gain by leaving it a real function.


I am not going to review the actual algorithm. However, there are some improvements possible:

1

static int[] value;
static int[] weight;
static float[] ratio;
static int knapSackWeight;

You expose the state of your algorithm to entire package. Also, your implementation is not thread-safe: if two threads call the getMaximumBenefit more or less simultaneously, they might interfere.
One way to circumvent this issue is to make sure that getMaximumBenefit  constructs an object holding the state of computation and manipulate only that object throughout the computation.

2

getMaximumBenefit should be declared public. Otherwise no-one
will be able to call it outside of your (default) package.

3

Since getMaxRatioItem is a helper routine, it would be nice to declare it private.

4

int ratioIndex = -1;

What is the purpose of the value -1? It would be nice to declare a constant:

private static final int NO_ITEMS_LEFT = -1;

and then write

int ratioIndex = NO_ITEMS_LEFT;
...
if (item == NO_ITEMS_LEFT) {
    return benefit;
}

A nice point here is that if you need for some reason to change the value of that constant, you will have to edit its definition only in one place. The rule here is not to hardcode magic values, but make named constants out of them.

5

System.out.println(ratio[i]);

Printing within an algorithm is a bad taste (unless debugging). Think about how much output you get in production whenever computing a large problem instance.

6

getMaximumBenefit should return some simple data structure representing the result, not just print it on standard output.

Summa summarum

All in all, I had this in mind:

import java.util.Objects;
import java.util.Scanner;

public class FractionalKnapsackSolver {

    private static final int MINIMUM_CAPACITY = 1;
    private static final int NO_ITEMS_LEFT = -1;

    private final int[] values;
    private final int[] weights;
    private final float[] ratios;
    private final int knapsackCapacity;

    private FractionalKnapsackSolver(final int[] values,
                                     final int[] weights,
                                     final float[] ratios,
                                     final int knapsackCapacity) {
        this.knapsackCapacity = checkCapacity(knapsackCapacity);
        this.values = Objects.requireNonNull(values,
                                             "The value array is null.");
        this.weights = Objects.requireNonNull(weights,
                                              "The weight array is null.");
        this.ratios = Objects.requireNonNull(ratios,
                                             "The ratio array is null.");
        checkWeightArrayLength();
        checkRatioArrayLength();
    }

    private int checkCapacity(final int capacity) {
        if (capacity < MINIMUM_CAPACITY) {
            throw new IllegalArgumentException(
                    "Nonpositive capacity given: " + capacity + "." +
                    "Must be at least " + MINIMUM_CAPACITY + ".");
        }

        return capacity;
    }

    private void checkWeightArrayLength() {
        if (weights.length != values.length) {
            throw new IllegalArgumentException(
                    "The length of the weight array (" + weights.length +
                    ") does not match the length of the value array (" +
                    values.length + ").");
        }
    }

    private void checkRatioArrayLength() {
        if (ratios.length != values.length) {
            throw new IllegalArgumentException(
                    "The length of the ratio array (" + ratios.length +
                    ") does not match the length of the value array (" +
                    values.length + ").");
        }
    }

    public static float computeBenefit(final int[] values,
                                       final int[] weights,
                                       final float[] ratios,
                                       final int knapsackCapacity) {
        final FractionalKnapsackSolver solver =
                new FractionalKnapsackSolver(values,
                                             weights,
                                             ratios,
                                             knapsackCapacity);

        return solver.compute();
    }

    private int getMaximumRatioItem() {
        float maximumRatio = 0.0f;
        int maximumRatioIndex = NO_ITEMS_LEFT;

        for (int i = 0; i < ratios.length; ++i) {
            if (maximumRatio < ratios[i]) {
                maximumRatio = ratios[i];
                maximumRatioIndex = i;
            }
        }

        return maximumRatioIndex;
    }

    private float compute() {
        int currentWeight = 0;
        float benefit = 0.0f;

        while (currentWeight < knapsackCapacity) {
            final int item = getMaximumRatioItem();

            if (item == NO_ITEMS_LEFT) {
                return benefit;
            }

            for (int i = 0; i < weights[item]; ++i) {
                if (currentWeight + ratios[item] <= knapsackCapacity) {
                    currentWeight++;
                    benefit += ratios[item];
                }
            }

            ratios[item] = 0;
        }

        return benefit;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        final int n = in.nextInt();
        final int[] values = new int[n];
        final int[] weights = new int[n];
        final float[] ratios = new float[n];

        for (int i = 0; i < n; ++i) {
            weights[i] = in.nextInt();
            values[i] = in.nextInt();
            ratios[i] = (float)(values[i]) / weights[i];
        }

        final int knapsackCapacity = in.nextInt();

        System.out.println(computeBenefit(values,
                                          weights,
                                          ratios,
                                          knapsackCapacity));
    }
}

Hope that helps.


Medical database design and queries optimization

The Symptom and Disease tables are well-conceived.
Their purpose is clear, and they are about specific thing each.

The Combination table on the other hand stinks.
Combination of what?
It seems your goal with this table is to represent:

One record per case, maybe?
Age, gender, body part, weight, disease, main symptom of the case
Additional symptoms

Instead of putting the addition symptoms as a concatenated list of values,
it would be better to create another table with:

foreign key on case id, and symptom id
unique constraint on case id + symptom id

Also,
the prefixing of column names with s_ for symptom and d_ for disease is not great. It would be better to drop these prefixes.
You can use table aliases s and d instead, for example:

SELECT DISTINCT s.id, s.name, s.common FROM symptom s, combination c
WHERE c.age = '$age' AND c.gender = '$gender' AND c.bp_id = '$bodypart' AND c.s_id = s.id


Arabic numbers to Roman numerals conversion

Similar to dankohn's comment, there are really only a handful of operations going on, just with different character sets.

Here is my quick implementation.  It only handles the base 10 digits, and dynamically swaps out character sets depending on the power of the number.

def to_roman(digits)
    numeral_sets = {  1=>['I', 'V', 'X'],
                     10=>['X', 'L', 'C'],
                    100=>['C', 'D', 'M'],
                   1000=>['M', "\u2181", "\u2182"] }

    str = ''
    digits.reverse.each.with_index do |d, ix|
        set = numeral_sets[10**ix]
        case d
            when 0 then roman = ''
            when 1..3 then roman = set[0] * d
            when 4 then roman = "%s%s" % [set[0], set[1]]
            when 5 then roman = set[1]
            when 6..8 then roman = "%s%s" % [set[1], set[0] * (d-5)]
            when 9 then roman = "%s%s" % [set[0], set[2]]
        end
        str = str.insert(0, roman)
    end
    str
end

And a few tests:

puts to_roman [1,9,9,7] # expected MCMXCVII
puts to_roman [1,9,0,7] # expected MCMVII
puts to_roman [5,6,7,8] # expected ↁDCLXXVIII


Exponential growth calculator for COVID-19

Your formula was assuming 14,000 cases a day, rather than 14,000 cases a month.  I removed all rounding, choosing to round for display only.

Here's a partial result of the last test run I did.  I formatted the output manually to fit in the answer.

Let us see the Exponential growth of Covid-19.
We will set the initial value of Covid as
88,000 as that was the amount of cases in
February.

We need to find the growth rate of Covid-19,
we can use the growthRate method.
We'll assume a linear growth rate of 14,000
cases a month.

Using the growthRate method, we worked out
the growth rate is 0.005303.

The time interval will be from February 1,
2020 - April 16, 2020, 45 days.
Now we have all the values let us use the
method calculateExpoGrowth

The Exponential growth of Covid 19 is
111,647 cases by April 16, 2020.

I cleaned up the code a lot.  Here it is.

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Covid19ExpoGrowth {
    public static void main(String[] args) {
        try {
            calculateGrowth();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println();
        System.out.println("You can now work out your "
                + "own Exponential Growth");

        // User works out chosen exponential growth
        Scanner scan = new Scanner(System.in);
        while (getUserInput(scan));
        scan.close();
    }

    private static void calculateGrowth() throws IOException {
        // I will use the formula y = a(1 + r)^x
        // a = initial value
        // r = growth rate
        // x = time interval
        int a;
        double r;
        int x;

        // Workout exponential growth
        System.out.println("Let us see the Exponential "
                + "growth of Covid-19.");
        System.out.println(
                "We will set the initial value of Covid "
                + "as 88,000 as that was the amount of "
                + "cases in February.");
        System.out.println();
        a = 88_000;
        System.out.println("We need to find the growth "
                + "rate of Covid-19, we can use the "
                + "growthRate method.");
        System.out.println("We'll assume a linear growth rate "
                + "of 14,000 cases a month.");
        System.out.println();
        r = growthRate(a, 14_000d + a) / 30d;
        String output = String.format("%.6f", r);
        System.out.println("Using the growthRate method, "
                        + "we worked out the growth "
                        + "rate is: " + output + ".");
        System.out.println();
        System.out.println("The time interval will be "
                + "from February 1, 2020 - April 16, 2020,"
                + " 45 days.");
        x = 45;
        System.out.println("Now we have all the values "
                + "let us use the method calculateExpoGrowth");
        System.out.println();
        double roundedExpo = calculateExpoGrowth(a, r, x);
        DecimalFormat formatter = new DecimalFormat(
                "###,###,###");
        output = formatter.format(roundedExpo);
        System.out.println("The Exponential growth of "
                + "Covid 19 is " + output
                + " cases by April 16, 2020.");
    }

    private static boolean getUserInput(Scanner scan) {
        int a;
        double r;
        int x;

        System.out.println("Please enter the initial value");
        String value = scan.nextLine().trim();
        if (value.isEmpty()) {
            return false;
        }

        a = Integer.valueOf(value);

        System.out.println("Enter WORKOUT GROWTH RATE if you "
                + "would like to workout the growth rate,"
                + "if you already know it press enter");
        String gr = scan.nextLine().trim();
        if (gr.equalsIgnoreCase("WORKOUT GROWTH RATE")) {
            int pastValue;
            int presentValue;

            System.out.println("Please enter the past value");
            pastValue = Integer.valueOf(scan.nextLine().trim());

            System.out.println("Please enter the present value");
            presentValue = Integer.valueOf(scan.nextLine().trim());

            System.out.println("Please enter the days");
            int days = Integer.valueOf(scan.nextLine().trim());

            r = growthRate(pastValue, presentValue) / days;
        } else {
            System.out.println("Please type in the growth rate");
            r = Double.valueOf(scan.nextLine().trim());
        }
        System.out.println("Now finally, type in the time "
                + "interval");
        x = Integer.valueOf(scan.nextLine().trim());
        double roundedExpo2 = calculateExpoGrowth(a, r, x);
        DecimalFormat formatter = new DecimalFormat(
                "###,###,###");
        String output = formatter.format(roundedExpo2);
        System.out.println(
                "The program has calculated the Exponential "
                + "growth is: " + output + ".");
        return true;
    }

    public static double growthRate(double pastVal,
            double presentVal) {
        double newVal = presentVal - pastVal;
        return newVal / pastVal;
    }

    public static double calculateExpoGrowth(int a, double r,
            int x) {
        // Exponential growth formula
        return (a * Math.pow((1d + r), (double) x));
    }
}


I think you're being too lenient with your input checking, which results in some unexpected results:

-3,000,0    results in:     -3000/1
3,000      results in: 3/1
3 results in 3/1
3-1 results in 1/1

Personally, I'd pick an expected format and then ensure that the input complies with it.  If you want to support multiple decimal marks, then I would suggest having a function for each supported format that validates the input and returns it in one common format which is then used by the rest of the code.
argc & argv
In your example you have ./a.out "3 000,375".  You're quoting the space in order to ensure it's all pushed as part of argv[1].  It seems likely that this could be forgotten.  If it was, then you would end up with the output of 3/1.  Your argc checking only checks for no parameters being supplied:
if (argc < 2) {
    fprintf(stderr, "Please enter a number to fractionize.\n");
    return EXIT_FAILURE;
}

Unless you're going to continue through the arguments supplied, appending them to the input it would be better to do something like this:
if (argc != 2) {
    fprintf(stderr, "Usage: %s <number to fractionize>\n", argv[0]);
    return EXIT_FAILURE;
}

One declaration per line
This is obviously subjective, but I don't particularly like multiple declarations on a single line.  I don't mind it so much when you're declaring several uninitialised variables, however when you're assigning values to the variables it would be better to have each declaration on a new line.  For me, denominator and previous get a bit lost on this line:
unsigned long long previous, denominator = 1, numerator = 0;


Improve this image file browser (remove redundancy)?

First of all, Java code doesn't really make sense outside of the context of a class and a method. Sometimes you can get away without the class, but the method signature is definitely important. In this case, you've included references to variables without a type: are these arguments to a method? Members of a class?

Second, your description of what this code does has too many ands in it. Code should be organized in terms of abstractions. For instance, if you describe something this way, it's a bit confusing as to what it actually does: "It lets you write arrays of bytes to a magnetic medium and causes the read heads to seek to a particular place on the disk and also it lets you refer to a group of bytes by a name, etc, etc." Instead you might start from the bottom: "Files are sequences of bytes intended for long-term storage; they support the following operations: append, truncate, etc. Files are organized into a directory structure by a filesystem, which is built on top of a storage device, etc." This description divides the details into various levels of abstraction.

I'll give a new listing and afterward describe why I made the changes I did.

class Card {
    private final ImageIcon frontImage;
    private final ImageIcon backImage;

    public Card(ImageIcon frontImage, ImageIcon backImage) {
        this.frontImage = frontImage;
        this.backImage = backImage;
    }
    // Probably more goes on here
}

class Deck {
    private static final String DEFAULT_SUBDIRECTORY = "default";
    private final String baseDir;
    private final ImageIcon cardBackImage;

    private List<File> loadSubdirectory(String subdir) {
        List<File> files = new ArrayList<File>();
        File[] listing = new File(baseDir, subdir).listFiles();
        for (int i = 0; i < listing.length; i++) {
            if (listing[i].isFile()) {
                files.add(listing[i]);
            }
        }
        return files;
    }

    public List<Card> selectCardsFromDirectory(int numCards, ComboBox cboImages) {
        return selectCardsFromDirectory(numCards, cboImages.getSelectedItem().toString());
    }

    /** Selects numCards at random from the user's directory,
        filling in from the default directory if the user has
        too few */
    public List<Card> selectCardsFromDirectory(int numCards, String userDirectory) {
        List<File> userFiles = loadSubdirectory(userDirectory);
        List<File> defaultFiles = loadSubdirectory(DEFAULT_SUBDIRECTORY);

        Collections.shuffle(userFiles);
        Collections.shuffle(defaultFiles);

        List<Card> cards = new ArrayList<Card>();
        for (int i = 0; i < numCards; i++) {
            ImageIcon frontImage;
            if (i < userFiles.size()) {
                frontImage = loadScaledImage(userFiles.get(i));
            } else {
                frontImage = loadScaledImage(defaultFiles.get(i - userFiles.size()));
            }
            cards.add(new Card(frontImage, cardBackImage));
        }
        return cards;
    }

    private ImageIcon loadScaledImage(File file) {
        Image image = new ImageIcon(file.getPath()).getImage();
        return new ImageIcon(
            image.getScaledInstance(IMAGE_WIDTH, IMAGE_HEIGHT, Image.SCALE_SMOOTH));
    }
}

This is a quick and dirty refactoring and I haven't compiled it to check that it all builds, but it should give you the idea. In particular, the code is not presented in any reasonable order.

It appears that you had a bug in the code; you use fileCounter to determine how many normal files are in a directory, and only take fileCounter files from the user directory, but you don't skip past directories, etc. I've modified the logic.

This Deck class knows about too many things. Why does it know about the disk layout? Why does it know about elements of the GUI (ie cboImages)? Try reading up on MVP or MVC design for ideas of how to restructure your code to have better encapsulation. Some thoughts:

Separate the shuffling logic out of the class that deals with the file system; that should be as simple as moving loadSubdirectory into a new class.
Remove the overload of selectFilesFromDirectory that takes a ComboBox; the GUI should extract the String before calling into this class.

I've pulled out some helper functions. These do two things: reduce code duplication, and improve abstraction. As a good rule of thumb, most methods shouldn't exceed 25 lines. By pulling out the file-loading logic, I've made it so you don't need to think about how exactly the files are loaded when you're reading selectFilesFromDirectory.

Card has some problems as a class. It is odd that you are default-constructing it, and then constructing it more afterward. I've redesigned part of it.

ctr is not a very good name for a generic loop counter. Most programmers use i, j, and other one-letter names for short loops, or actually descriptive names. For this reason, when reading the code, my brain tries to figure out what ctr means. I'm lucky; English is my first language -- for some people who don't have English as their first language, unusual abbreviations of English words are difficult to decipher.


What happens if one of your slides is itself a block that contains an image, such as an article. Consider this markup:

They seem fine on their own and for six months they might be, but it's perfectly reasonable for the
 block to be nested in the
 slide show block, at which point any styles defined on .slide-show .image will effect the article's images too.

By building up modules using BEM and sticking to the naming conventions you guarantee unique classes that won't clash regardless of the order or hierarchy. You know the styles won't leak or be leaked on and you know that you can move the block anywhere in the hierarchy without leakage.