Apply same format function to each python print() parameter

Time will tell if your question is considered a worthy Code Review question, but till then I'ld like you to give a short review on your code nevertheless.

Format function

You could reduce the code duplication in the format function and make use of .format or f-strings (from Python 3.6 onwards).

def sizeof_fmt_rev(num, suffix='B'):
    for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
        if abs(num) < 1024.0:
            break
        num /= 1024.0
    else:
        # this part is only executed if the loop was not left with a break
        unit = 'Yi'
    return f"{num:.1f}{unit}{suffix}"

This uses for ... else, one of the less well-known features of Python and only has a single line where the format expression has to be written. I see a chance to build something using math.log instead of that loop, but I will leave that as an exercise to you. You can even build something that works without a loop, but at least the version I came up with (found below) is actually slower than the original implementation.

def sizeof_fmt_rev_log(num, suffix='B'):
    exponent = min(int(math.log(abs(num), 1024)), 8)
    num /= 1024**exponent
    unit = ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi')[exponent]
    return f"{num:.1f}{unit}{suffix}"

I used

for i in range(10):
    num = 3.8 * 1024**i
    print(sizeof_fmt_rev(num))
    assert sizeof_fmt(num) == sizeof_fmt_rev(num)
    assert sizeof_fmt(-num) == sizeof_fmt_rev(-num)

to test the revised version.

Code

As @AJNeufeld mentions in his comment, you could use map to save yourself some typing

print(
    statement.format(*map(sizeof_fmt, (input_file_size, chunk_size, block_size, surrendered_space)))
)

which is functionally equivalent to using a list comprehension:

print(
    statement.format(*[
        sizeof_fmt(i)
        for i in (input_file_size, chunk_size, block_size, surrendered_space)
    ])
)

Both build upon a technique called tuple unpacking, but as you can see it can also be used with lists, other sequences, and maybe also iterables (if it is a generator, it will be consumed - thanks @Graipher, who confirmed it/pointed it out in a comment).


1. Python strings have an .endswith() method. Use it.
While string[-3:] == 'ing' isn't particular hard to read, string.endswith('ing') is even clearer.
Potentially, depending on how it's implemented, .endswith() could even be slightly more efficient, since it doesn't have to copy the last three characters of the string.  However, always keep Knuth's maxim in mind.  The entire operation of testing whether a string ends with "ing" is so trivial that any performance difference between different ways of doing it will surely be negligible compared to e.g. the time consumed by reading and printing the string.  Thus, given two ways to do it, you should choose the most readable and idiomatic way even if it wasn't the most efficient.
2. Separate I/O from computation.
It's common for beginning programmers to litter their code with input() and print() calls in the middle of program logic, simply because those are the only ways of receiving and returning data they're familiar with.  But in practice, that's almost always a mistake.(*)
Your main task is to modify a string.  Reading the string from standard input and printing the result to standard output are merely auxiliary tasks to that (and may or may not even be strictly necessary, unless the exercise explicitly specifies that particular method of input and output).  You shouldn't unnecessarily intermix those auxiliary tasks into your solution for the main task.
The simplest way to do that would be to just pull the print() calls out of the program logic, e.g. like this:
string = input()

if string.endswith('ing'):
  string += 'ly'
elif len(string) >= 3:
  string += 'ing'

print(string)

This is OK if you expect to only ever use this code for processing data read from one file (or pipe) and written to another.  You're still doing the input, processing and output in one linear program, but at least the processing logic is now grouped together in a single block of code that you can extract from the script if you want to reuse it, and the I/O code is clearly separated from it, making it easy to change to another I/O method later if you need to.
Alternatively, you could go a step further and wrap the program logic in a function that takes the input string as a parameter and returns the output.  And, while you're at it, you can use the if __name__ == '__main__' idiom to make your I/O code only run when your script is invoked directly:
def inglify(string):
  if len(string) < 3:
    return string
  elif string.endswith('ing'):
    return string + 'ly'
  else:
    return string + 'ing'

if __name__ == '__main__':
  string = input()
  print(inglify(string))

The advantage is that now your script file is also usable as a module that you can import into another script to gain access to any functions defined in it without executing the I/O part of the code.

*) So, when is it appropriate to include print() calls directly in your code, then?  Off the top of my head, I can think of three or four cases (with some partial overlap between them):

When I/O is the main purpose of your code, with everything not directly relevant to this purpose already split off into reusable functions.  For example, print(inglify(input())) really does nothing but read data, call a function and print the result.  Obviously, using print() there is not only appropriate but necessary.

When your code is interactive, i.e. when it prints something to the console, expects the user to reply, then prints something in response, etc.  The REPL that you can start by running python with no script file argument is one example of such a program.  In this case the input and output are intrinsically part of your program logic and cannot be easily separated from it.  That said, you should still try to keep such interactive loops as simple as possible, and split off any parts of your code that don't directly involve interactive I/O into reusable functions or modules.

When you're doing debug printing, i.e. when what you're printing isn't the actual intended output of your program, but merely some metadata to help in tracing its execution.  This can sometimes be a very useful ways to find out what your code is actually doing, and it's the one case where putting print() or other I/O calls even deep inside your program logic can be acceptable.  Of course, if you're leaving such debug logging in your finished code, you should probably only enable it if requested by the user.  (For example, many command-line tools will accept a --verbose or --debug switch to turn on such extra output.)  Often it's best to use an actual logging framework designed for this purpose.

I would also personally include an exception for "simple data processing" scripts that involve nothing more than reading in some data, processing it and printing it out, much like the first rewritten version of your code that I suggested above.
Such scripts are characterized by the fact that they only perform a single task, that this task involves reading, processing and writing data, and that their control flow is simple and mostly linear.  That is, such a script might consist of a loop that reads the input, another loop or two to process it, and then a loop to print out the results.  Sometimes it might even have a loop that e.g. reads a line of input, processes it, and prints out the result before reading the next line, etc.  But what it definitely shouldn't have is print (or, worse yet, input) calls buried deep within conditional code, or in functions whose main purpose isn't obviously to perform I/O.
While such scripts can be refactored to separate the I/O code from the rest of the data processing, often that can actually make the code harder to read, since it breaks up the simple step-by-step program flow into a more complex sequence of function calls.  Basically, if your code is naturally structured like a cooking recipe, with nothing but simple sequential steps, it's sometimes better to just keep it like that and not complicate it by needless refactoring.


Code which pulls from SQL and dumps in Excel

First of all let me make an important comment not related to performance:

Security issues

I hope your table is only accessible by by a limited number of trusted people. I say this because building a SQL string like this, without further verification, is generally a bad idea. Just do a short online search for SQL injection attack to understand what I mean. Or see bobby-tables.com for a quick reference.

Performance

Now, regarding the performance. The general problem seems to be that you are querying the database for each row separately. That is usually not how you should work with a database. You can pull in larger result sets using an ADODB.Recordset or other means. Unfortunately, we cannot really see how you pull in the data since you do not provide information about mydata. In particular, we do not know what sqlVal is as you declared it (implicitly) as variant. Accordingly, I can only say something on general terms.

If the table in the database you are pulling the data from is not too large, you could probably pull in all data and filter in memory, which is faster.

If the database table is indeed very large, which I presume, you might want to dynamically generate a filtering condition based on the FIGI and dates, which I assume to be able to differ, in your table. (If the dates are always the same, this would allow a simplification.) The goal is to pull all relevant data in one go.

How to do this best really depends on the database you are talking to. If it supports CTEs (common table expressions) and has syntax to create tables on hard-coded values, it is probably best to generate such a table out of your FIGI/date pairs and do a join to build up the condition. Otherwise, you can just use a generated OR (FIGI = xxx AND PriceDate < yyy) chain in the WHERE clause. However, based on your probaly 1917 hard-coded rows, the performance might not be too good. Either filter would be applied in the subquery which would require a new GROUP BY clause on the FIGI. Then, you just join the result to the table, to get your desired values.

If your database provider supports aggregate window functions you can do the filtering on the max PriceDate using those. Then, no subquery and only an IN condition on the FIGI is required.

Without knowing more about the database you talk to, I cannot say any more regarding the query structure, since basically all databases use different SQL dialects.

That said, I wonder why you do not just use an actual database tool, e.g. Access, to query the main database and then just dump the result into the Excel file. (You can insert entire ADODB.Recordsets and you can read in data from an Excel sheet using SQL via ADO, as well.)

General Remarks

Since this is Code Review, I will also provide some thoughts about your code.

First of all, the readability really suffers from the superfluous vertical whitespace, which has been noted in a comment already, and the partial lack of indentation. To fix the indentation, you might want to visit the online VBA indenter. (Full disclosure - I am involved in the project this website belongs to.)

Second, the three executable lines in front of the For loop, do not do anything since the values are overwritten immediately in the loop, which has hard-coded bounds.

Instead of hardcoding the bounds as magic numbers, you might want to consider introducing a constant with a meaningful name.

Another thing I noticed is that you do not exit the the procedure before running into the error handler, i.e.: the error handler gets executed every time you execute the procedure. You should put an Exit Sub in front of it.

Now, a few nit-picky things:

The Call statement you use at the top, is deprecated. It would be more idiomatic to not use it.
You should always specify the accessibility of a procedure. If you really want it to be public, you should state that.
Declaring a variable As New is not the same as declaring it and then setting it to a new instance. If you declare a variable As New it will only be instantiated the first time it is used and it will be re-instantiated on the next use after setting it to Nothing. Since the execution engine has to check each time whether the object still exists, there is an overhead involved.
The use of Integer in favour of Long is largely useless. Internally, the Integer is saved as a Long. See this SO answer.
It is generally better practice to declare variables as close to first usage as possible, contrary to what Microsoft previously suggested. (They have reverted their stand on this in more recent style guides.)
You could separate the different concerns in this sub a bit more into separate subs and functions, following the single responsibility principle, although, admittedly, the sub already does not do all too many things.


Here's my notes

First don't use #map and use #pluck instead (for database calls), all over your code.

bad:

@membership.user.accounts.map(&:id)

better:

@membership.user.accounts.pluck(:id)

Use eager loading, to reduce queries

Bad:

Membership.find(member_id)

Better:

Membership.includes(user: :accounts).find(member_id)

Because you are using users and accounts in the loops after.
This whole block could be reduced to a single statement

if user_edit_params
  cloned_user.email = invite_email
  cloned_user.permissions = user_edit_params[:permissions]
  cloned_user.accounts = Account.find(invite_app_access.map(&:to_i))
  cloned_user.level = user_edit_params[:user_level]
end

To

if user_edit_params
  cloned_user.assign_attributes(
    email: invite_email
    permissions: user_edit_params[:permissions]
    accounts: Account.find(invite_app_access.map(&:to_i))
    level: user_edit_params[:user_level]
  )
end

No idea what this does

@membership.user.attributes.slice('permissions')

but wouldn't this do the same ?

@membership.user.permissions

Law of Demeter
And basically just group common stuff into single methods and call the methods inside this method, isntead of having one huge method like this


Rolling loop with an array of data points

range returns a list.  You could use xrange instead.

range([start,] stop[, step]) -> list of integers

  Return a list containing an arithmetic progression of integers.

vs

xrange([start,] stop[, step]) -> xrange object

  Like range(), but instead of returning a list, returns an object that
  generates the numbers in the range on demand.  For looping, this is
  slightly faster than range() and more memory efficient.

The other thing that strikes me is the slice in the argument to np.mean.  The slice is always of length 3.  Assuming this is an arithmetic mean, you could turn the division into

(3.0 * data[i] / (data[i - 2] + data[i - 1] + data[i]))

So putting it together

def fcn(data):
    return [(3.0 * data[i] / (data[i - 2] + data[i - 1] + data[i])) - 1
            for i in xrange(len(data) - 1, len(data) - 362, -1)]

and you could further optimize the sum of last three values by recognizing that if

x = a[n] + a[n+1] + a[n+2]

and you have already computed

y = a[n - 1] + a[n] + a[n + 1]

then

x = y + (a[n - 1] - a[n + 2])

which helps whenever a local variable access and assignment is faster than accessing an element in a series.


React modal visibility and content toggling based on action clicked

I've kept the Modal Component light opting to pass the events back to the App Component

I believe this is the correct way to make components generic.

&nbsp;

OMG! Use margins instead. :P

I also notice you use the BEM naming scheme to specifically target styles to the component and not wreak havoc globally. To me, this is a big plus.

I notice that you either add or remove the modal depending on modalVisible. Since you're adding and removing the element from the DOM, the modal will pop in and out of existence and you have no room for transition effects. I think you should just leave the modal on the DOM rendered, but initially hidden. Then use modalVisible to toggle the presence of the modal--is-open modifier.

I also would discourage peppering your code with console function calls. It's debugging code, not for production and leaving it there is bad practice. Use breakpoints in the browser's debugger to inspect code.

One trick to still do console.log without ever putting them in your code is to use a conditional breakpoint but with the console.log call as the expression. When the breakpoint is hit, it is evaluated, console.log gets called. But since console.log returns undefined, which is falsy, the breakpoint won't pause.

The Right Way™ to do React apps is for your components to not to hold state... at all. State should be in stores. In your case, you just made your top-level component the holder of state, which is fine for small apps. Should it grow, consider using stores. I heard Redux is the simplest of them all.


Calculation of RGB values given min and max values

Calculations like these can be hard to understand, so I would try to strive for something that is clearly correct, not just correct.

What I would do:

normalize the value from \$[min, max]\$ to \$[0, 2]\$
realize that the "strength" of a color is \$1 - |value - color|\$ (where \$color\$ is \$0\$ for blue, \$1\$ for green and \$2\$ for red), so compute that
clip the computer strength to remove negative numbers
finally multiply it by \$255\$ and convert to int (while also rounding the value, to avoid bias towards smaller numbers)

In code:

public static RgbValues GetRgbValues(float minimum, float maximum, float value)
{
    var normalizedValue = Normalize(minimum, maximum, value);

    return new RgbValues
    {
        Blue = Distance(normalizedValue, 0),
        Green = Distance(normalizedValue, 1),
        Red = Distance(normalizedValue, 2)
    };
}

private static float Normalize(float minimum, float maximum, float value)
{
    return (value - minimum) / (maximum - minimum) * 2;
}

private static int Distance(float value, float color)
{
    var distance = Math.Abs(value - color);

    var colorStrength = 1 - distance;

    if (colorStrength < 0)
        colorStrength = 0;

    return (int)Math.Round(colorStrength * 255);
}

This code is longer than the original, but I think it's also clearer about what it does. I didn't figure out what your code did until I read the SO question, I think it's much more likely I would have succeeded with this code.


Optimizing a python script with large arrays

You can get minor performance improvements if you use the += synthax of numpy, e.g.

mainarr[0, lats, lons] = mainarr[0, lats, lons] + c550

would reduce to

mainarr[0, lats, lons] += c550

Though it is not really in-place, you still gain some speed.

Another idea I had, was to use numpy.clip as it might be faster than setting the upper bound for your indices manually. You may be able to gain further improvements using numpy.put with mode=clip instead of really clipping the values. Positive effects for numpy.take (which is the opposite of numpy.put) are described here.

I put up a little program to test the gain compared to your proposed code. As you did not provide much additional information, I had to do some assumptions, e.g. for the way your data looks like (see mock_data).

The result is something like the following

Experiment (10 files, 10000 points)
Original: 10.093s   Refactored: 9.964s

Experiment (10 files, 1000 points)
Original: 2.399s   Refactored: 2.362s

Experiment (10 files, 100 points)
Original: 0.349s   Refactored: 0.342s

Experiment (100 files, 10000 points)
Original: 47.823s   Refactored: 47.672s

Experiment (100 files, 1000 points)
Original: 10.888s   Refactored: 10.781s

Experiment (100 files, 100 points)
Original: 3.306s   Refactored: 3.195s

Experiment (1000 files, 10000 points)
Original: 423.727s   Refactored: 420.922s

Experiment (1000 files, 1000 points)
Original: 58.546s   Refactored: 56.579s

Experiment (1000 files, 100 points)
Original: 20.227s   Refactored: 18.260s

Conclusion

In my oppinion, you will not be able to gain a great speed-up by fiddling around with numpy here. I made a small test not included in the listing above with 1 file and 1M points

Experiment (1 files, 1000000 points)
Original: 51.245s   Refactored: 48.703s

Because of this I think numpy is not really the problem in your case. If your mask hits a lot of points, it might be a good idea to remove the corresponding indices from lats and lons with numpy.delete, because both lists will get shorter and mainarr[0][0] will not be messed up with all the values you put there.

As the operations on the files do not really depend on the other files, one could come up with the idea to split up the process and merge their results later. Your task would be to re-implement your function, so that you can run it in parallel in different processes for parts of your file list. But even this might not help you that much, if your I/O capacity is the bottleneck.

Test script

import numpy as np
import timeit

def mock_data(n_samples=1000):
    """Mock data generation"""
    lats = np.random.uniform(-90.0, 90.0, (n_samples, ))
    lons = np.random.uniform(-180.0, 180.0, (n_samples, ))
    c550 = np.random.rand(n_samples)
    c670 = np.random.rand(n_samples)
    c870 = np.random.rand(n_samples)
    cldy = np.random.rand(n_samples)

    return lats, lons, c550, c670, c870, cldy

def mock_files(n_files=500, n_data=1000):
    """Mock files for benchmarking"""
    np.random.seed(42)
    return [mock_data(n_data) for _ in range(n_files)]

def getmask(cldy, tresh, max_val, min_val):
    """Mock getmask"""
    return cldy > (tresh / 2.0)

def original(files):
    """Original function by @Simon"""
    mainarr = np.zeros((4, 1800, 3600))
    i = 0

    #Loop over all input files
    for infile in files:
        lats, lons, c550, c670, c870, cldy = infile

        lats = np.array(np.round((lats+90)*10), dtype=np.int16)
        lons = np.array(np.round((lons+180)*10), dtype=np.int16)

        lats[(lats>=1800).nonzero()]=1799
        lons[(lons>=3600).nonzero()]=3599

        #The function below is already optimized
        masker = getmask(cldy, 1.0, 1.0, 0.0)
        pts = (masker != 1).nonzero()
        lats[pts] = 0
        lons[pts] = 0

        mainarr[0, lats, lons] = mainarr[0, lats, lons]+c550
        mainarr[1, lats, lons] = mainarr[1, lats, lons]+c670
        mainarr[2, lats, lons] = mainarr[2, lats, lons]+c870
        mainarr[3, lats, lons] = mainarr[3, lats, lons]+1

        i = i+1

    return mainarr

def refactored(files):
    """refactored function by @Alex Vorndran"""
    mainarr = np.zeros((4, 1800, 3600))

    #Loop over all input files
    for i, infile in enumerate(files):
        lats, lons, c550, c670, c870, cldy = infile

        lats = np.array(np.round((lats+90)*10), dtype=np.int16)
        lons = np.array(np.round((lons+180)*10), dtype=np.int16)

        np.clip(lats, 0, 1799, out=lats)
        np.clip(lons, 0, 3599, out=lons)

        #The function below is already optimized
        masker = getmask(cldy, 1.0, 1.0, 0.0)
        pts = (masker != 1).nonzero()
        lats[pts] = 0
        lons[pts] = 0

        # make use of "in-place" additions
        mainarr[0, lats, lons] += c550
        mainarr[1, lats, lons] += c670
        mainarr[2, lats, lons] += c870
        mainarr[3, lats, lons] += 1.0

    return mainarr

def validate_refactoring(n_files, n_data):
    """Validate the refactoring with comparison by value"""
    files = mock_files(n_files, n_data)
    mainarr_o = original(files)
    mainarr_r = refactored(files)
    return np.allclose(mainarr_o, mainarr_r)

def test_functions():
    """Test different versions"""
    n_runs = 100
    n_files_all = (10, 100, 1000)
    n_data_all = (100, 1000, 10000)

    # a list of tuples where the first element is the number of files
    # and the second one is the number of elements
    files_and_points = [(  10, 10000), (  10, 1000), (  10, 100),
                        ( 100, 10000), ( 100, 1000), ( 100, 100),
                        (1000, 10000), (1000, 1000), (1000, 100)]

    assert validate_refactoring(10, 100)

    imports = 'from __main__ import original, refactored, mock_files;'

    for n_files, n_data in files_and_points:
        data = 'files = mock_files({}, {});'.format(n_files, n_data)

        time_original = timeit.timeit(
            'original(files)', setup=imports+data, number=n_runs)
        time_refactored = timeit.timeit(
            'refactored(files)', setup=imports+data, number=n_runs)

        print('Experiment ({} files, {} points)'.format(n_files, n_data))
        print('Original: {:.3f}s   Refactored: {:.3f}s\n'.format(
            time_original, time_refactored))

if __name__ == '__main__':
    test_functions()


Design of a remoteControl class for connecting to electronic devices

@Override
public void turnOffDevice() {
    turnOnTVAlarm();
    System.out.println("TV has been turned off");
}

Welcome to the hell that never ends.

Just kidding. But please don't make TVs that automatically turn on an alarm to wake you up in the morning. I have alarm clocks for that, which are beating resistant.

Method naming

    control = RemoteControl.connectWithdevice(niceProjector);
        control.clickOnButon();

    control = RemoteControl.connectWithdevice(niceLargeScreenTV);
        control.clickOffButon();

Did you mean clickOnButton and clickOffButton?

Actually, your method naming could use some work. Let's go over some of them. But first, Java convention. It's Java convention that your function names are camelCase.

So, let's look at your method names:

connectWithdevice

This should be connectWithDevice, as each word after the first starts with a capital.

SwitchToFavoriteChannel

This should be switchToFavoriteChannel, as the first word does not have a capital. (That's how we easily distinguish classes and methods from each other).

turnOnTVAlarm

This one is tricky. For now, I'd let it stay... TV is only two characters. But when you have an acronym, treat it as one word. That is, turnOnTvAlarm. This because you end up with class names like HTTPConnection later, and getHttpConnection reads a lot better than getHTTPConnection. Especially if you're not familiar with the acronym.

Instantiating RemoteControl

private Device theDevice= null;

private RemoteControl(){

}

public static RemoteControl connectWithdevice(Device aDevice){
    RemoteControl remote = new RemoteControl();
    remote.theDevice = aDevice;
    return remote;
}

Have you considered passing the device in as constructor argument instead?

Then you can do something like this:

private final Device device;

public RemoteControl(Device aDevice){
    device = aDevice;
}

And people will always be forced to set a device.

With Objects.requireNotNull you can even make them not pass in a null value (you can also write the check yourself, but it's easier with Objects.requireNotNull.

private final Device device;

public RemoteControl(Device aDevice){
    device = Objects.requireNotNull(aDevice, "A remote control requires a device to work with.");
}

Design

Good designs feel natural.

Let's see how natural your design feels.

I have a Projector. And I have a TV. And I may have a RemoteControl... wait, I need to ask RemoteControl to connect to a device so it can send messages to the device? Why can't I just grab the remote control for the TV?

There's two options that I'm aware of in real life:

You take a programmable remote and set it to control a specific device. This would be like passing a different Device into an existing RemoteControl.
You pick up the remote that belongs to the TV. We'll assume we're clean, orderly people who store the remote with the device (far more likely for projectors than for TV's...). This would be like asking the Device to give a RemoteControl.

Both are more natural than wishing for a RemoteControl for a device.


Fetching weather data from the OpenWeatherMap API

I would suggest splitting this into two classes, one being your CityWeather POJO and a separate class for performing the logic currently in CityWeather.  The primary reason for this is to separate the business logic here (the parsing of the response from OpenWeatherMap) and your representation of the response (CityWeather).  In doing so, whichever class you have that is currently invoking the call to OpenWeatherMap should then pass the OpenWeatherMapResponse response that is returned from the call to this new class, which we'll call OpenWeatherMapParser.  OpenWeatherMapParser should take this response, and instantiate CityWeather objects based on the logic you currently have in CityWeather by calling it's setter methods


You need to access _cache in both classes, so it makes sense to have it as field in both of them too.
Your code is not thread safe. If you wanted to make it thread safe, I think the best solution would be to have a lock that you use whenever you access _cache or _source.
I don't think anything like this is in .Net.
What you're currently doing in Dispose() is wrong. You can't call Dispose() on _source and expect to use it later in another enumerator. In your case, I think you shouldn't do anything in Dispose(). You certainly shouldn't “nuke” _cache, because you're going to need it later!


Handling dialog closure in a VBA user form

I like how your form is no longer concerned with anything other than being a form.

One More Abstraction Level

I'd go one step further, and encapsulate the controls, so that the presenter class doesn't need to know about the implementation details of the form. For example the ChangeLabelAndCaption method knows that there's a Label control on the form, named lblInfo.

The form could expose a property for it instead:

Public Property Get InformationText() As String
    InformationText = lblInfo.Text
End Property

Public Property Let InformationText(ByVal value As String)
    lblInfo.Text = value
End Property

This adds a little layer of abstraction, so that the presenter no longer needs to care what actual controls are on the form, so if you decide to change the Label control for some Frame instead, nothing breaks - your code is now independent of the form's implementation details:

objSummaryForm.InformationText = strLabelInfo

For Closure's Sake

Private Sub UserForm_QueryClose(CloseMode As Integer, Cancel As Integer)

    End

End Sub

The End keyword is essentially analoguous to this:

Sure, that will get your form closed, and everything the VBA runtime has been doing will get released. But it's a tiny little wee bit excessive: the End keyword literally ends execution of all VBA code, right there and then.

The QueryClose event is fired just before the form closes, and its parameters give you a handle on the process.

It's just unfortunate that their types are Integer.

The CloseMode parameter tells you how the form is closing; its value is one of the VbQueryClose enum values:

vbAppTaskManager
vbAppWindows
vbFormCode
vbFormControlMenu
vbFormMDIForm

The interesting value - the one that means "user clicked the red X button", is vbFormControlMenu. The integer value for it is 0. So you can do this:

If CloseMode = 0 Then

Or better, this:

If CloseMode = vbFormControlMenu Then

And then handle form close yourself.

When the "red X button" is clicked, the form instance is normally destroyed. If the form contains state that the calling code wants to use, if you don't handle QueryClose and the calling code looks like this:

myForm = New MainForm
myForm.Show vbModal
Debug.Print myForm.SomeProperty

Then the last statement will be a runtime error, because myForm is Nothing at that point.

The Golden Rule

  He who creates an object, shall be responsible for its destruction.

If the form can destroy itself, the calling code is left needing awkward If myForm Is Nothing post-conditions to handle the case where it created an object that decided to hara-kiri.

A cleaner approach is to prevent the form from being able to destroy itself.

Private Sub UserForm_QueryClose(CloseMode As Integer, Cancel As Integer)
    If CloseMode = vbFormControlMenu Then
        Cancel = True
        Hide
    End If
End Sub

We set the Cancel parameter to True, thus preventing the destruction of the object, but only when the CloseMode flag indicates that the form was closed from the control menu. If we didn't call the Hide method, the form would simply refuse to close with the "red X button". This is useful for the rare circumstances where you don't want a form to be closable by the user.

The QueryClose handler signature would arguably be much clearer like this:

Private Sub UserForm_QueryClose(ByRef CloseMode As VbQueryClose, ByRef Cancel As Boolean)

Unfortunately that signature mismatches the interface declaration, and wouldn't compile. But handling the QueryClose event works exactly as if that's what the signature was.

Hungarian Notation

Your code suffers from the "bad" form of Hungarian Notation. While Systems Hungarian is traditionally acceptable for form controls (e.g. lblInformation, txtUserInput, btnOk, etc.; the prefix tells us what type of control we're looking at), using it in actual code for everyday variables, makes things messy:

Dim lngLong         As Long
Private WithEvents objSummaryForm As frmMain
Public Sub ChangeLabelAndCaption(strLabelInfo As String, strCaption As String)

Hungarian Notation was never intended to turn out this way (<~ must read!).

The guy that invented Hungarian Notation meant prefixes to describe the kind of variable, not their type. Apps Hungarian actually does make the code easier to read and understand, and makes wrong code, look wrong:

't: measured in twips
'p: measured in pixels

tArea = tHeight * tWidth 'obviously correct
tArea = pHeight * tWidth 'obviously wrong

Assuming the same context (twips vs pixels), compare to:

'int: integer
'lng: long

lngArea = intHeight * intWidth 'correct?
lngArea = lngHeight * intWidth 'correct?

When you prefix an object variable with obj, or a string with str, an integer with int, lng, or any other type-prefix, you add zero useful information to its identifier, and make the names read awkwardly.

Dim oRange As Range

Stop doing that.


How to implement HasMany() relationship with PHP?

I have the feeling that there is something wrong with your database structure. According your query, user will have exactly one item?

If one user can have many items and the items belongs only to this user, your schema should look like:

User:
ID Name ...

Item
ID Name UserId ...

So your query will look like

SELECT * FROM Item where UserId=100

If the items are shared you need a additional table

UserItemRelation
UserID ItemID

SELECT i.* FROM Item as i, UserItemRelation as r WHERE i.ID=r.ItemID and r.UserID=100

In both cases there is no need to join the User table as you know already the user ID.

Do get this into an abstract method in your model class you have to extract every information related to your concrete class into abstracts methods. Just as a draft:

function __call($method_name, $args)
{
     if (isRelationGetter($method_name))
     {
         return getRelatedEntities(extractField($method_name))
     }
     ....
}

function isRelationGetter ($method_name)
{
    $field=extractField($method_name);
    return isRelationField($field)
}

abstract function isRelationField($field);
abstract function getFieldInfo($field);
abstract function getPrimaryKey();

function getRelatedEntities($field)
{
    $fieldInfo=getFieldInfo($field)
    $query="SELECT * FROM "+$fieldInfo['foreignTable]+" where $fieldInfo['foreignKeyField]="+getPrimaryKey();
    //any database abstraction here
    return fetchAll($query)
}

As you see, a lot of magic.

If you write your own ORM let me recommend to automatically generate some abstract classes between your entity classes and your model and add all the getter to this abstract class. The getter itself can then call getRelatedEntities and you get rid of all this name guessing. Of course it would be easier to use an existing ORM.


Creating a dictionary of multiple results

Since I'm not really a web guy, this is going to be a style review, like my other reviews.

Why are you mixing camelCase and underscore_case together when naming variables? Variables and functions should be underscore_case, and classes should be PascalCase.
This seems like something that could be separated into functions, which allows for easier reusability. See if you can take parts of the code and separate them into their relevant parts.
I noticed that the 2nd-to-last line of this Python script is import json. You shouldn't be importing libraries after code has run. You should put imports/includes at the top of your script.
Why are you doing this? print "*"*25. It doesn't really seem like it's needed. Same with print json.dumps(final_result). That should be a return inside of a function.
You shouldn't be using file.close(). The reason for this is that the file isn't explicitly closed. You should be using a with..as context manager, like this.

with open("path/to/myfile.ext", "mode") as file_name:
     # Blah blah blah code goes here

Finally, if you aren't using parts of the code, don't comment them out. Just remove them completely. Commented out lines of code are an eyesore to look at.

That's about all I have. If there's anything else you might want me to cover, just mention it in the comments, and I'll see what I can do. Hope this helps!


JavaScript solution for diagonal difference

You don't need the inner for loops because you know exactly which array element you want for each sum:

for(currentLine = 1 ; currentLine <= numberOfInputs ; currentLine++)
    {
        var inputs = inputAll[currentLine];
        var inputArray = inputs.split(" ");

        sumFirstDiagonal += parseInt( inputArray[ currentLine - 1 ])
        sumSecondDiagonal += parseInt (inputArray [ inputArray.length - currentLine ])

    }


Remove excessive recurrent code from store and computed

DRY the code

The 3 store getters are identical apart from the filter value. So first thing is to remove the repeated code. Create a function (either in the store, or within its scope, that you pass the state and the filter string.

You get something like

filterTournaments(state, filter) {
  return state.tournaments.data
    ? state.tournaments.data
      .filter(tournament => tournament.state_value === filter)
      .sort((A, B) => A.created_at - B.created_at)
    : [];
},
getActiveTournaments(state) { return this.filterTournaments(state, "in_progress") },
getFutureTournaments(state) { return this.filterTournaments(state, "promo") },
getPastTournaments(state) { return this.filterTournaments(state, "finished") },

Direct to the array

The current solution on the HTML side is ugly, if you do have data to display, you have to get the data again, filtering and sorting each a second time.

Get the three items and put them directly in an array and test if all truthy, if so return the array, else an empty array.

getLatestTournaments() {
  const tournaments = [
      this.getActiveTournaments[0],
      this.getFutureTournaments[0],
      this.getPastTournaments[0]
  ];
  return tournaments[0] && tournaments[1] && tournaments[2] ? tournaments : [];
}

Do it in the store

Fast and efficient

If you want it done at the store and you can add some smarts to the filter function, that way you can avoid a lot of needless processing and memory use. Using filter and sort to find the min item with a matching state_value is not efficient.

getFilteredTournaments(state) {
    const data = state.tournaments.data;
    if (!data) { return [] }
    const filters = ["in_progress", "promo", "finished"];
    const tournaments = [];
    for (const filter of filters) {
        let min = Infinity, minTournament;
        for (const tournament of data) {
            const {state_value, created_at} = tournament;
            if (state_value === filter && created_at < min) {
               min = created_at;
               minTournament = tournament;
            }
        }
        if (minTournament) { tournaments.push(minTournament) }
        else { return [] }
    }
    return tournaments;
},

Then you need only the one call

:slideData="getFilteredTournaments"

I am not that familiar with VUE so may need the wrapper

:slideData="getLatestTournaments"

<script>
   getLatestTournaments() { return this.getFilteredTournaments }
</script>

But that type of code does not suit everyone.

Keep it simple

Using the existing methodologies you can do the 3 filters in one function in the store as follows

getAllTournaments(state) {
    const data = state.tournaments.data;
    if (data) {
        const filter = filter => data
          .filter(tournament => tournament.state_value === filter)
          .sort((A, B) => A.created_at - B.created_at)[0];
        const result = [
            filter("in_progress"),
            filter("promo"),
            filter("finished"),
        ];
        return result.some(item => !item) ? [] : result;
    }
    return [];
},

and call with

getLatestTournaments() { return this.getAllTournaments }


You could have used the fact that if \$n = k^x\$, then \$\log_k(n) = x\$ is an integer. However, due to the limited precision of floats in Python, this will generate some problems. To get around this, we can test both the ceil and the floor of the logarithm to see if we can get back n. This way we only ever need to do three expensive computations at most.

from math import log, ceil, floor

def check_kth_power(n, k):
    kth_log = log(n, k)
    return k ** int(ceil(kth_log)) == n or \
           k ** int(floor(kth_log)) == n

Now, instead of doing the exponentiation twice, we can realize that k ** int(ceil(kth_log)) = k * k ** int(floor(kth_log)) for a small speed-boost in about 50% of the cases (thanks to @KyleGullion:

def check_kth_power(n, k):
    candidate = k ** int(log(n, k))
    return candidate == n or k * candidate == n

This seems to work for quite large values (I checked up to about \$2^{32000}, 2^{20000} - 1, 3^{20000}\$). This is the version in the timing table below.

To get even more of a speed-boost, you can steal the nice premature exit from @pantarei's answer. This sacrifices some speed in the case that the number is a power of k, but gains about a factor 2 if it is not:

def check_kth_power_gp(n, k):
    if n%k != 0:
        return False
    candidate = k ** int(log(n, k))
    return candidate == n or k * candidate == n

And, finally, some timings. This compares my code and the code from @user1825464's answer, @pantarei's answer, @RyanMill's answer, @Eevee's answer and @JamesMishra's answer:

+-------------+---+----------+-------------+-----------+------------+---------+--------------+
|      n      | k | Graipher | user1825464 | panta rei | Ryan Mills |  Eevee  | James Mishra |
+-------------+---+----------+-------------+-----------+------------+---------+--------------+
| 2**1000     | 2 | 1.73 µs  | 9.9 µs      | 105 µs    | 12.9 µs    | 388 µs  | 3.23 µs      |
| 2**1000 - 1 | 2 | 1.99 µs  | 2.5 µs      | 619 ns    | 15.7 µs    | 765 ns  | 3.09 µs      |
| 3**1000     | 2 | 2.41 µs  | 4.26 µs     | 854 ns    | 22.4 µs    | 1.04 µs | 4.08 µs      |
| 3**1000     | 3 | 2.81 µs  | 12.6 µs     | 125 µs    | 13.8 µs    | 556 µs  | 4.51 µs      |
+-------------+---+----------+-------------+-----------+------------+---------+--------------+

So the log does not care if it actually is a kth power, whereas the loop has to do more work in that case, but potentially finds that it is not a power faster.

You could be checking for integerness using x % 1 == 0 for integers, != 0 otherwise (thanks to @Peilonrayz in the comments):

from math import log

def check_kth_power(n, k):
    return log(n, k) % 1 == 0

But, as noted in the comments, this works only until the precision of float is not enough anymore to distinguish that the result of the log is not an integer.

For numbers of the form \$ 2^x - 1\$, this happens at \$x = 48\$, as noted by @GarethReese, so you should have asked if there are any limits on n and k.


Vertically print a list of strings to STDOUT into 3 columns with column lengths as balanced as possible

You should take a look into Python advanced iteration capabilities, i.e. the itertools module. You’ll find a number of recipe; amongst which is take:

import itertools

def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(itertools.islice(iterable, n))

Which will help you extract columns out of your list of words. You can divide the length of the list by 3 to know how much data to take in each column, and adjust using the modulo of the length by 3 (the modulo first columns get to pick one more word); which can be eased thanks to divmod. Lastly, you need to organize your columns into rows, which is easily done using itertools.zip_longest.

That being done, you will need to print the data. The simplest solution is to only print them, as you do:

def print_words(words):
    columns, dangling = divmod(len(words), 3)
    iterator = iter(words)
    columns = [take(columns + (dangling > i), iterator) for i in range(3)]
    for row in itertools.zip_longest(*columns, fillvalue=''):
        print('{}  {}  {}'.format(*row))

Which behaves like so:

>>> print_words(['a', 'b', 'ccccccc', 'dd', 'e', 'ffffffff', 'gg', 'h', 'i', 'j'])
a  e  h
b  ffffffff  i
cccccc  gg  j
dd

Which is not pretty. So you might want to save the intermediate result to check, for each column, the length of the longest word, and apply some padding:

def print_words(words):
    columns, dangling = divmod(len(words), 3)
    iterator = iter(words)
    columns = [take(columns + (dangling > i), iterator) for i in range(3)]
    paddings = [max(map(len, column)) for column in columns]
    for row in itertools.zip_longest(*columns, fillvalue=''):
        print('  '.join(word.rjust(pad) for word, pad in zip(row, paddings)))

Which behave more nicely:

>>> print_words(['a', 'b', 'ccccccc', 'dd', 'e', 'ffffffff', 'gg', 'h', 'i', 'j'])
      a         e  h
      b  ffffffff  i
ccccccc        gg  j
     dd

Lastly, we can generalize to support an arbitrary number of columns:

def print_words(words, column_count=3):
    columns, dangling = divmod(len(words), column_count)
    iterator = iter(words)
    columns = [take(columns + (dangling > i), iterator) for i in range(column_count)]
    paddings = [max(map(len, column)) for column in columns]
    for row in itertools.zip_longest(*columns, fillvalue=''):
        print('  '.join(word.rjust(pad) for word, pad in zip(row, paddings)))

Which allows

>>> print_words(['a', 'b', 'ccccccc', 'dd', 'e', 'ffffffff', 'gg', 'h', 'i', 'j'])
      a         e  h
      b  ffffffff  i
ccccccc        gg  j
     dd
>>> print_words(['a', 'b', 'ccccccc', 'dd', 'e', 'ffffffff', 'gg', 'h', 'i', 'j'], 4)
      a        dd  gg  i
      b         e   h  j
ccccccc  ffffffff
>>> print_words(['a', 'b', 'ccccccc', 'dd', 'e', 'ffffffff', 'gg', 'h', 'i', 'j'], 5)
a  ccccccc         e  gg  i
b       dd  ffffffff   h  j


Peter already pointed out several important issues which I won't repeat, but here's what I've got:

Instead of verifying that the length of the key is correct, your code silently pads or trims the key. I would much rather see an exception being thrown instead. Especially security-related code should be easy to use correctly and difficult to use incorrectly.
Because the encryption key can only be specified when constructing an AES256 instance, your design 'encourages' key reuse. On its own that may not necessarily be a problem, but you're not using IVs correctly, and together that does introduce certain vulnerabilities.
RijndaelManaged and ICryptoTransform are both disposable, but they're not being disposed anywhere.
The private Encrypt/Decrypt methods are so short that merging them into the public methods would actually make the code easier to manage.
You may want to document which cipher and padding modes your code uses (and why), so other programmers (and future you) don't need to look at the implementation to find out (or wonder why certain decisions were made).
MSDN recommends using the Aes class instead of RijndaelManaged. It also appears that the Rijndael implementation isn't 'FIPS compliant', which apparently makes it unusable under certain security configurations.
As far as I understand there's no need to create a new RijndaelManaged instance for each operation, so why not create one instance and store it in a field? Or, instead of creating a very thin wrapper class, you could just create a factory method and some extension methods for encryption/decryption. By having these extension methods operate on SymmetricAlgorithm they can also be reused for other encryption algorithms, should the need ever arise.


You seem confused.  Given two objects, a.Equals(b) tests whether they have equivalent content.  Basically, what you wrote as UnnamedCompareMethodB() should actually be the Equals() method.

I wouldn't bother with defining an UnnamedCompareMethodA() at all.  If someone wants to compare objects by FullFilePath, they can just write a.FullFilePath.Equals(b.FullFilePath).

Furthermore, calling object.ReferenceEquals(this, null) makes little sense.  If the object were indeed null, the code would have already crashed with a NullReferenceException before then.


I'll review this in two steps: first the body of selectionSortAlgo and then the higher level structure/architecture.

The selection sort implementation

Swapping elements

First of all, there is a bug (the only one I could find) in the code that swaps two elements that sometimes loses elements while swapping them. The smallest example where I can reproduce this is by sorting [1, 0, 0] which results in [0, 0, 0], losing the 1.

Looking at this code:

if minimumIndex != index {
    elements[index] = elements[minimumIndex]
    elements[minimumIndex] = item
}

I see that you're reading the item from the array as you're enumerating it and writing that at the minimumIndex, presumably to avoid having to get a tempItem to swap the two elements:

if minimumIndex != index {
    let tempItem = elements[index]
    elements[index] = elements[minimumIndex]
    elements[minimumIndex] = tempItem
}

The problem is that — because of array's value semantics — this doesn't account for changes that happen to the array since you started enumerating it. In short, you're swapping in a stale value from before you started sorting the array.

Now, what you're really doing here is swapping the elements at two indices, and that is best done with swapAt(_:_:). It's also documented to have no effect if the two indices are the same, so you can get rid of the surrounding if-statment:

elements.swapAt(minimumIndex, index)

If you're following along step-by-step you'll notice that the item of the enumerated array is now unused, so you can change it to only loop over the indices:

for index in elements.indices { ... }

Finding the index of the smallest element

I'll make two small syntactical changes to the code that finds the minimumIndex, partly to leverage Swift features but also to prepare the code to be generic (which I'll discuss later).

First, I'd like to describe what this loop is doing as "iterating through the indices of the slice of elements starting from the current index". In code I'd translate that into:

for subIndex in elements[index...].indices { ... }

Other than the minor syntactical difference, this means that the type of subIndex is an associated type of the collection being enumerated. This has no benefit for arrays, but will be important if you want to be able to sort other collections.

Secondly, since the loop body is only executed when the element at that subIndex is smaller than the element at the current minimumIndex I would possibly move the inner if-statement to a where clause:

var minimumIndex = index
for subIndex in elements[index...].indices where elements[subIndex] < elements[minimumIndex] {
    minimumIndex = subIndex
}

This change is only syntactical.

Going even further

Realistically I would probably stop here, but I'm going to continue to show more of this process and other implementations.

Considering the goal of that loop, what it's really doing it "finding the index of the minimum element in the rest of the elements".

There is two ways we can approach this goal. The first approach is by first finding the minimum element, and then finding the index of that element:

// The slice will never be empty, so it will always have a smallest element
let minimumElement = elements[index...].min()!
// This is one of the elements, so it will always have an index
let minimumIndex = elements[index...].index(of: minimumElement)!

In both of these lines it's safe to force-unwrap the results because:

the array slice will never be empty, so there will always be "some" smallest element
the smallest element comes from elements, so it will always have an index.

This alternative works, if it's a style that you prefer. However, it's iterating the slice twice; once to find the element and once to find the index.

To address that I'll use a zip to iterate over both the elements and the indices at the same time and find the minimum element-index-pair by comparing the elements. Since only the minimum index is needed to swap the elements I'll use tuple destructuring to only reference the minimumIndex once it's found.

// The slice will never be empty, so it will always have a smallest element
let (_, minimumIndex) = zip(elements[index...], index...).min(by: { $0.0 < $1.0 })!

For the same reason as before, it's safe to force-unwrap here. The slice will never be empty.

Higher level structure/architecture

At a high level there are two limitations to the Sort struct and its underlying implementations:

It can only compare Int elements
It can only sort arrays.

The first is pretty straightforward to address, by making the struct generic over an Element type that is constrained to be Comparable and by using arrays of that Element type:

struct Sort<Element: Comparable> {
    private var elements : [Element]
    ...
}

The second one is a bit trickier and highlights some constraints in how Sort can be extended to support other sorting algorithms. To make Sort support any kind of collection, it would be natural to also make it generic over a Collection type that is a Swift collection:

struct Sort<Collection: Swift.Collection, Element: Comparable>
       where Collection.Element == Element {
    private var unsortedElements : Collection
}

However, with this change the selection sort algorithm can no longer be used because swapAt(_:_:) is a method of MutableCollection rather than Collection. It's possible to constrain the Sort Collection to be a mutable collection, but what if another algorithm has another requirement? With this strategy we would end up constraining Sort more and more to the sum of all the different algorithms requirements.

A better alternative is to keep Sort as broad as possible, but to supply no sorting algorithms by default. Instead each sorting algorithm would be added as an extension only where the generic placeholder types satisfy those requirements:

extension Sort where Collection: MutableCollection {
    func bySelection() -> Collection {
        var elements = unsortedElements
        for index in elements.indices {
            let slice = elements[index...]
            let (_, minIndex) = zip(slice, slice.indices)
                                .min(by: { $0.0 < $1.0 })! // The slice will never be empty, so it will always have a smallest element
            elements.swapAt(minIndex, index)
        }
        return elements
    }
}

This change was greatly simplified because I had already moved away from the assumption of Int indices and instead got the index type from the collections associated Index type (implicitly). In other words, here minIndex is of the type Collection.Index rather than Int.

With this strategy each sorting algorithm can be added separately with the type constraints it needs, and a user of this API would have access to only the sorting algorithms that are available for the type of collection they are using.

At this point I don't see any value in the wrapping Sort struct, since these algorithm could be added as extensions to the collection itself in the same way. This solutions also has a more convenient and more "swifty" call site syntax

[2, 4, 23, 268, 9, 0].selectionSorted()

In the end, this is probably the solution that I'd end up with (without the Sort struct):

extension MutableCollection where Element: Comparable {
    func selectionSorted() -> Self {
        var elements = self
        for index in indices {
            let slice = elements[index...]
            let (_, minIndex) = zip(slice, slice.indices)
                                .min(by: { $0.0 < $1.0 })! // The slice will never be empty, so it will always have a smallest element
            elements.swapAt(minIndex, index)
        }
        return elements
    }
}

It's flexible in that it works with any mutable collection of any comparable element type. It's convenient in that it will show up immediately on the collection types where it's supported. I also feel that it's "swifty" in its style and conventions – both in its implementation and at its call site.


This is unnecessarily complicated:

  if (argc != '\0' && argc == 2 )

This is exactly the same thing but simpler:

  if (argc == 2)

Instead of the hard-coded ASCII code 65 of "A", you could use 'A' to make the code easier to read. So instead of this:

//converting capitalized chars
char acap = (a[i] - 65);
int ccap = (acap+f)%26;
//final capitalized chars loop
char ecap = ccap + 65;
printf("%c", ecap);

You can write like this:

//converting capitalized chars
char acap = (a[i] - 'A');
int ccap = (acap + f) % 26;
//final capitalized chars loop
char ecap = ccap + 'A';
printf("%c", ecap);

I also added spaces around operators in (acap+f)%26 to make it more readable, which is a good practice.

The same goes for the number 97, it's better to use 'a' instead.

The code for handling upper case and lower case letters is practically the same, except for the constant 'A' and 'a'.
Avoid such code duplication, repetition and copy-paste coding as much as possible.
Extract the common logic to a helper function,
and reuse it by passing 'A' and 'a' as parameter.

Use more descriptive variable names.
f, acap, ccap, ecap are really not intuitive,
and your code could become much more readable if you gave these better names.

@Edward made an excellent remark in comments that I'm just going to quote verbatim:

  It's worth noting that both original and suggested changes assume a
  character encoding with a contiguous encoding for the alphabet. This
  is not actually guaranteed by the C standard. For example, EBCDIC
  systems are admittedly rare but not yet extinct.


Mutation You are mutating the existing state when you do
let newArr = [...rowDataTracker];
// ..
  newArr[itemIndex]["payload"][columnId] = newValue;

because spread syntax only creates a shallow copy of the array or object. This should never be done in React. (See end of answer for how to fix it - create the new obj no matter what, then either push it to the new array, or replace the existing object in the array, without mutating the existing object in the array)
Dot notation Most people prefer to read and write using dot notation in JS when possible - it's more concise and easier to read. ESLint rule: dot-notation. You can use .payload instead of ["payload"].
Property/variable naming The rowId refers to the same thing as the itemNbr, which looks to refer to the same thing as the id in the rowDataTracker array. It's good to be consistent with variable names and properties when possible - consider picking one and sticking with it. If you use the variable name itemNbr, you can use it  shorthand in the object literal:
const obj = {
  itemNbr,
  // ...

id or itemNbr or both? You check against the id property in rowDataTracker in ifItemExist, but you push to the same array with a property named itemNbr. This looks very likely to be  a typo. You probably meant to push an object with an id property, or you wanted to check against the itemNbr property instead.
Misleading function name ifItemExist doesn't return a boolean indicating if an item exists - it returns the index of the possibly-existing item. Maybe call it getItemIndex.
Prefer const over let when the variable name doesn't need to be reassigned.
In all:
const getItemIndex = (arr, item) => {
  return arr.findIndex((e) => e.id === item);
};

function storeEdit(id, field, newValue) {
  const itemIndex = getItemIndex(rowDataTracker, id);
  const obj = {
    id,
    payload: {
      ...rowDataTracker[itemIndex]?.payload,
      [field]: newValue
    }
  };
  if (itemIndex === -1) {
    setRowDataTracker([...rowDataTracker, obj]);
    return;
  }
  const newArr = [...rowDataTracker];
  newArr[itemIndex] = obj;
  setRowDataTracker(newArr);
}


Problem 1

Just assign them one at a time, once the object already exists:

ns = {};
ns.a = function (x, y) { return x+y; };
ns.b = ns.a;

To answer specifically whether there's any other workaround if you're dead set on declaring these inside the object literal syntax: no.

Problem 2

Looks good enough to me, though I'd try to avoid using the object's name so deep into its definition.

Consider using prototyping instead.


Handle data received by Ajax request and update database (prepared statement)

Should I avoid using die();?

I would (at least in the places you are using it). It makes your code really hard to reuse. And it can easily lead to problems once your requirements change.

Personally, I would just use exceptions, and let them bubble up to wherever you want to handle the problem (I usually follow MVC loosely and do this in the controller).

Security

Yes, your code should be secure. You are using prepared statements, and you are using them correctly. Additionally, you prevent XSS, which is also done correctly.

Two small things:

You should not echo database error messages directly to the enduser. It may contain information that can help in further attacks, and it is not very user friendly.
You should not use REQUEST, but POST instead. Requests that change state should always be submitted via POST, and using REQUEST thus provides a fall-back to GET, which might aid attackers in exploiting other existing vulnerabilities such as CSRF or XSS. Example: Let's say your request is vulnerable to CSRF. Without the fallback, I could only use POST, meaning I can only distribute my payload via websites I control or websites that allow JavaScript to be posted. But if you do allow the fallback to GET, now I can use any website where I can eg control image urls, which is easier to find. Same for XSS, where it's distributing links vs getting the victim to visit my website.

Readability

I found your code a bit hard to read, resulting from a combination of these issues:

Naming

don't shorten variable names. If I have to guess and/or remember what you meant, it will make the code harder to read. Examples: dob (date of birth?), mate (no idea), exe (execute)
consistency: Same things should be named the same, and all variable names should follow the same pattern. If you use snake_case, use it everywhere (eg newdob vs date_of_birth; one uses snake_case, one doesn't, one shortens dob, one doesn't; same with new_dob vs userId).
again naming consistency: Here, you use the same pattern for different things: update_exe/update_result vs update_dob. All three deal with dob stuff, but only the ar contains it in its name (instead of eg update_query which would follow the pattern of the other two names).
one more naming consistency issue: For the select query, you use this pattern: check_info (the query), check_mate (bind result for param as well as result, and check result), check_exe (execute result). For the update query, you use update_dob (the query), update_exe (not execute result, but prepare result, as well as bind result), update_result (execute result). It would be better to be consistent here.

Formatting

I wouldn't put spaces around ->. Spaces indicate an interaction of two entities (eg when using == or .), but that's not what's happening. There is only one entity, and its method is being called. This confused me a couple of times while reading your code.
inconsistent spacing, eg in your if statements.
inconsistent function use: you use exit and die interchangeably in very similar situations. I would pick one and stick with that.

Nested ifs and lack of function

For my taste, your code is too nested, and it does too many different things for its length. An alternative might look like this (a bit simplified):

$result = processBirthday($_POST['newBirthday'], $_POST['userId']);
[...]

function processBirthday($newBirthday, $userId) {
    if (!isValidDate($newBirthday)) {
        return "not valid";
    }

    $oldBirthday = getBirthday($userId);
    if ($newBirthday == $oldBirthday) {
        return "same date";
    }
    updateBirthday($newBirthday, $userId);
}

function isValidDate($newBirthday) {
    return !($newdob == '--' || $newdob == '0000-00-00' || $newdob == false || $newdob == NULL);
}

The getBirthday and updateBirthday functions now do the actual db interaction. This way, you can easily reuse those functions in other parts of your application, and your code is a lot more readable.

Other

double checks: if ($newdob != $date_of_birth) { ... } else if ($newdob == $date_of_birth) { ... } here you don't need the second check. Either it's the same, or it's not.
one-time variables. If these kinds of variables have good names they may sometimes increase the readability of code. But often times, they just make code harder to read. So instead of $update_result = $update_exe -> execute(); if ( false === $update_result ) I would just write if ( false === $update_exe->execute()) or just if (!$update_exe->execute()).


LINQ to SQL query filter, with the name match ignoring multiple punctuation characters

You are rather removing those parts instead of replacing them, so more appropriate name would be remove all.

You can make your own extension method like this :

public static class Extensions
{
    public static string RemoveAll(this string source, string[] charsToRemove)
    {
        return charsToRemove.Aggregate(source, (current, t) => current.Replace(t, string.Empty));
    }
}

If you really want to replace them with something you can do it like this :

public static string ReplaceAll(this string source, string[] charsToRemove, string[] charsToReplace)
{
    string result = source;
    for (var i = 0; i < charsToRemove.Length; i++)
    {
        result = result.Replace(charsToRemove[i], charsToReplace[i]);
    }
    return result;
}

Example usage :

var filter = "filter";
string[] itemsToRemove = {"'", @"""",};

query = query.Where(x =>
    x.Name.RemoveAll(itemsToRemove).Contains(filter) ||
    x.FullName.RemoveAll(itemsToRemove).Contains(filter));

UPDATE

LINQ to SQL would require you to call .AsEnumerable(), .ToList() or .ToArray() first before operating on strings, you might loose some performance from that but the other way is to write your custom query provider or stick with what you have.


Converting List to a DataTable and/or DataSet Extension Methods

There are a few things I notice right off the bat.

Your variable names while not bad, could be better.  For instance props -> properties.  Stuff like this makes the code easier to read.
You have the properties, why not use a foreach loop to fill the datatable (you did it in ToDataSet)
the _ prefex should be used for class variables, not local variables.
try using var when declaring obvious variable types var row = t.NewRow()
There is no error checking when you are filling the values in the data table.  What happens if it is not a class (int, double, long)?  You could force the generic to be a class by adding where T : class.
Why don't you use the ToDataTable method to create the table in the ToDataSet method?  This will eliminate duplicate code, and have 1 point of failure/modification as required.  As an aside, I would use the code from ToDataSet to create your DataTable, as it is written better.
While I applaud your use of it, I'm not sure the using syntax is appropriate here.  I would move that to where these methods are being called using (var dt = list.ToDataTable())  Having it here will more than likely cause unexpected things to happen in your code.
I would make these extend IEnumerable<T> as that will make them way more useful by not limiting them to IList<T>.

I do like your use of white space and indentation, so good job on that.  The extra indentation will be removed when the using statements are removed.  I also like the name of your methods, very clear and concise to their intent.


That seems like a very long method to splice and put together the string every even set of characters. You are essentially trying to build a square matrix using the characters from the given string. Python has a very nice slice-and-stride feature which can perform the same task in a single inline operation.

I took the liberty of rewriting your encrypt function:

from math import ceil
from string import whitespace

def square_encrypt(str_input): # avoiding the name `string` as python has a module `string`
    str_input = str_input.translate(None, whitespace) # making a copy and overwriting input parameter
    square_size = int(ceil(len(str_input)**0.5)) # or int(ceil(sqrt(len(str_input))))
    encrypted_list = [str_input[i::square_size] for i in xrange(square_size)]
    return " ".join(encrypted_list)


Make sequential fadeIn() promises more manageable

You don't actually need promises for this one. Here's an overly simplified version that takes advantage of the fact that you can call the containing function by a given name.

// Let's turn a jQuery set to an array coz it doesn't have shift, which we'll use
var liArray = $('li').hide().get();

$('input').click(function handle(){
  // Unqueue one from the set and fade it in. Note that shift() alters the array so
  // the next time we call it, the second one is in front of the queue. Also wrapping
  // what we shifted with jQuery because get() returns an array of DOM elements of
  // the jQuery set
  var li = $(liArray.shift());

  // If we shifted out nothing, then that's the end of this.
  if(!li) return;

  // Set the callback of the fadeIn to the same function. That way, if the animation
  // completes, then it fires again.
  li.fadeIn(handle);
});

If the idea is to teach promises, then the following might be better. Here's an interesting approach where we use Array.prototype.reduce to carry over a dummy deferred, attach the handlers and kick it off, starting the fadeIn process.

var liArray = $('li').hide().get();

// So here we create a deferred object and during its creation, fade in the element.
// When the animation completes, it calls on `deferred.resolve` which resolves the
// fade promise.
function fade(item) {
  return $.Deferred(function (deferred) {
    $(item).fadeIn(deferred.resolve);
  }).promise();
}

// Here we use reduce to attach a handler for each item as well as allow us to carry
// over a value to the next iteration - the result value of `then()`.
function reducer(promise, item) {
  return promise.then(function () {
    return fade(item);
  });
}

// Here we create a dummy promise which allows our reducer to attach the handlers.
// Then we use reduce to attach a handler for each item on the promise and then kick
// of the whole operation by resolving the dummy promise.
$('input').click(function handle() {
  var root = $.Deferred();
  liArray.reduce(reducer, root.promise());
  root.resolve();
});

Both examples assume liArray is an array containing li elements, whether dynamically generated or just fetched from the page, either way it doesn't matter as long as they're already rendered. Also went for an array instead of a jQuery object because array operations like shift() and reduce() are very handy.


Project Euler problems 18/67: maximum path sum

Even before starting the review I have to disappoint you. The problem has nothing to do with the dynamic programming. Now let's go.

Naming: Avoid meaningless names, such as q, temp1, temp2, calc and otherCalc.
Responsibilities: You correctly separated IO in a method of its own. The actual calculations also deserve to be separated.
Algorithm: A triple nesting loop is an immediate red flag. In fact, you don't need to iterate over q (which is the index into the bottom row, right? - it took me a while to figure it out) at all: the kth element of the upper row can be only influenced by kth and k+1th of the bottom one. Taking it into consideration, you'd eliminate one level of nesting as well as a really ugly special case of temp2.size() == 1.

The core loop should look like

    for (k = 0; k < upperRow.size(); k++)
            upperRow[k] += max(bottomRow[k], bottomRow[k+1]);

That said, let me reiterate a very important rule of no raw loops: for every loop you write, think of it as a standalone method and figure out a meaningful name for it. If you can't than you effectively don't know what it is doing!


There are other data structures for priority queues. You might consider implementing the queue as a binary heap instead, which gives you a run-time complexity of O(1) for accessing the "largest" (or "smallest", depending on the comparison) element, and O(log n) for insertion and removal (of the largest).


First of all, I started rewriting your class but found many implementation problems design wise that stopped me from rewriting it (because it would be to much for you to learn in one go and would take me a long time to design, code and explain). So I have done a small portion.

Problems Are

No type casting so ANY object could be passed to the constructor
What if the database object changes? The method calls on the db object inside the VisitorCounter class will break
You are doing two roles inside the VisitorCounter class, you are both keeping a global visitor count using the database AND trying to keep track of the users visits. Also, you are hard coding it to the $_SESSION! What if you want to use APC or Memcache for example!? Code changes would occur.
You are not programming to interfaces but instead to concrete classes (and globals i.e. $_SESSION)

Solution

This is a semi pseudo (not complete but will show for demonstration purposes) PHP example just to demonstrate many things for you to learn but i have only taken out the site counter part of your visitorcounter class. You can implement thevisitorcounter in exactly the same way I have done for the DB & Site Counter, but instead for Session & Visitor Counter which would be brilliant practice for you! ;)

Read the comments in the comment.

/**
* by programming to this db interface, you can CHANGE the db class to ANY class you want at any time. As long as the new class
* implements this interface, the rest of the code will no how to handle the class :) this demonstrates programming to implementations
* and not to (concrete) classes
*/
interface db_connection {
    public function connected();
    public function query($sql);
}

/**
* this will be where the database specific database calls will be made. I have named this one mysql, but I only
* did this because it means I could have db_oracle (and others), and if I were to pass a db_oracle instace to the visitor counter construct
* it would still work :D as long as the db_oracle class implemented db_connection. You can then interchange db_mysql and db_oracle as you wish
*/
class db_mysql implements db_connection {
    public function connected() {
        //returns true or false depending on if connected
    }
    public function query($sql) {
        //actually makes the query, returns the result resource if ok, false if it failed
    }
    public function escape($string) {
        //escapes the string to protect from sql injection attacks
    }
    public function result($sql_resource) {
        //if the resource contains results, will return the first field from the first row of the result, FALSE otherwise
    }
    //... and all the other methods you want such as connect() disconnect() ping() etc...
}
/**
* site counter
*/
class site_counter {

    private $db = null;
    private $total = 0;

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

    /**
    * increments the site counter
    */

public function increment($step = 1) {

    //ensure the step is numeric
    if ( ! is_numeric($step)) {
        throw new Exception("Expected a number, got something else!");
        return false; //didn't work
    }

    //notice the limit clause, use this to indicate to SQL that it no longer has to keep searching for more to update
    //you can increment existing fields by using SQL directly, don't do things the long way around as you did as you will also have concurrency issues (another poster I believe explained it)
    $step = $this->db->escape($step); //just to be safe ;)
    if ($this->db->query("UPDATE stats SET visits=visits+{$step} LIMIT 1;")) {
        return true; //worked ok
    }

    return false; //didn't work

}

    /**
    * resets the counter in the database and session
    */
    public function reset($to = 0) {
        if (is_numeric($to)) {
            $to = $this->db->escape($to); //just to be safe ;)
            //notice the limit clause, use this to indicate to SQL that it no longer has to keep searching for more to update
            return $this->db->query("UPDATE stats SET visits={$to} LIMIT 1;");
            } else {
            throw new Exception("Expected a number, got something else!");
        }
        //something went wrong
        return false;
    }

    /**
    * resets the counter in the database and session
    */
    public function get_total_hits() {
        //the (int) is called type casting, so false (if the query fails for example) will return 0
        return (int) $this->db->result($this->db->query("UPDATE stats SET visits={$to} LIMIT 1;"));
    }

}


Javascript function to get cellId from map point

I always like to document my functions using high-level doc-blocks, e.g.

/**
 * Return the ID of the cell whose center is at the given point or -1 if ...
 *
 * @param {number} x - The x coordinate of the given point.
 * @param {number} y - The y coordinate of the given point.
 * @return {number} cell ID or -1 if no cell found at given point.
 */
const getCellIdFromMapPoint = (x, y) => { ... }

Also, I use inline comments to help the reader and my future self to understand complex statements such as

// Do C if A and B or C:
if (x < offsetX && y < offsetY)
   if ((offsetY - y) / (cellCoordinates.x - x) > (offsetY - cellCoordinates.y) / (cellCoordinates.x - offsetX)) return cellId

Better yet, take those complex statements as a hint to better refactor your code.

I advise to use available language constructs where appropriate. If you replace a simple for-loop with a while-loop for no apparent reason, a fellow developer will have a harder time to read and understand your code.

Also, I really recommend to use curly brackets with if-statements. The lack of those might be more pleasing to the eye by hiding the deep nesting, but makes reading and understanding as well as modifying your code much harder.

I suggest to combine if-clauses with identical statements. Instead of writing e.g.

if (A)
  if (B)
   return cellId;
if (C)
  if (D)
   return cellId

write e.g.

if ((A && B) || (C && D)) {
  return cellId;
}

Better yet, write helper functions to reduce the complex conditions, e.g.

if (isSomeCondition(A, B) || isSomeOtherCondition(C, D)) {
  return cellId;
}

Give those functions clear, self-documenting names to help the reader along. In your case, those could be e.g. isWithinRect(x, y, rect) or similar.

Your algorithm's runtime complexity is probably linear in the number of available cells. If you find that your application is running slow because of that, you can employ techniques such as spatial partitioning to improve runtime performance.


Instead of checking for a UID collision before an insert, I would put a unique key on that column, and then write fallback code for the case (very very unlikely) when two collide. That way you can simplify your logic and reduce the number of queries to one instead of two. You also don't need a transaction if you implement this change, since there is only 1 query.

//you can remove the outer try/catch since only the execute() should possibly fail
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //<~ put this in the initialize of the db connection
$STH = $DBH->prepare("INSERT INTO USERS (uid,namn) VALUES (:uid, :name)");
$STH->bindParam(':uid', $uid);
$STH->bindParam(':namn', $_POST['namn']); // a value posted form user input
try {
    $STH->execute();
} catch( PDOException $e ) {
    //deal with collision
}


Find the smallest number greater than "n" with the same digit sum as "n"

You have to come up with a trickier algorithm here rather than doing a brute force approach.

Let's try to think about a couple of cases here.

123, its sum of digits is 6. If we decrease 3 by 1, then we'll have to increase 2 by 1 (as you're trying to get the least larger element) -> 132
1293, sum of digits is 15. If we decrement 3 and increment 2 (9 is already a maximum digit so we cannot increment it) then we'll get 1392. But is it really the least greater value? Well, no, 1329 is. So, what we should do it increment 2, substitute 9 with 3 and decrement 3 (as 2 was just incremented). 9 must go to the end to minimise the value as much as possible.
129993 - here we have a similar case as #2. The only difference is that the full 999 must go to the end -> 132999.
12920 - another interesting case. But again, find the first non-zero digit from the left, then if 9s are its immediate neighbours move them to  the end, decrement 2 and put 0 before it -> 13019.

Hopefully, based on examples above it's clear which steps have to be implemented (we move from right to left):

Find the rightmost digit that can be decremented. So, 0 cannot be such a digit as it's minimal already. If such digit doesn't exist then there's no solution. Decrement it.
Find the closest digit to the left of the digit from step 1 that can be incremented. So, 9 cannot be such a digit as it's maximum already. If there's no such digit then just prepend 0 to the start of the current number. Increment the digit.
Now, sort all the digits after the digit from step 2 in ascending order.
You have a solution now!

UPDATE

As a bonus, a quick implementation of the approach in Python. I'll leave it up to you to improve this solution (if possible :) )

def solve(n):
    size = len(n)

    trailing_zeros = list()
    first_nines = list()

    i = size - 1
    while i >= 0:
        if int(n[i]) != 0:
            break
        trailing_zeros.append(n[i])
        i -= 1

    if i < 0:
        print ("No solution!")
        return

    first_non_zero_digit = int(n[i])
    i -= 1
    while i >= 0:
        if int(n[i]) != 9:
            break
        first_nines.append(n[i])
        i -= 1

    if i < 0:
        remaining = '1'
    else:
        increased_digit = int(n[i]) + 1
        remaining = ''.join(n[:i]) + str(increased_digit)

    print(remaining + ''.join(trailing_zeros) + str(first_non_zero_digit - 1) + ''.join(first_nines))


Add or remove a class on two elements when two different events fire

Don't repeat the queries. Store any queries that are called more than once in a variable, and utilize jQuery's chaining:

const navbarNav = $( '#navbarNav' );
const htmlBody = $( 'html, body' );

navbarNav.on( 'show.bs.collapse', function() {
    htmlBody.addClass( 'noscroll' );
}).on( 'hide.bs.collapse', function() {
    htmlBody.removeClass( 'noscroll' );
});

Why are you setting the class on both the html and body elements? Either should be sufficient.

Name the class semantically. Just like you call a class for important text "important" and not "red", just because it happens to be red, you don't call a class that indicates whether the main navigation is open "noscroll" but "main-nav-open" (for example).


Webservice methods using EclipseLink and database entities

Just a few notes:

if(!em.getTransaction().isActive()) {
   em.getTransaction().begin();
}
try {
     em.merge(person);
     em.getTransaction().commit();
     emf.getCache().evict(Person.class);
} catch (Exception ex) {
     if(em.getTransaction().isActive())
        em.getTransaction().rollback();
} finally {
    em.close();
}

I'd create a local variable for em.getTransaction() here and move the isActive check inside the try block.

try {
    EntityTransaction transaction = em.getTransaction();
    try {
        if (!transaction.isActive()) {
            transaction.begin();
        }
        em.merge(person);
        transaction.commit();
        emf.getCache().evict(Person.class);
    } finally {
        if (transaction.isActive()) {
            em.transaction.rollback();
        }
    }
} finally {
    em.close();
}

It closes the EntityManager in every code path as well as the transaction.

I've removed the exception catching. If you catch it consider at least logging it.

Evicting the whole Person cache every time you save a Person entity does not seem a good idea for performance.

Please note that if something call this method with an active transaction (I'm not sure if it's possible at all) it will returns with a committed or rollbacked, but not active transaction.


The Caesar function

First the parameter string should be renamed as it has the same name as the standard module string. Sure you don't use it, but it is a bad habit to get into and can result in problems later on. Regardless, since we're dealing with cryptography and sending messages and such, wouldn't a better word be message?

There is also no documentation. caesar is not a descriptive name if you don't already know what a Caesar cipher is. You should have a docstring that describes that this a Caesar cipher and at least link to Wikipedia for a description of the Caesar cipher if not describe it yourself.

The main function

store_true

if args.bruteforce:
    bruteforce = True
else:
    bruteforce = False
    shift = args.shift

The 'store_true' flag indicates that args.bruteforce is True when the flag is specified and False when it is not specified. Forget the bruteforce variable and just concern yourself with args.bruteforce.

store_const

There is also a store_const action that has the optional1 parameters const and default. Thus you can have const=re.compile('[^A-Z\s]') and default=re.compile('[^A-Z]'). This removes the need for:

if args.preserve_spacing:
    regex = re.compile('[^A-Z\s]')
else:
    regex = re.compile('[^A-Z]')

1 The const parameter is a paradoxically optional argument that is required


12 hours to 24 hours conversion function

This function is not just cryptic — it's also wrong.  I would expect convert_to_24('12:00:00AM') (midnight) to be '00:00:00', but it returns '12:00:00' (noon).


Function that recursively downloads entire directory is slow

Check your buffer/BLOCKSIZE. If it's too small, it may be making many more reads and writes, and each has to wait for the network to respond.

I'm not given any information as to what block size you're using, so I can't help anymore.


Project Euler 23 in Scala (non-abundant sums)

I was able to reduce the run time of your code to a few seconds (2 seconds on my computer) by changing the type of abundant from a List to an immutable Set.

You were correct that !abundantList.exists(x => abundantList.contains(num - x)) was the major bottleneck in your code.

This is a bottleneck because checking that an item exists in a List means inspecting every item in the List until we find it or reach the end of the List. Fortunately we can use a Set (which under the hood is supported by the immutable.HashMap class) and reduce the search time for objects from linear to effectively constant.

Notice that in the code below I simply applied the method toSet to your abundance function converting the returned List to a Set.

val abundant = abundance(3, List()).toSet

def notSumAbundant(num: Int, currentList: List[Int]): List[Int] = {
  if(num <= n) {
    val abundantSet: Set[Int] = abundant.filter(_ < num)
    if (!abundantSet.exists(x => abundantSet.contains(num - x))) {
      notSumAbundant(num + 1, num :: currentList)
    } else
      notSumAbundant(num + 1, currentList)
  } else
    currentList
}

For more information check out this nice write up on Scala collections that is co-written by the creator of Scala, Martin Odersky.


Finding the market price for each order at the time it was placed


My review of your current code is easy to summarize: It's too darn complicated and
makes my head hurt. But don't feel bad, because you're in great company. First
attempts are often like that – even for people who have been doing this
for a long time.
What, specifically, makes it hard to understand? Algorithmic complexity: nested loops
and conditionals, breaks, managing list indexes, and so forth. Whenever you perceive that type of complexity, it often helps to consider whether a more powerful data structure
would simplify the situation (I'm using "data structure" in a very broad sense).
In the rewrite offered below, we will use
a special iterable that allows us to peek at the next value without actually
consuming it every time. That one change drastically simplifies the bookkeeping
inside the main loop, and it also simplifies how we append the needed
remainder of missing values after we exit the loop.
# This is a third party library that is worth knowing about.
from more_itertools import peekable

# Your data, aligned so we can see what is going on.
# When you ask a question, it's a good idea to help your helpers.
xs = [
    'first = 1st', 'second = 2nd', 'third = 3rd', 'fourth = 4th',              'sixth = 6th',
    'first = A',   'second = B',   'third = C',                   'fifth = E', 'sixth = F',
                   'second = W',   'third = X',   'fourth = Y',   'fifth = Z', 'sixth = AA',
    'first = BB',
]

ys = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']

# Python has a builtin concept for missing data. Use it if you can.
# If you cannot, define a constant.
MISSING = None

# The results we want.
# When you ask a question, it's a good idea to provide this.
EXPECTED = [
    '1st',     '2nd',     '3rd',     '4th',     MISSING,   '6th',
    'A',       'B',       'C',       MISSING,   'E',       'F',
    MISSING,   'W',       'X',       'Y',       'Z',       'AA',
    'BB',      MISSING,   MISSING,   MISSING,   MISSING,   MISSING
]

# We will use a peekable iterable for both the Xs and the Ys.
xit = peekable(xs)
yit = None
results = []

# Process all Xs to build the results.
# A Y is consumed each time, and we get a fresh Ys iterable as needed.
# We consume an X only when current X and Y agree.
while xit:
    yit = yit or peekable(ys)
    x = xit.peek()
    y = next(yit)
    val = next(xit).split('= ')[-1] if y in x else MISSING
    results.append(val)

# The results should always contain a full cycle of Ys.
results.extend(MISSING for _ in yit)

# Check.
print(results == EXPECTED)


Project Euler question 2 in CoffeeScript

Better CoffeeScript

First of all, if you're going to use CoffeeScript, then use its full potential and do away with h:

limit = 4000000
sum = 0

[a, b] = [1, 1]

while b < limit
  sum += b if b % 2 is 0
  [a, b] = [b, a + b]

console.log sum

It's nice and easy to read, and I'd use this implementation instead of a recursive one in "real code", but it's still instructive to think about a functional equivalent.

Memoization

What you're looking for is named memoization. The trick is that you should store the values of fib(n) in an array. This allows you to lookup in the array for most cases instead of computing the value again. You'll be able to use fib() in a natural but optimized way.

memo = [1, 1]

fib = (x) ->
    if typeof memo[x]  != 'number'
        memo[x] = fib(x - 1) + fib(x - 2)

    return memo[x]

Now we have a function that compute memo[x] if needed, and returns it for every call. This means that the first call to fib(3) is going to compute it using memo[2] and memo[1], but all subsequent calls are going to be "free".

I can now use this implementation to compute the sum over even values:

fib_sum = (i) ->
    // Initialize i to 0 for the first call
    if i is undefined then i = 0

    return 0 if fib(i) > limit

    if fib(i) % 2 == 0
        return fib_sum(i + 1) + fib(i)
    else
        return fib_sum(i + 1)

You can use a tail-recursive function if you want but this won't help since you're probably going to overflow before doing a stack overflow.

Purely functional from the outside

Now the implementation seems functional but there's still this "memo" array that we would like to hide. Well, closures are the perfect way to achieve this. This is called the "pattern module" in JavaScript. Here's the full code:

fibonacci = (() ->
    'use strict'

    memo = [1, 1]
    limit = 4000000

    fib = (x) ->
        if typeof memo[x]  != 'number'
            memo[x] = fib(x - 1) + fib(x - 2)

        return memo[x]

    even_sum = (i) ->
        if i is undefined then i = 0

        return 0 if fib(i) > limit

        if fib(i) % 2 == 0
            return even_sum(i + 1) + fib(i)
        else
            return even_sum(i + 1)

    return {nth: fib, even_sum: even_sum}
)()

console.log fibonacci.even_sum(); # 4613732

There's no way to know that out fibonacci module uses an array internally, but it's still used and allows for very fast code. Benchmarking show that it's as fast as the iterative version, and takes about 0.02s on my machine.

Automatic memoization?

It turns out that JavaScript: The Good Parts mentions that you can have automatic memoization and uses fibonacci as an example. It can be interesting to try to apply this to our fib_sum, but I'll leave it as an exercise. :)


Although the command pattern you brought in makes it easy to create a 'flexible' Execute method. I wonder if it is really transparant to the ones who read your code.

Perhaps you can combine your two ideas, by implementing a certain ReadOnlyRepository using the command objects. So that the user of your interace keeps using:

repository->Update(SomeEntity);

While the repository implementation does:

repository.Execute(new UpdateCommand());

Consider, if you had to make a change to your later interface. Where would you need to update that in your code? In my suggestion it simply requires you to change it at one place. (since all the other code still uses the 'old' interface).

I hope my post makes sense :)


How to manipulate directories using Python

Enumerate

counter = 1
for repo in git_repo_tags:
  # ...
  print('--Removing the .git folder ' + str(counter) + '/8')
  counter += 1

should be using enumerate:

for counter, repo in enumerate(git_repo_tags, start=1):

String interpolation

print('--Removing the .git folder ' + str(counter) + '/8')

can be

print(f'--Removing the .git folder {counter}/{len(git_repo_tags)}')

The 8 should not be hard-coded.

Pathlib

For basically every one of your directory and file names, and many of your file operations (rmtree being an exception), you should consider using pathlib.Path. For instance, this:

if not os.path.exists('Food-101/images'):
    os.makedirs('Food-101/images')
    print('Created the Food-101/images')

can be

image_path = Path('Food-101/images')
if not image_path.exists():
    image_path.mkdir(parents=True)
    print(f'Created {image_path}')

Path parsing

Rather than this:

name_of_folder = line.split('/')[0]
name_of_file = line.split('/')[1].rstrip()

consider at least unpacking it, i.e.

folder_name, file_name = line.rsplit('/', 1)

But it's better to again use pathlib:

line_path = Path(line)
folder_name = line_path.parent
file_name = line_path.name

Functions

Move logically-related chunks of code to subroutines for better legibility, maintainability, modularity, testability, etc.

Indentation

Use four spaces, which is more standard. You do this in some places but not others.


First of all, calling your super class "Browsers" is wrong, because it doesn't have anything to do with browsers. It is probably a TestBase class, if your Test extends it.
You don't have to have duplicates and you don't have to have a constructor in your base class. Tests doesn't care about what browser it is executed on, so you should handle this information in TestBase class (currently Browsers). Personally I handle it in configuration/properties file. In that case I can switch easily and modify values from continuous integration server (i.e TeamCity).


Your solution looks rather map-happy.

It is important to remember for this task that counting higher than 2 of any encountered letter is needless processing as is any processing on any letter after the earliest positioned unique letter.

Also, doing a complete sweep of the input string may be ill-advised if the input string is of considerable length.

Due to not being as well across .js as others here are, I'll post a humble for loop.

function firstNonRepeatedCharacterPosition(string) {
    for (let char, pos, i = 0; i < string.length; ++i) {
        char = string.charAt(i);
        pos = string.indexOf(char);
        if (pos == i && string.indexOf(char, i + 1) == -1) {
            return pos;
        }
    }
    return -1;
}

console.log(firstNonRepeatedCharacterPosition('abcbebc'));

It does make 3 function calls per iteration, but they aren't heavy ones, there is at most only one pass through the string, and early-return programming is in effect.

Grab the letter at the incremented position.
Find the earliest occurrence of that letter.
Check if there is a later occurrence of the same letter.

The later the unique letter exists (or if there are no unique letters), the more laborious my function is.  On the other hand, if the first letter is unique, then you are finished in just 3 function calls.

p.s. I lack the knowledge to interpret your js code, so I cannot review it beyond saying that it isn't very novice friendly.

After Rotora's challenge, I was doubting myself, so I whacked this little battery of tests together:

function MickMacKusa(string) {
    for (let char, pos, i = 0; i < string.length; ++i) {
        char = string.charAt(i);
        pos = string.indexOf(char);
        if (pos == i && string.indexOf(char, i + 1) == -1) {
            return pos;
        }
    }
    return -1;
}

function RoToRa(string) {
    for (let char, pos, i = 0; i < string.length; ++i) {
        char = string.charAt(i);
        if (string.indexOf(char, i + 1) == -1) {
            return i;
        }
    }
    return -1;
}

let table = document.getElementById("test"),
    row;
for (let i = 1; i < table.rows.length; ++i) {
    row = table.rows[i];
    row.cells[3].innerHTML = MickMacKusa(row.cells[0].innerHTML);
    row.cells[4].innerHTML = RoToRa(row.cells[0].innerHTML);
}

Input	Letter	Index	MickMacKusa	RoTora

abccbcba	  -	 -1

abcbebc	   a	  0

abc	       a	  0

aabbc	     c	  4

abcba	     c	  2

abba	      -	 -1

abaa	      b	  1

aabcbcbca	 -	 -1