First a stylistic note: you should always use at least 2 spaces of indentation for code; 1 space makes it very difficult to read nested statements in particular. PHP most often uses 4 spaces for indent.

Your regular expressions wouldn't need comments to explain them if you gave them meaningful names.

$password_filter1 = '/(?=.*[a-zA-Z0-9]{6})/m';  //Password contains more then 6 char
$password_filter2 = '/(?=.*[A-Z])/m';           //Capital letter
$password_filter3 = '/(?=.*\d)/m';              //A digit

There is also no need for m multiline flag for a password, since passwords shouldn't accept any newline characters.

Compare to:

$has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]{6})/';
$has_a_capital_letter = '/(?=.*[A-Z])/';
$has_a_digit = '/(?=.*\d)/';

You may also consider making them into small functions so they are reusable elsewhere in the code, and if you needed to change them later you would just change them in one place.

function has_a_capital_letter($str) {
    return preg_match('/(?=.*[A-Z])/', $str);
}

//...

if (!has_a_capital_letter($password)) {
    $password_error = "Your password must have at least 1 capital letter";
}

There is no real value in nesting multiple if/else statements inside each other like this, when a simple sequence of if/elseif/else will work just as good. Nesting like that with even simple conditions makes the code quite hard to read, in fact. Nesting like this with more complex operations could lead to serious performance bottlenecks as it cannot break early as easily.

It's also simpler to test for the existence of conditions instead of the lack of them, and just break out of the conditionals as soon as a condition is met.

This is much simpler and cleaner:

if (empty($password & $confirm_password)) {
    $password_error = "You must enter a password";
}
elseif ($password !== $confirm_password) {
    $password_error = "The passwords do not match";
}
elseif (!preg_match($has_at_least_6_chars, $password)) {
    $password_error = "Your password must be at least 6 characters long";
}
elseif (!preg_match($has_a_capital_letter, $password)) {
    $password_error = "Your password must have at least 1 capital letter";
}
elseif (!preg_match($has_a_digit, $password)) {
    $password_error = "Your password must contain at least 1 number";
}
else {
    //If everything is true do this
}

By the way, I think there is a problem with $has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]{6})/m' in that it doesn't truly check for 6 characters, it checks for 6 letters and/or numbers. According to the way your error messages are written, this should be a perfectly valid entry meeting all conditions:

$password = "Hell0!";
$confirm_password = "Hell0!";

Yet your code returns "Your password must be at least 6 characters long" (which of course it is, except that your regular expression removes the ! and all other non-alphanumeric characters). It would be much simpler (and more accurate) to use the built-in strlen() PHP function.

elseif (strlen($password) < 6) {
    $password_error = "Your password must be at least 6 characters long";
}

That is, unless you have requirements that forbid non-alphanumeric characters, which I think would be a terrible idea, since many people use them to make for stronger passwords that are harder to break through brute force.


Function simulating single elevator movement

As a C++ learning exercise, you will benefit from creating an Elevator class in this case. Make it a class that has a the current floor and direction as a data members (those are the current states of the elevator), and a function PlanRoute that gets input floors as input, and returns the output floors.

The h-file will look something like this:

class Elevator {
public:
  Elevator();
  void setCurrentFloor(int currentFloor);
  void setDirection(bool goingDown);
  std::vector<int> planRoute(const std::vector<int>& inputFloors)
private:
  bool goingDown;
  int currentFloor;
}


I'm not sure how to optimize your code, but let's talk about those variable names.

Naming is hard. It's doubly hard in vb.net, because it's case insensitive. That fact makes it difficult not to step on keywords like Field. I don't like recommending this, but without a being able to use fields and field to differentiate from the keywords Fields and Field, you could de-vowel it to flds and fld and still have a variable name that's easier to understand than fd.

dt I get, but what does that date actually represent?

s1,s2,s3? What do those mean? I vaguely understand what s1 is, but then I hit this.

Dim s2 As TimeSpan = TimeSpan.Parse(fd.sg)
Dim s3 As TimeSpan = TimeSpan.Parse(fd.os)

Field.sg and Field.os? Why do we have a stargate address and an operating system stored in those fields?

TL;DR: Stop over abbreviating variable names. They make sense to you (now), but will they make sense to Mr. Maintainer? Remember, that poor confused maintainer could be a future version of yourself.


First of all, when presenting a piece of code to fellow developers, you help them the most by letting them know what your code does and what the inputs and expected outputs are. You immediately start by describing how your code does something, which is a bit confusing.

Regarding your code, I suggest the following:

Both arrSubtitles and subtitles are arrays, but only one has the 'arr' prefix which is confusing. I find it more helpful to name variables according to their role instead of their type. You are splitting subtitles into some arbitrary whitespace delimited tokens, so how about tokens instead of arrSubtitles?
arrSubtitlesSeparate and arrSubtitlesSepMultiDim are bulky, nondescript names. Following above advice, how about time and times?
There is no need to perform a strict boolean comparison === true within your if-clause, your code looks neater by simply omitting that.
Within the loop body, you access arrSubtitles[i] 10 times. To avoid those many lookups and improve readability, you could assign that array element to a temporary variable. Or you use a for ... of loop instead, which iterates over array values instead of array indices.
Replace successive string.charAt concatenations with a single call to string.substr.
Leverage the block scope of const and let instead of using the function scoped var.

Applying those suggestions to your code would result in e.g.

const regex = /[0-9]{2}:[0-5][0-9]:[0-5][0-9],[0-9]{3}/;
const times = [];

for (const token of subtitles.split(" ")) {
  if (regex.test(token)) {
    const time = [
      token.substr(0, 2),
      token.substr(3, 2),
      token.substr(6, 2),
      token.substr(9, 3)
    ];
    times.push(time);
  }
}
console.log(times);

You asked what happens when you don't initialize arrSubtitlesSeparate = [] in the loop body?

Initially you create a single array instance arrSubtitlesSeparate. Then, during each loop iteration, you modify the content of this array and push it onto arrSubtitlesSepMultiDim. So in the end, each index of arrSubtitlesSepMultiDim contains a reference to the same arrSubtitlesSeparate array, similar to this:

arrSubtitlesSepMultiDim = [arrSubtitlesSeparate, arrSubtitlesSeparate, ...];

See also Is JavaScript a pass-by-reference or pass-by-value language?

Now, if we look again at your implementation, we note that you already perform a regex test. We could perform a regex matching instead and get rid of all those redundant string.substr calls. I wrapped this new implementation in a documented function and ended up with:

/**
 * Find and parse all timestamps of type "hours:minutes:seconds,milliseconds"
 * within a given subtitles string.
 * @param {string} subtitles
 * @return {Array} Array of times [hours, minutes, seconds, milliseconds]
 */
function findTimes(subtitles) {
  const regex = /([0-9]{2}):([0-5][0-9]):([0-5][0-9]),([0-9]{3})/g;
  const times = [];

  let matches;
  while (matches = regex.exec(subtitles)) {
    times.push(matches.slice(1));
  }
  return times;
}


Concurrent dependant routines in a gui application

Running non-gui related stuffs using the main event-dispatch(gui-thread) is kind of anti-gui practice.
If first process should be called, and then second process, so it's basically a long synchronous calls (with user prompt between each)
Probably(good practice) is run the first long process using a thread(usually out of event-dispatch/gui-thread).
Meanwhile, the long process could inform the GUI about the process by sending progress events(assuming gui works as a process-progress-listener here).
Now, because the long process is run by a thread, gui is functional, and not freezing, so user could see progress, or control the progress(e.g. abort, etc...)
Once the long thread is finished, ask the gui-thread/event-dispatch for user prompt, and if starting the second long process is a thing, go for it just like first one using a thread.
Overall
Try not to perform excessive non-gui stuffs using gui-thread/event-dispatch. This is actually a good practice.
Try not to perform gui related stuffs(such as updating a progress-bar value/status) using non-gui threads(out of widget/dispatch scope). This may not be valid for all widgets, but usually(possible) any gui change(here like progress-bar change) seems to be ignored.
But actually that out-of-scope thread could not force the main-gui thread to perform a refresh/repaint on target component.
Assuming, the-gui/event-dispatch thread is the guy who sitting next to the widget door, and is waiting for any gui-related requests.
So if a request about updating progress-bar is made correctly by the expected routine, that guy will repaint the target progress-bar since it have to.
But what happens when the request came from out of event-dispatch scope? It's more like getting into the room from windows, rather the door, and the guy next to it.
So technically progress bar will be updated, but might not updated immediately(or at all), since the guy who in charge to keeps ui updated did not realized there is a requests that forces component(s) to get repainted.


K&R2 solution to exercise 1-18 (discarding trailing whitespace and empty lines)

Don't cast the return value from malloc and family - provided there's a prototype in scope (which there is here, due to our #include <stdlib.h>), the void* result will convert to any pointer type.

Always check whether the returned pointer is a null pointer before using it:

wsbuffer = malloc(buffer_size * sizeof *wsbuffer);
if (!buffer) {
    fputs("Memory allocation failure\n", stderr);
    return EXIT_FAILURE;
}

Robust code needs to take extra care when using realloc().  If we write something like p = realloc(p, new_size); then we have a problem when it fails - p is assigned null, and we have nothing pointing to the memory any more (i.e. a memory leak).  The usual pattern looks something like:

void *new_buf = realloc(wsbuffer, buffer_size * sizeof *wsbuffer);
if (!new_buf) {
    free(wsbuffer);
    fputs("Memory allocation failure\n", stderr);
    return EXIT_FAILURE;
}
wsbuffer = new_buf;

Minor things:

Instead of c==' ' || c=='\t', we might consider isspace(c), remembering that this test includes newlines and other whitespace.
We can store whitespace in an array of char rather than int, since we never need to store EOF into that buffer.
The logic might be simpler if use a larger buffer and read a whole line at a time.  Then we just overwrite the start of the last whitespace found in the line, and print it.  That's likely a bit more efficient than our character-at-a-time operation, too.


Could someone check the Minimax Algorithm correctly implemented?

tmp = game[:][:] is not doing what you think it is doing.  game[:] returns a slice of all the rows of game (so a list of columns).  To that, you apply the slice operator [:], which takes the slice of the row list (of columns), and returns a row list (of columns).  In short, game[:] is the same as game[:][:], which is the same as game[:][:][:][:][:].

In particular, tmp is list which contains references to the same column lists as game, so tmp[row][col] accesses exactly the same entry as game[row][col].  You have not created a temporary copy of game; you have created a copy of references to the same column list objects.

As such, you can remove tmp, and just set game[row][col] directly, and set it back to None like you are doing via tmp.

The code x, y = move[0], move[1] seems to be useless, since x and y are never used.

The minimax() function returns the best possible outcome for that player, but doesn’t return the move that corresponds to that outcome.  “You have a guaranteed winning move, but I’m not going to tell you what it is.”

You might want to return the move that corresponds to that outcome.


Good set of code.

Observations

#ifdef structure lacks uniqueness and detection if none are true.  Suggest #elif

#ifdef _WIN32
#elif __APPLE__
#elif __unix__
#else
#error Error Message
#endif

Rather than a differing #if structure in the .c file, suggest a matching one as in #1

//#ifndef _WIN32
//#endif
#ifdef _WIN32
#elif __APPLE__
...

Memory leak.  Should free(filename) before returning NULL.

if ((r = readlink(proclnk, filename, FILENAME_MAX)) < 0) return NULL;

Name-space.  Prefer some naming convention that ties these 3 functions to
their .h file.  Maybe wavutil?

wavutil.h
wavutil_getTmpDir();
wavutil_createSafeFileDescriptor()
wavutil_getPathFromDescriptor();

Since function allocates data, make that clear in the function declaration.  Also document candidate error returns

* ALLOCATES the file path given the file descriptor
* Returns NULL on ...
...
const char* getPathFromDescriptor(int fd);

Suggest error return of NULL instead.  Hoping "/tmp/" exists after failing 3 environment variables it a questionable fix.  At least "./" is sure to exist.  Also the environment variable might not end with /.  May need to check that.

// else return "/tmp/";
else return NULL;
// or
else return "./";

snprintf() is good to prevent overruns, yet if it fails, do not proceed with a runt string.

int len = snprintf(proclnk, sizeof(proclnk), "/proc/self/fd/%d", fd);
if (len < 0 || len >= sizeof(proclnk)) Handle_Error();
if ((r = readlink(proclnk, filename, FILENAME_MAX)) < 0) return NULL;

Minor

Comment inconsistent with code 5 vs. 4?  Could avoid magic number 4.

   // // the 5 is for the length of the suffix ".wav"
   // return mkstemps(flacFile, 4);

   char ext[] = ".wav";
   snprintf(flacFile, FILENAME_MAX, "%sXXXXXX%s", fileRoot, ext);
   return mkstemps(flacFile, sizeof ext - 1);

Prefer right-sizing allocations that start off large.

   char *filename = malloc(FILENAME_MAX);
   ...
   char *p = realloc(filename, strlen(filename) + 1);
   return p ? p : filename;

Curious style change.  Why sizeof() in 2nd line, yet FILENAME_MAX instead of sizeof(flacFile).  Suggest the latter.  Further, not a fan of xxx_MAX when xxx_SIZE is meant.  MAX to me means the maximum number so characters - which is 1 less than size.

char proclnk[PATH_MAX] = {0};
snprintf(proclnk, sizeof(proclnk), "/proc/self/fd/%d", fd);

char flacFile[FILENAME_MAX] = "";
snprintf(flacFile, FILENAME_MAX, "%sXXXXXX.wav", fileRoot);


Given points on a 2D plane, find line that passes through the most points

i think your task was to use the given classes Point and Lineand extend them...

public class Line{

    public Line (Point a, Point b);

    public boolean contains(Point p);

}

thus leaving a quite simple task in your Solution (and pretty easy to read)

Lines lines = getAllLines();//easily iterate over the permutated Point matrix

for(Line line: lines){
    int amountOfPoints = 0;
    for (Point p: points){
        if (line.contains(p) {
            amountOfPoint = amountOfPoint + 1;
    }
}

NOTE

this is just an explanation of OO-Programming, i didn't include the subtaks, e.g. how to get the max of the lines, or how contains() works, but it surely gives a hint on where the questions aims at...


Overriding the Price property in TechnicalBook modifies the behavior of Publication. Which means you've broken the OCP. Besides, what do you expect TechnicalBook.Price to be if you have just set it to 10.0? (Does it even compile when you only override get?)

What you could do is employ the template method pattern:

abstract class Publication
{
    // ...
    public decimal IndividualPrice { get; set; }
    public decimal Price {
        get { return CalculatePrice(); }
    }

    protected decimal CalculatePrice() {
        decimal price = IndividualPrice;
        price += GetAdditionalPrices();
        return price;
    }

    protected virtual decimal GetAdditionalPrices() {
        return 0;
    }
}

public class TechnicalBook : Publication
{
    // ...
    protected override decimal GetAdditionalPrices() {
        return Cd.Price;
    }
}

This makes Publication closed for modification (cannot change price / individual price), but open for extension (can add to price).

(Naming and structure in my example could probably be improved, but it serves the purpose)

The behavior is still possible to modify, though, so an even better solution would be to have some collection or set of rules you can add to, so you don't accidentaly override GetAdditionalPrices without calling base.GetAdditionalPrices().


Pseudoportable C script pattern - follow-up

It can be made even simpler, by arranging for the C program to remove itself when it runs:

#! /bin/bash

# Create a temporary file name for the executable file:
TMP_PROGRAM_FILE="$(mktemp programXXXXXX)"

# Compile the embedded C program:
gcc -o "$TMP_PROGRAM_FILE" -x c - <<- END_OF_SOURCE
#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
    int i;

    puts("Hello, world! I am a pseudoportable C program.");
    for (i = 1; i < argc; ++i)
    {
        printf("Argument %d: %s\n", i, argv[i]);
    }
    unlink("$TMP_PROGRAM_FILE");
    return argc - 1;
}
END_OF_SOURCE

# Run the program delegating all the arguments:
./$TMP_PROGRAM_FILE $@

This will not work under Windows but does work under Linux.  I haven't tested Mac, but believe it will work there, too. The change, of course, is that the C program now deletes itself.


You can do a Switch Statement to reduce the else-ifs you have.

Switch(action)
{
    case "a": Switch(enemyChoice)
              {
              case 2:
                   System.out.println("oohh! and "+pName+" throws a devistating blow into Rocky!");
                   enemyHealth-=10;
                   checkHealth();
              }
              case 3:
                   System.out.println("OH! "+pName+" JUST GOT SMASHED!");
                   enemyHealth-=10;
                   checkHealth();
              }
    case b:
etc....
}

Also is there any need to check health before you take away health? you remove health, then check, then disable play. you aren't alive then die before making an action I assume.


Function for minimum non-zero with multiple additional conditions

Try to use meaningful names. What's names (SelValue, ValOne,...) stands for? It don't give info on their purpose or usage.

Furthermore, you can simplify a lot your conditional branchments, using only this:

If ValOne < 0 Or ValTwo < 0 Then
    SelValue = -1
' remove this following condition to discard case 4
Else If ValOne = 0 Or ValTwo = 0 Then
    SelValue = ValOne + ValTwo
ElseIf ValOne > ValTwo <> NeedMax Then
    SelValue = ValTwo
Else
    SelValue = ValOne
End If

not fully tested, but should do the trick

Edit : fixed case (4), where NeedMax is false and one of values is 0.


Catch all checked exceptions and turn into unchecked exception

default void run () {

There should be no blank after a method name (neither in a declaration not in a call). There are only blanks after if and while to distinguish them visually from method calls.

    try {
        doRun();
    } catch (Error | RuntimeException e) {
        throw e;
    } catch (Throwable throwable) {
        throw new IndexOutOfBoundsException("IOBE");
    }

Really IndexOutOfBoundsException??? What index, what bounds? It should be

    try {
        doRun();
    } catch (Error | RuntimeException e) {
        throw e;
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

It's called exception wrapping. You can't throw e, so you wrap it into a RuntimeException and it can be obtained via getCause. Printing the stack does it, so you lose no information.

    final RunnableEx runnable = () -> {
        try {
            runner.doRun();
        } catch (Error | RuntimeException e) {
            throw e;
        } catch (Throwable ignored) {
            runner.doRun();
        }
    };

The line runner.doRun() makes no sense to me. It failed, so you do it again. Why?

Moreover, it may throw a Throwable.

Moreover, you're repeating what you did above.

You've been already given a workable example in the question:

new Thread(uncheck( () -> { System.out.println("Zzz"); Thread.sleep(1000); })).start(); // Look, no catch (InterruptedException)!


Generator for the collatz conjecture sequence

The only improvement I see here is to divide n by 2 using // (since we are dealing with Python 3.x) and to remove the explicit conversion to int (int(n)):

while n != 1:
    n = n // 2 if n % 2 == 0 else 3*n + 1
    yield n

Also, I suggest you put a single space before and after the multiplication operator in 3*n, so that it becomes 3 * n.

Hope that helps.


Read and write data to/from Serial Port in C#

There are a number of strange things going on here...

First, you have this:

//Buffer with data
byte[] data = HexStringToByteArray(mensage);

//Handle data
comport.Read(data, 0, data.Length);

The first line takes the mensage (message?) and turns it into a byte array, but then you immediately overwrite the data by reading into the same buffer. In essence, you are using HexStringToByteArray simply to create a new array of some length (3 bytes?).

Based on how you are using HexStringToByteArray, it certainly does not take a hex string and turn it into a byte array. mensage and mensage2 contain things other than valid hex characters. Maybe something more descriptive like StringToByteArray or StringToHexByteArray would be better. It does look like you are trying to convert a "hex" string input to byte data, but given the inputs I can't see how you can run this and not get an exception. The other problem with this method is that it assumes you have an input string length divisible by 2, and you are not checking that (nor are your values passed in adhering to that).

Since you are not doing anything with the data and data2 arrays, you are basically using them to flush some data out of the read buffer. I would have to assume that the code you posted is not complete, otherwise you could do something like SerialPort.Flush() instead.

Now, lets look at your variables:

string start = "?";
string carriageReturn = "\r";
string text = string.Empty;

string mensage = "@" + "r" + "\r";
string mensage2 = "@" + "{" + texto + "\r";

I would advise against using the carriageReturn and either call it something like messageDelimiter or just don't use it. It would be akin to defining something like:

int zero = 0;

Zero will always equal zero, so you shouldn't have variables for them. The name text doesn't really help here, you should give it a descriptive name like emptyMessage since it doesn't look like it ever changes. mensage and mensage2 are also not descriptive (or spelled correctly), maybe something like doorOpenQuery and doorCloseCommand. (And in addition, since texto isn't defined, I don't see this even compiling...)

The last problem I see is that you have an un-throttled while(true) loop in your program with no exit conditions other than something throwing an exception. How many times do you want to run this loop? You shouldn't have an unbounded while, you are going to have a not-responding program if you let it run for about 10 seconds.

From what I see I don't believe that this is functioning code. Have you run this through the debugger? If you have functionality problems this probably isn't the StackExchange site for that.


Streamlining button creation and Handlers

The Button control/class has a Tag property of type Object. You could simply pass to that property your strings "1", "2" etc. In this way you would only need one eventhandler where you the read the value of the Tag property back, call the ToString() method and then pass this string as argument to the PrcDash2() method.


There's really not a lot going on in what you've posted, so there's not much to pick apart.  Really the only functional change I'd mention is that there's a MediaController class available that you can use that provides play, pause, and seek functionality (including a standard UI that Android users are familiar with) that you might want to check out.  That said, it's 100% find to use your own UI if that's a design decision and not just the result of being unaware.  Also, you don't update the play/pause UI the first time the `MediaPlayer is started.  Other than that, it's mostly code style and convention issues that I see.

Classes are usually named using PascalCase (you have lowercase).  Also, convention is to use the word "Activity" when extending an Activity, so your radio class should probably be RadioActivity.
The prefix set is generally reserved for setter methods - methods that update a variable value and often do some pre- or post-processing work around that update.  I would probably call setMediaPlayer something like initializeMediaPlayer or startMediaPlayer.
You could break setMediaPlayer into multiple smaller methods.
You probably don't want that whole method body in the try block - figure out what's going to potentially throw and move the rest out.  This is a bit of a nitpick and isn't critical for a fairly small function like this, but it's a good habit to get into.
imb is a bad variable name - it's not clear what kind of object is being referenced.
Your code might be a little easier to read with less nesting.  I'd probably move the functionality in the onClick to its own method, and call that method in the onClick.
Why is the imb variable final and not a member variable?  It's OK to do this, but there doesn't seem to be clear reason - you're using member variables elsewhere.
Again, not a critical issue, but Android convention is to prefix private variables with m, so mediaPlayer would become mMediaPlayer.
Why is setMediaPlayer public?  Always be as restrictive as possible.
isMediaPlayerStarted will default to false so you don't need to set it.
If an error is thrown, do you really want to print the stack trace?  This might be fine if that's what you want, but I suspect that's either the IDE's decision or the result of a copy/paste...  What error might be thrown here?  What could be a possible source?  What do you really want to do if that happens?
If you're not using any ImageButton methods, you don't need to cast it - findViewById returns a View, which has a setOnClickListener method, so the cast doesn't do anything.


Trading Card Game database schema for statistics

I really don't see much to comment on here. The code was easy to read, well structured, and the code style was, for SQL relatively easy on the eyes, and consistent, which is good.

One inconsistency I see is:

create_date TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW(),
delete_date TIMESTAMP WITHOUT TIME ZONE NULL DEFAULT NULL,
last_seen_date TIMESTAMP NULL

yet the image of your schema clearly shows that last_seen_date is also created without the time zone. When I investigated, I found:

  Note: The SQL standard requires that writing just timestamp be equivalent to timestamp without time zone, and PostgreSQL honors that behavior.

So, there is no need to specify WITHOUT TIME ZONE at all, or, if you do, you should do it consistently.

The create_date (or start_date) on all of your tables are defaulted to NOW(), but the columns are still nullable. CreateDate will never be null, and should be created as NOT NULL.

I am suspicious of the type column on card. Columns like that are typically a small domain (only a few values, with many repetitions). That should be normalized out in to a cardtype table, and the type column replaced with a type_id. This will potentially improve the performance and maintainability of the system. Of course, if your type has many different values with few repetitions, the normalization won't make sense.

Similarly, I am sispicious of the version column on deck. This is a value related to the application that does not make clear sense based on what you have presented. I can only guess what it will be used for, but, since the rest of the schema is clear, it stands out as being ... 'obtuse'.

Fnally, I expect that you are missing some indexes.

Postgres will index the primary and foreign key columns, but I suspect indices on player.name, mod.name, and card.name would be good (and consider making things like mod and card names unique....).


Generating random number inside a paralleled loop (openmp)

Generating good random numbers is a hard problem, and generating parallel random numbers is harder. (Consider that you don't want to replicate the same sequence in different threads). You should use a library which provides a parallel random number generator (such as Intel MKL [now free for anyone]). It has an implementation of the generator described in Parallel Random Numbers: As Easy as 1, 2, 3 which may be appropriate.


Making change using the smallest possible number of coins

The following is a bit of variation, exploiting that one does not need to subtract the same coin value one-by-one.

$c = array(100, 25, 10, 5, 1); // $coins
$n = array(  0,  0,  0, 0, 0); // Number of coins.
$i = 0;
while ($amount > 0) {
    $k = floor($amount / $c[$i]); // How many coins
    $n[$i] = $k;
    $amount -= $k * $c[$i];
    // Or shorter: $amount %= $c[$i];
    ++$i;
}

Also, I subtract from the original amount instead of adding to $sum.


First of all, when you are selecting and want to perform mathematics on it you should directly specify what you want done

instead of

Voters.Upvotes * 8 as [EstimatedAddedRep],

it should be

(Voters.Upvotes * 8) AS [EstimatedAddedRep]

And

Voters.Upvotes * 8 / Users.Reputation as [Ratio]

Should be

((Voters.Upvotes * 8) / (Users.Reputation)) as [Ratio]

you should always specify with parenthesis when performing arithmetic in code, because it doesn't always do what you think it will do.

I don't do this with my FROM and WHERE Statements

FROM Users, Voters
WHERE users.id = Voters.Id

I would do this

FROM Users INNER JOIN Voters ON Users.Id = Voters.Id

and leave out the WHERE clause.

For the issue brought up in Chat  you would just need to add it in like this (simple query so not an issue to repeat yourself in the select)

((Voters.Upvotes * 8) / Users.Reputation) AS RepCreated --?????

Check all your Columns and Tables as well, you have some weird casing issues where sometimes you capitalize and sometimes you don't, it was hard to figure out what was right


Shift part of char array to the same array after encountering a delimiter

C's string implementation is null-terminated. Thus, as long as,

one doesn't care about the original string, (this may not be possible if you have a const char *,) and
one has at least one char that one is willing to discard per block, (usually the block delimiter,) to turn into '\0',

one can do this in place without copying. This tokenizing is very common, and string.h from the standard library has functions that will help. For example, strtok, (and thread-safe extension to the ISO C standard, strtok_r,) or non-standard, but strsep is an improvement, (possible implementation.) In this code, this takes advantage that argv is writable and uses it to come up with some strings which are separated by strchr.

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

/** One could probably store this, but printing it is easier. */
static void print(const char *p) { printf("codeBuffer <- %s\n", p); }

/** `str0` is a string that get separated by '!'. */
static void str_sep_bang(char *str0, void (*const callback)(const char *)) {
    char *str1;
    assert(str0 && callback);
    for( ; ; ) {
        if((str1 = strchr(str0, '!'))) *str1 = '\0';
        if(*str0 != '\0') callback(str0);
        if(!str1) break;
        str0 = str1 + 1;
    }
}

int main(int argc, char **argv) {
    int i;
    for(i = 1; i < argc; i++) {
        printf("You passed: %s.\n", argv[i]);
        str_sep_bang(argv[i], &print);
    }
    return 0;
}

This prints out,

bin/stringthing foo\!bar\!baz\!qux \!\!
You passed: foo!bar!baz!qux.
codeBuffer <- foo
codeBuffer <- bar
codeBuffer <- baz
codeBuffer <- qux
You passed: !!.

However, if one needs to store these values, you need space, (an array of char *, same as is passed in argv.) Usually that involves dynamic allocation or static allocation of the maximum size. As well, accessing this list is only valid while the data from the underlying string doesn't change or go out-of-scope; this is why crossing different modules typically involves duplication of the underlying data.


Use extend() instead of append() to add a list to another list, and use the fact that None and empty lists compare as False, while a non-empty list compares as True, and omit the redundant return statement:
def test(x1, x2):
    if x2:
        x1.extend(x2)

As for reducing the number of print statements, prepare a list or tuple with your test cases, and handle them all in a single for-loop:
l = ['tt', 'yy', 'pp']
testcases = [
    None,
    ['hello'],
    ['hello', 'world']
]

for testcase in testcases:
    test(l, testcase)
    print(l)


Instead of multiple echo statements, consider using a here document:

cat <<EOF
-- Testing our implementation of OpenShell --

- If you have any problem in passing a test read the corresponding
- source file to understand what the test is checking
EOF

To echo an empty line, you can write echo without parameters instead of echo.

The flags of echo are not portable. Instead of echo -n, you can use printf.

If you don't need the user input, you don't need a parameter for read.

Parsing the output of ls -l is considered a bad practice.

Instead of this:

./shell < <(echo "...")

You can use a here string:

./shell <<< "..."

Some vertical space (blank lines) can improve the readability of your code.

Putting it all together, your script would be better this way:

#!/bin/bash
cat << EOF
-- Testing our implementation of OpenShell --

- If you have any problem in passing a test read the corresponding
- source file to understand what the test is checking

EOF
printf "********************* PRESS ENTER TO RUN TESTS  ... "
read

echo ls -al openshell.* | ./shell
printf "********************* TEST ALGORITHMS ... "
read

./shell <<< "ls -al|grep open|awk '{print \$9}'"
printf "********************* TEST DONE. YOU SHOULD SEE FILENAMES ABOVE ... "

Update

As per your follow-up question, and as @Mat pointed out, neither <(cmd) nor here-strings will work in dash. To make the last statement work, you could use a here document:

./shell << EOF
ls -al|grep open|awk '{print \$9}'
EOF


I recommend using the Array.prototype methods.

These lend themselves to adopting a functional style of programming.

Functional programming is a lot easier to test, as a pure function always returns the same result and never mutate objects.

const vowels = ['a','e','i','o','u'];
function vowelStringReverse(str) {

    //split the string into an array of chars, that includes their index position
    const strArray = str.split('').map((v,i) => ({
        value: v,
        i: i,
        isVowel: vowels.includes(v)
    }));

    //For just the vowels,
    //Create index position lookup, where the index positions are reversed
    const vowelsReverseIndexLookup = strArray.filter(v => v.isVowel)
    .reduce((acc, cur, i, array) => {
        return {
            ...acc,
            [array[array.length-1-i].i]: cur.value
        };

    }, {});

    //Now iterate through the string, and look up the vowel from the lookup.
    const strReversed = strArray.map((v,i) => {
        if (v.isVowel) {
            return vowelsReverseIndexLookup[i]
        }
        else {
            return v.value;
        }
    });

    return strReversed.join('');

}

console.log(vowelStringReverse('hello'));
console.log(vowelStringReverse('leetcode'));

In this example I've given, if you wanted, you could then pull out the anonymous functions I've declared, and write tests for them:

for example:

const vowelsReverseIndexLookup = strArray.filter(v => v.isVowel)
.reduce(reverseIndexReducer, {});

//elsewhere:

const reverseIndexReducer = (acc, cur, i, array) => {
    return {
        ...acc,
        [array[array.length-1-i].i]: cur.value
    };

};


With the data.table package, you can do a quick join and get the gini coefficient much easier. This solution is also vectorized, so you can call it with something like gini(2000:2004, 'USA') to get the gini coefficients for the USA for years 2000-2004.

It is also good practice to include the data in your function call, so you don't use objects from the global environment within the function call. This function outputs the entire data.table, but you can also just use the gini coefficient as output, if you add [, GINI] at the end.

gini <- function(year, country, data = inequality){
  require(data.table)
  setkey(setDT(data), 'Code', 'Year')[J(Code = country, Year=year),
                                        list(GINI = mean(as.numeric(Gini))),
                                        by=list(Code, Year)]
}


Finding Matches in a Range / Formatting Call to Sub

What you want to do is called refactoring - combining similar methods into a single function.

You have two loops-

 For softwareCol = 0 To 10
 Next softwareCol

 For softwareCol = 0 To 5
      If Not (softwareCol = 2 Or softwareCol = 4)
 Next softwareCol

I don't see an easy way to eliminate those loops.

Let's focus on what you want to combine

If targetSoftware = cell.Value & " " & cell.Offset(0, 1).Value Then
   cell.Rows.Hidden = False
End If
If targetSoftware = cell.Value & " " Then
   cell.Rows.Hidden = False
End If

You can do this in a boolean function -

Private Function NeedsToHide(ByVal targetSoftware As String, ByVal firstValue As String, Optional ByVal secondValue As String = vbNullString) As Boolean
    If targetSoftware = firstValue & " " & secondValue Then
        NeedsToHide = False
    Else
        NeedsToHide = True
    End If
End Function

So now it's just

 For softwareCol = 0 To 10
    'etc
    cell.Rows.Hidden = NeedsToHide(targetSoftware, cell.Value, cell.Offset(0, 1).Value)
 Next softwareCol

 For softwareCol = 0 To 5
    'etc
     cell.Rows.Hidden = NeedsToHide(targetSoftware, cell.Value)
 Next softwareCol


Know the language
Part of being a programmer is being familiar with the language/s you are using. These days languages are changing yearly thus keeping up to date is very important. MDN JavaScript provides a good JavaScript reference. Every now and then its good to peruse the site to keep your knowledge up to date.
Strings
String.slice will slice to the end of the string if you don't include the second argument. Thus there is no need for the variable lastCharPos
If the arguments for String.slice are negative the position of the slice if from the end of the string. eg "abcd".slice(-2) will return "cd"
You can String.split a string using ... (Spread syntax) spread operator. eg[...str].map
Arrays
Array.map creates an array. You do not use the array and so you should have used Array.forEach
Often when using arrays and their iteration functions like map, it forces you to adapt the code to fit the array function's needs, increasing the complexity of the source and at runtime.  You do this twice...

The need to soak the first argument of map map((_, i) => which is a hack in my view.
As you have no control over the number of iterations you are forced to add two statements i !== lastCharPos and i ?  in the ternary expression i ? i : ''

Improving the code.
Always make your code portable by wrapping it in a function
Code should be focused on one task (role) at a time. Because you created the code inline (not a function) you have combined various tasks into one.

Creating the set of strings
Outputting to the console.

As a function you can separate the output from the creation, returning an array of strings that you can then use as needed. eg Output to console.
The Array iteration functions are too cumbersome for what your code does. You can use a while loop and push the built string to an array which you return at the end.
Rewrite
Your function does not output anything if the string length is <= 1. It is unclear if this is just an output requirement. The rewrite will return the input string (as first item in the array) no matter what its size
The string is sliced using a negative index to slice from the end of the string.
I used a while loop but you can also use a for loop
Using while loop
function numeronyms(str) {
    const result = [str], len = str.length;
    var i = 1;
    while (i < len - 1) { result.push(str[0] + (i++) + str.slice(i - len)) }
    return result;
}

Using for loop
function numeronyms(str) {
    const result = [str], len = str.length;
    for (let i = 2; i < len; i ++) {
        result.push(str[0] + (i - 1) + str.slice(i - len));
    }
    return result;
}

Usage
To use the function so that it behaves the same as your code it needs to check the string length.
const str = "qwerty";
if (str.length > 1) { console.log(numeronyms(str)) }

or
const str = "qwerty";
str.length > 1 && console.log(numeronyms(str));

Or just assign the array for use later
const numers = numeronyms("qwerty");


Find max values of all subarrays of specific length

Run rustfmt. It will automatically tell you such things as:

else blocks in Rust belong on the same line as the closing } and opening {
spaces belong around binary arithmetic operators: &a[i + 1 - k..i + 1].

Run clippy. It will automatically tell you such things as:

You are using match for a single pattern. Use if let instead.

Don't specify types of variables if type inference can handle it.
If you don't care about the value of an Option, use is_some / is_none instead of matching on it.
Both branches end with push_back, that shared logic should be pulled out of the conditional.
If all you care about is if the front of the queue is present, all you really care about is if it is empty.
You can continue to simplify by transofrming that into a while let and using break.
I'd create a function (or an Iterator implementation) to separate the algorithm and the driver.

use std::collections::VecDeque;

fn max_of_subarrays<F>(a: &[i32], k: usize, f: F)
where
    F: Fn(&[i32], i32),
{
    let mut deque = VecDeque::new();

    for i in 0..a.len() {
        while let Some(&x) = deque.back() {
            if a[i] > a[x] {
                deque.pop_back();
            } else {
                break;
            }
        }

        deque.push_back(i);

        if i + 1 >= k {
            if let Some(&x) = deque.front() {
                f(&a[i + 1 - k..i + 1], a[x]);
                if x <= (i + 1 - k) {
                    deque.pop_front();
                }
            }
        }
    }
}

fn main() {
    let a = [10, 5, 2, 7, 8, 7];
    let k = 3;

    max_of_subarrays(&a, k, |sub, max| {
        println!("max({:?}) = {}", sub, max);
    });
}

Truthfully, I wouldn't do any of that unless I had a really good reason. Instead, I'd just use the less efficient algorithm but very concise implementation:

fn main() {
    let a = [10, 5, 2, 7, 8, 7];
    let k = 3;

    for (sub, max) in a.windows(k).flat_map(|sub| sub.iter().max().map(|max| (sub, max))) {
        println!("max({:?}) = {}", sub, max);
    }
}

I didn't take the time to benchmark this, but there's no allocation required here, so I'd expect it to be faster than the better algorithm in certain cases.


On new RollingAverage(-1) it throws a NegativeArraySizeException. An IllegalArgumentException with a proper message would be better here since clients should not know that you are using arrays in the implementation.
On new RollingAverageImpl(1).getAverage() it throws an ArithmeticExpression. What about an IllegalStateException here?
If you are using Integer.MIN_VALUE as a special marker value the addData method should not accept it. Just throw an IllegalArgumentException. (I'd consider using Double.NaN here as a named constant, like EMPTY_DATA or just EMPTY.)
Comparing doubles with integers (like point == Integer.MIN_VALUE) might not be precise. See: Why not use Double or Float to represent currency?
If you calculate the new average after every addData call maybe you should cache it and use the cached value in the  getAverageDouble method.
Actually, I'd cache the sum too, and in the addData subtract the old value from the sum (if the array is full) and add the newData to it, then divide it by the number of elements. Maybe there are better algorithms.


It's fairly common to use an auxiliary parameter as an index or accumulator in recursive functions.  If you don't like having the extra function or method "cluttering" the namespace, you can nest it inside the driver like this:

class Solution:

    def letterCasePermutation(self, S):

        def aux(S, i):

            if i >= len(S) and len(S) > 0:
                self.ans.append(S)
                return

            if S[i].isalpha():
                temp = list(S)
                temp[i] = S[i].upper() if S[i].islower() else S[i].lower()
                self.letterCasePermutationAux("".join(temp), i+1)

            self.letterCasePermutationAux(S,i+1)

        self.ans=[]
        self.letterCasePermutationAux(S)

        return self.ans

A common way to recursively process a string, list, or other sequence is to define the base case as an empty sequence which returns a list with with the base case answer.  If the sequence isn't empty, take off the first element of the sequence and recursively call the function with the rest of the list.  Then process the list returned by the recursive call to add back in the first element.

class Solution:
    def letterCasePermutation(self, s):

        # base case the answer is a list with an empty string
        if s == '':
            return ['']

        else:
            ans = []

            if s[0].isalpha():
                # if s[0] is a letter, prepend it to all the answers in the list
                # returned by the recursive call.  First as a lowercase letter
                # and then as an uppercase letter
                for tail in self.letterCasePermutation(s[1:]):
                    ans.append(s[0].lower() + tail)
                    ans.append(s[0].upper() + tail)

            else:
                # if it's not a letter, just prepend it to all the answers in
                # the list returned by the recursive call.
                for tail in self.letterCasePermutation(s[1:]):
                    ans.append(s[0] + tail)

            return ans

Here's an elegant solution using generators to create the permutations lazily:

class Solution:

    def letterCasePermutation(self, s):
        def aux(s, acc):
            if s == '':
                yield acc

            else:
                yield from aux(s[1:], acc + s[0])

                if s[0].isalpha():
                    yield from aux(s[1:], acc + s[0].swapcase())

        yield from  aux(s, '')


A solution to the Journey Planner programming challenge

Your current implementation is a brute force method, that has some hefty space performance problems (you are copying large parts of the journey every step of the way). Note that both the runtime and space costs are exponential in the worst case in this form.

This problem can be solved more elegantly through some of graph theory.
First we note that every location has to be entered the same number of times as it is leaved, except the end and start points which counts as an extra leaving and entry respectively. If this isn't the case then there is no solution, and if it is the case we are guaranteed for there to be a solution.
To find such a solution we can separate the locations into places that have only one way to enter and leave, and then the rest (remember that we have already identified our endpoint based on which place had one place less to leave). For those will multiple ways through, we need to find enough cycles that passes through other locations to have it returned to being a one pass in and out, such that we can have a route enter it, go through the cycles and then leave through the remaining exit.
The algorithm then is as follows:

Calculate the order (amount of flights entering and leaving) of each location.
Determine if it is possible to solve and identify the ending location.
Start from the starting point and go through any combination of journeys until you reach the end location (there is no way to screw yourself over on this one).
While there are still journeys left untaken, connect them in separate cycles, by just starting at any one of its locations and walk until you get back to the starting location.
Combine the results from results from step 3 and 4, by injecting the cycles from step 4 as parts of other routes when those other routes reach a location in such a cycle. Repeat this until there is only one route left, that is the result.

There are different ways to implement this, mainly based on how you deal with storing the information of the journeys, routes and locations. It should be possible to implement the above algorithm in such a way that it only require \$O(E)\$ runtime and extra space, with \$E\$ being the number of journeys.


Subtract multiple columns in PANDAS DataFrame by a series (single column)

There's need to transpose. You can subtract along any axis you want on a DataFrame using its subtract method.

First, take the log base 2 of your dataframe,  apply is fine but you can pass a DataFrame to numpy functions.

Store the log base 2 dataframe so you can use its subtract method. You can also reuse this dataframe when you take the mean of each row.

Finally subtract along the index axis for each column of the log2 dataframe, subtract the matching mean.

log2df = np.log2(my_df)
log2mean = log2df.mean(axis='columns')
log_div_ave = log2df.subtract(log2mean, axis='index')


C program to print a vertical english ruler whose length is given by the user

The task you are solving is quite simple. So I don't think there's any great change possible. Here are a few things:

You might want to consider accepting command-line parameters (argc and argv) to determine the number of dashes and the dash height.

Your variables are poorly named, and not initialized. You have not specified an old version of C, so I'm assuming that you can write to at least the 1999 C standard (known as "C99").

You don't validate your user's input.

You don't need to return 0 from main(). Just "fall off the end" of the function and it will do that automatically.

Your last two calls to printf should be merged.

You might want to write functions (or preprocessor macros) to make the various fractional gradations more clear:
#define DRAW_1_8(HEIGHT) for (int i = 0; i < (HEIGHT) - 3; ++i) printf("-")

then your main loop becomes a series of named statements:
for (int inch = 0; inch < length; ++inch) {
    DRAW_INCH(height, inch);
    DRAW_1_8(height);
    DRAW_1_4(height);
    DRAW_1_8(height);
    DRAW_1_2(height);
    DRAW_1_8(height);
    DRAW_1_4(height);
    DRAW_1_8(height);
}
DRAW_INCH(height, length);

This does serve to make the code a bit clearer, but mainly it serves to reduce repetition. I'll bet there were a few mistakes early on as you adjusted all the n - K parameters, and macros or functions address that issue.


POSIX shell script for generating pseudo-random numbers

Firstly, it's good that you use tput to portably obtain terminal codes if they exist.  Too many shell script authors fail to do that!  We might choose to only evaluate those if we know we'll use them (i.e. inside print_error_and_exit), and there seems little point in setting $bold_red to use only once.
I wonder if the error checking within print_error_and_exit might be overkill.  If you're using it only within this script, you might omit the argument checking (if you made a mistake in the recursive call, you might end up in a worse position than not checking at all!).
It might be worth accepting the arguments to print_error_and_exit in the opposite order (exit code first), to avoid the important part being overlooked at the end of the line.
Some of the if tests are very verbose compared to simply chaining commands with && or ||.  That might be a style decision, but I would certainly reconsider
if command
then
    return 0
else
    return 1
fi

When it's the last line of the function, that simplifies to just
command

(unless you really care which non-zero value indicates failure).
Although we know that $# expands to an integer, and is therefore safe to use without quoting, there's nothing wrong with quoting it as you have (and here on Stack Exchange it helps the prettifier distinguish it from a comment).
I was concerned that shuf might be very inefficient if a large range is selected, but reading the source for the GNU coreutils implementation shows that it manages to avoid building the entire list of numbers to choose from.  Whether other implementations are similarly optimised is left as an exercise.
Modified program
#!/bin/sh

print_error_and_exit()
{
    # check if exactly two arguments have been passed
    test "$#" = 2 || print_error_and_exit 2 "print_error_and_exit(): There have not been passed two arguments!"

    # check that the first argument is a number
    is_this_a_number "$1" || print_error_and_exit 5 "print_error_and_exit(): The argument #1 is not a number!"

    bold=$(tput bold)
    red=$(tput setaf 1)
    nocolor=$(tput sgr0)

    echo "$bold$red$2 Exit code = $1.$nocolor" >&2
    exit $1
}

is_this_a_number()
{
    # check if exactly one argument has been passed
    test "$#" = 1 || print_error_and_exit 2 "is_this_a_number(): There has not been passed exactly one argument!"
    # check if the argument is an integer
    test "$1" -eq "$1" 2>/dev/null
}

# print a number in range $1 to $2, inclusive
random_number()
{
    # check if exactly two arguments have been passed
    test "$#" = 2 || print_error_and_exit 3 "random_number(): There have not been passed exactly two arguments!"

    # check if the arguments are both numbers
    is_this_a_number "$1" || print_error_and_exit 4 "random_number(): The argument #1 is not a number!"
    is_this_a_number "$2" || print_error_and_exit 5 "random_number(): The argument #2 is not a number!"

    shuf -i "$1-$2" -n 1
}


Generic Adapter with search and sort functionality

Here are some suggestions take what you like from it:

You can make BaseModel an interface. This gives the added benefit that your models do not need to extend your abstract class.
In your getFilter method in a code review I'd ask you to put curly braces around your first if.

if (origList == null) {
    origList = new ArrayList<>(itemList);
}
You can instantiate your filter once as a member of the class, rather than instantiating a new one every time the function getFilter is called.
Use collections.unmodifiablelist to protect yourself from unwanted mutations of the original list, when creating or assigning a new list. This is just a precautionary suggestion that has performance implications. Your not mutating when you should not be.


User php class. Should I connect to DB in this class?

Also this class can activate, register and login the user. This means I should connect to DB. Is it normal?

It's up to you and your requirements. Personally I am trying to make all domain specific objects simple as possible and use it only as Value Object. So, in this case all actions such as checking for existance, creation, activation, registration etc should go to another class, for example, UserManager or similar. And in this class I will hold reference to DB and doing all SQL-queries.

Should I make $connect and $dsn variables static?

Again, it's depends from your requirements. But from my point of view -- no, you shouldn't. When you doing this you cannot have two different connections for MySQL and PostgreSQL, for example.
In any case, I suggest to change public modifier to private (or protected) for $connect, $dsn and $connected memebers.


Build all possible phrase pairs from a sentence pair

Repeating work

You should move all of the code that computes enPhrase to before the deLoop.  There is no need to recompute enPhrase each time you modify de2.

Furthermore, when you compute dePhrase, you can do so by appending the next word deSentence[de2] to the current dePhrase.  Right now you reconstruct all of dePhrase in the inner loop, making it an \$O(n)\$ operation when it could be an \$O(1)\$ operation.

Get rid of loop labels

You can get rid of the loop labels if you precalculate the proper end of the loop.

Use StringBuilder

It's more efficient to use a StringBuilder to concatenate strings rather than using the + operator.

Rewrite

Here is a rewrite showing the above changes:

StringBuilder enPhrase = new StringBuilder();
StringBuilder dePhrase = new StringBuilder();

for(int en1 = 0; en1 < enSentence.length; en1++) {
  int en2Max = Math.min(enSentence.length, en1+maxPhraseLength);
  for(int en2 = en1; en2 < en2Max; en2++) {
    if (en2 == en1) {
      enPhrase.setLength(0);
    } else {
      enPhrase.append(" ");
    }
    enPhrase.append(enSentence[en2]);
    for(int de1 = 0; de1 < deSentence.length; de1++) {
       int de2Max = Math.min(deSentence.length, de1+maxPhraseLength);
       for(int de2 = de1; de2 < de2Max; de2++) {
         if (de2 == de1) {
           dePhrase.setLength(0);
         } else {
           dePhrase.append(" ");
         }
         dePhrase.append(deSentence[de2]);

         System.out.print(enPhrase.toString());
         System.out.print(" - ");
         System.out.println(dePhrase.toString());
       }
     }

  }
}


forever.sh - should keep a process alive forever

By quite, you mean quiet, I think.  You also have a typo with "runnig".

The script would be better self-documented if you put the about and help functions first.

In help, instead of echoing $1, which may be a path, it would be more conventional to echo just the basename.

It would be more elegant for the respawn function to accept the command as a parameter rather than using the $myprocess global variable.  "Process", to me, implies a particular instance, i.e. a running program with a PID, so I'd rename myprocess to command.  You only need to execute date if you're actually going to print a log message.  I'd rearrange the conditions to emphasize how to exit the loop and to reduce nesting.

respawn() {
    command="$1"
    while true; do
        $command
        exit_code=$?

        if [ $exit_code -eq 0 -a $force -ne 1 ]; then
            break
        elif [ $quiet -ne 1 ]; then
            echo "`date +"%Y-%m-%dT%H:%M:%S%z"` | service $command exited with code $?. Restarting after ${timeout}s." >&2
        fi
        sleep $timeout
    done
}

In the argument parser, the --help and the -h conditions are identical.  You should write

case "$1" in
    "--help"|"-h")
        help "$0"
        break
        …

Note that double-quoting variables is a good habit.

I don't believe that the [[ $2 =~ '^[0-9]+$' ]] test is available in traditional Bourne shell.  If portability is a concern, you could write the not-quite-equivalent test

case "$2" in
    [0-9]*) timeout=$2 ; shift
    ;;
esac
shift


Style

I'm sorry for making it personal here, camelCase, but the preferred styling for function names is that they're, well, camelCased. (Apologies for the bad pun). So not GetBinarySum, but getBinarySum.

Removing the Operations class

I think your approach for implementation of Operations is flawed.

You're taking two Strings, converting them to numbers, performing a simple operation and converting it to String again.

This by itself is not a problem, but...

        System.out.println("Sum:        " + operation.GetBinarySum(binOne, binTwo));
        System.out.println("Difference: " + operation.GetBinaryDiff(binOne, binTwo));
        System.out.println("Product:    " + operation.GetBinaryProd(binOne, binTwo));
        System.out.println("Quotient:   " + operation.GetBinaryQuotient(binOne, binTwo));

Here you're doing the following:

read two Strings
convert to ints
sum
convert to binary string
print
convert to ints
diff
convert to binary string
print
convert to ints
prod
convert to binary string
print
convert to ints
quotient
convert to binary string
print

If you instead converted the Strings directly after reading, you could do input validation per input ("hey, you entered a 2 for your second binary number!"), and you'd save on doing all this conversion. You'd convert once, do the math, convert back 4 times (4 different results), and done.

Something like this:

read two Strings
convert to ints
sum
convert to binary string
print
diff
convert to binary string
print
prod
convert to binary string
print
quotient
convert to binary string
print

Here's an implementation without error handling:

        int left = Integer.parseInt(binOne, 2);
        int right = Integer.parseInt(binTwo, 2);

        System.out.println("Sum:        " + Integer.toBinaryString(left + right));
        System.out.println("Difference: " + Integer.toBinaryString(left - right));
        System.out.println("Product:    " + Integer.toBinaryString(left * right));
        System.out.println("Quotient:   " + Integer.toBinaryString(left / right));

And poof! The entire Operations class is gone.

Why have an Operations class

Now, if this were some super advanced calculator which has to do more than just do basic math, it'd help to have the Operations class.

For example, "count all the positive bits in the number" or "detect if this binary number is a square". Then you'd be better served by an operations class that takes int(s) and returns int or boolean. You can later convert this to a String. If you write the implementations like that, your BinaryOperations (which needs a better name) class would be responsible for handling input and output (Like the screens and the buttons of a calculator) and the Operations class would be responsible for doing the actual calculating.

Consider why the Java creators made a java.lang.Math class that takes integers, not Strings and it should be easier to understand how to split responsibilities.

About use of Integer.parseInt with radix

Use built-ins when you can.

Built-ins apply to a larger populace than your custom code. Built-ins have been tested by the people who create the Java language. And above all, built-ins don't require you to implement them yourself.

When the resulting code is written faster, has a greater chance of being correct and uses components people are familiar with, why wouldn't you use built-in functions?

Oh, and in case you forgot what they do, they come with documentation too. So it's easy to remind yourself of how the built-ins work. Custom functions require you to re-read the code if you've forgotten and there's no documentation.


I think this is a bug:

if (current->size == nblocks)
{
    //we've found an exact match, remove the chunk from the free list
    if (prev == NULL) //remove the first chunk
        _dTail = NULL;
        ^^^^^^^^^^^^^^^
        You are just removing the head of the list
        Not NULL(ing) the list.
        I think the line should be:

        _dTail = current->next;

    else
        prev->next = current->next;
    return current + 1;
}

The only thing I don't like is:

unsigned short next; //in blocks of sizeof(Header)

This because you have to keep doing maths to covert it to/from a pointer. I think your code would become much simpler if you just convert this too:

Header* next; // next block in list

I would also remove the assert:

assert(nbytes % sizeof(Header) == 0);

and replace it with code to move the size up.

if (nbytes % sizeof(Header) != 0)
{
    nbytes += (sizeof(Header) - (nbytes % sizeof(Header)));
}

I think you can simplify your code by quite a bit by using sentinel values on your list. See this answer about lists read the bit about sentinals and how it makes things easier.


Emitting multiple States for Single Input using ViewModelType architecture

Well, the fact that the result of the network request is needed in the next network request means you have a cycle which mean you have to have a subject of some sort. Also, you have to maintain state which implies a BahviorSubject rather than a PublishSubject.
That said, whenever you have an onNext inside a subscribe, there is likely a cleaner way.
class MoviesViewModel: ViewModelType {

    struct Input {
        let fetchMovies: Observable<Void>
    }

    struct Output {
        let movieSection: Driver<MoviesViewModelState>
    }

    private let repository: SyncRepository
    private let disposeBag = DisposeBag()

    init(repository: SyncRepository) {
        self.repository = repository
    }

    func transform(input: Input) -> Output {
        let state = BehaviorSubject<[String]>(value: [])

        let movies = input.fetchMovies
            .withLatestFrom(state)
            .share(replay: 1)

        movies
            .map { $0.count }
            .flatMap { [repository] in repository.fetchNames(for: $0) }
            .withLatestFrom(state) { $1 + $0 }
            .bind(to: state)
            .disposed(by: disposeBag)

        return Output(
            movieSection: Observable.merge(
                movies.map { $0.count == 0 ? .loading : .loadRemaining },
                state.map(MoviesViewModelState.loaded)
            ).asDriverOnErrorJustComplete()
        )
    }
}

One of the interesting things to note is that the BahviorSubject does not need to be a property of the class. The bind will capture the subject for you.


While I think this is a very solid foundation, I think you could expand this to make it easier to use.

The first thing which caught my eye was the possibility to make a file handle open longer than necessary. You have already implemented the functionality, but to have the handle closed before the script is terminated is a responsibility of the developer. I would add a __destruct() magic method which checks if the file handle has been closed when the object is out of scope.

public function __destruct() {
    if(is_resource($this->handle)) { // Property name changed, see next.
        $this->close();
    }
}

The next thing is to provide a default $mode. As this class would mainly be used to read the file you could easily set a default value. As of now your code does not utilize any other functionality provided by the different file handle modes, so this should not change anything, other than making your class easier to use.

public function __construct($filename, $mode = 'r') {...

While we are at the constructor I would also rename your property $this->file into $this->handle and save the opened file name in a separate property. This is to write better error messages.

private $file;
private $handle;

public function __construct($file, $mode = 'r') {

    if(!is_string($file)) {
        throw new InvalidArgumentException('Parameter $file must be a string. Provided type: ' . gettype($file));
    }

    if(!is_file($file) || !is_readable($file)) {
        throw new RuntimeException('The provided file could not be opened for reading. File: ' . $file);
    }

    $this->file   = $file;
    $this->handle = fopen($file, $mode);
}

I would also write some error checking. The most obvious place something bad could happen is when opening the file handle. If you first make sure the file actually exists and throw a well written exception if not, you will save yourself some time when errors occur.

The next place I think could use some error checking is when you are reading a line using fgetcsv() in method getCSV(). If an error occurs it returns false, but the current state of the code is completely unaware this may have happened. A simple check to see if it returned false and then throw an exception would suffice.

public function getCSV($mode)
{
    $value = fgetcsv($this->handle, $mode);

    if($value === false) {
        throw new RuntimeException('Encountered an error while reading CSV file: ' . $this->file);
    }

    return $value;
}

Misc (naming)

I feel like the name of the class is somewhat misleading. If I only look at the like name I might also get the impression I can save values into the specified file. Consider changing the name to reflect its exact behavior. I would consider something like ReadCSV sufficient. I also think this is true for the method getCSV(). Do I read the entire file or just one line? It can be hard to determine just by looking at the name. I would rename it to readLine(). This name also skips the CSV part, as the class name states its associated with a csv file, so it should not come as a surprise.

I also have a little trouble understanding your argument $mode in the method getCSV(). If you look at the documentation for fgetcsv() it has more than one optional parameters, but none named $mode. Consider changing this to the same names, as this would make it easier to understand for other developers (or yourself in six months) who knows the method signature or looks at the documentation.

You should also consider writing documentation using the DocBlock feature. This can help reduce confusion when argument names are ambiguous and provide a short description of the behavior of the method as well as which exceptions it can throw.

Additional

You could also write methods for reading the entire file. A method that looks something like the following could be useful.

public function readAll()
{
    $array = [];

    while(($columns = fgetcsv($this->handle)) !== false) {

        $rows = count($columns);

        for($i = 0; $i <= $rows; $i++) {
            $array[] = $columns[$i];
        }

    }

    return $array;
}

Hope this helps. Please keep in mind none of this code has been tested.

Happy coding!


First off, both Grade and Class (GradedClass to avoid confusion with java.lang.Class) make sense as enums.

enum Grade {
    A(4),B(3),C(2),D(1),F(0);

    private final int value;

    Grade(int value) {
        this.value = value;
    }

    int getValue() {
        return value;
    }
}

enum GradedClass {
    ONE, TWO, THREE, FOUR, FIVE, SIX;

    @Override
    public String toString() {
        return "class " + (ordinal() + 1);
    }
}

This will allow a much simpler calculation loop :

    public double calculateGpa() {
        return calculateTotal() / GradedClass.values().length;
    }

    private double calculateTotal() {
        double total = 0d;
        for (GradedClass gradedClass : GradedClass.values()) {
            Grade grade = userInterface.askGradeFor(gradedClass);
            total += grade.getValue();
        }
        return total;
    }

Note that I've hidden away the scanner behind a UserInterface interface, in order to separate calculation from UI code.

It's implemented by the ConsoleUI class :

class ConsoleUI implements UserInterface {
    Scanner myScanner = new Scanner(System.in);

    @Override
    public Grade askGradeFor(GradedClass gradedClass) {
        System.out.println(MessageFormat.format("What is your grade for {0}?", gradedClass));
        String input = myScanner.findWithinHorizon(".", 0);
        return Grade.valueOf(input.toUpperCase());
    }

    @Override
    public void presentGpa(double gpa) {
        if (gpa > 3d) {
            System.out.println("Great job, you're on your way to success.");
        } else if (gpa > 2d) {
            System.out.println("You did OK, but better than average.");
        } else {
            System.out.println("You didn't do too well. You should look into getting a tutor.");
        }
    }

}

The Main class simply ties everything together :

public class Main {

    public static void main(String[] args) {
        UserInterface ui = new ConsoleUI();
        GpaCalculator gpaCalculator = new GpaCalculator(ui);

        double gpa = gpaCalculator.calculateGpa();
        ui.presentGpa(gpa);
    }

}


RSA algorithm implementation in Python 3

I think your Modular Inverse implementation is slow. We can apply this Extended GCD algorithm recursive implementation which shows quite a dramatic speed improvement (at least on my machine):

def egcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = egcd(b % a, a)
        return g, x - (b // a) * y, y

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

Here is a simple benchmark for some a and m which have a modular inverse of 16013:

In [24]: a = 108 ** 151

In [25]: m = 22499

In [26]: %timeit modinv_OP(a, m)
100 loops, best of 3: 11.2 ms per loop

In [27]: %timeit modinv_new(a, m)
100000 loops, best of 3: 5.62 µs per loop

I also wonder if adding an LRU cache via functools.lru_cache() would make an impact - probably not, but please experiment with that.

Some other improvements:

you can avoid converting s to a list in order to iterate character by character:

''.join(str(chr(encrypt_block(ord(x)))) for x in s)

I've also switched to a "lazy" join when joined from a generator.
if on Python 3.6+, you can use f-strings for your print messages


Sort Stack using just an additional stack

It's easier if you define your own Stack type, as the Scala Stack is a collection type which makes it a bit heavyweight.

A stack is either an Empty stack or an element (top) pushed onto a stack (pop):

// Define a simple immutable stack datatype.
trait Stack[+T]
object Empty extends Stack[Nothing]
case class Push[+T](top : T, pop : Stack[T]) extends Stack[T]

We can sort a stack by inserting each element onto a sorted stack. The insertion is done by popping the stack until we find the right position, and then rebuilding the stack when the call-stack returns.

object StackSort {
    // Sort a stack using insertion-sort.
    def sort[T](s : Stack[T])(implicit ord : Ordering[T]) : Stack[T] =
        s match {
            case Empty => s
            case Push(top, pop) => insert(top, sort(pop))
        }

    // Insert an element into a sorted stack.
    def insert[T](x : T, s : Stack[T])(implicit ord : Ordering[T]) : Stack[T] =
        s match {
            case Push(top, pop) if (ord.lt(x, top)) => Push(top, insert(x, pop))
            case _ => Push(x, s)
        }
}

A simple test:

object Test {
    import StackSort._

    def main(args : Array[String]) : Unit = {
        val test = Push(3, Push(1, Push(2, Push(5, Empty))))
        println(test)

        val sorted = sort(test)
        println(sorted)
    }
}

which outputs:

Push(3,Push(1,Push(2,Push(5,Empty$@45c8e616))))
Push(5,Push(3,Push(2,Push(1,Empty$@45c8e616))))


Iterating lists and updating dictionary for corresponding match logic improvement

Considering DRY principal, this

if not conflicts.get(user):
    conflicts[user] = [
                (
                    contribution.title,
                    contribution.url,
                )
                for person in contribution.person_links
                if user.affiliation in person.affiliation
            ]
else:
    conflicts[user] += [
                (
                    contribution.title,
                    contribution.url,
                )
                for person in contribution.person_links
                if user.affiliation in person.affiliation
            ]

can and should be replaced with a defaultdict:

from collections import defaultdict

conflicts = defaultdict(list)
...
for contribution in contributions:
    conflicts[user].extend((contribution.title, contribution.url)
                           for person in contribution.person_links
                           if user.affiliation in person.affiliation)

Or at least take advantage of dict.setdefault (while preferring a dict literal over a call to dict to save method look-up time):

conflicts = {}
...
for contribution in contributions:
    conflicts.setdefault(user, []).extend((contribution.title, contribution.url)
                                          for person in contribution.person_links
                                          if user.affiliation in person.affiliation)


Is it worth to use if-else statement as Java optional pattern?

My first instinct is that your code is a pretty “cool” way to rewrite if else statements, but I don’t think it gains you too much. If you have massive amounts of if trees and want to make them more readable, I would consider using polymorphism to your advantage or, when appropriate, strategy pattern.

If you want some help refactoring a certain if tree please feel free to post the code and we can help.

There are often, IMO, two big reasons to make a new abstraction.

1) to decrease the mental load on the maintainers of this code or

2) to increase the ability to add new features in the future.

Both of these are, of course, related. My question is, and feel free to comment below, does your if abstraction decrease maintainer mental load through simplicity or brevity and/or does your if abstraction improve the ability to add new features in the future? If not then you need to consider why you are doing it in the first place.


Generally, it is often not a good idea to hardcode values. For example, take a look at this piece of code. It won't work correctly from 2021 onwards:
if input_year <= 0 or input_year > 2020:
    print("don't you know your birthday??")

Better do it like this:
date = datetime.now()
current_year = int(date.year)

if input_year <= 0 or input_year > current_year:
    print("don't you know your birthday??")

This will make your program work in future years without the need to change the value for the current year manually.


Since none of these classes have private members, they can be structs instead.  As such, you'll no longer need to explicitly give them public inheritance.
Consider making the magic number 42.f a constant so that its intent is known.
This is specific to Visual Studio, thus is non-portable:

int _tmain(int argc, _TCHAR* argv[])

It should be changed to this to fit the standard:

int main(int argc, char* argv[])

In your various executeTask() functions, I believe you're meaning to pass by const&, not just by reference.  You're not modifying the argument, so const is best with them.


CLP(FD) labeling on possibly infinite domains

Before discussing correctness, efficiency and alternative approaches, I first have three smaller suggestions to simplify the predicate a bit:

Its seems I2 is nowhere really needed, you can always simply use J instead.
for  J2, I would stick to CLP(FD) constraints like: J2 #= J*10.
instead of (\=)/2, I recommend to use dif/2.

These changes make the code a bit easier to read and more uniform, and put us into a better position to discuss the remaining issues.


While the logic of this:

for (int i = 0; i < workOrders.Count; i++)
{
    if (workOrders.Count - 1 > i)
        reportObj.Count += workOrders[i].CreatedOn.DiffDays(workOrders[i + 1].CreatedOn);
}
reportObj.Count = reportObj.Count / row.count;

is valid.  I think the for loop might not be necessary.  You should be able to take the difference from the first to last:

reportObj.Count = workOrders[0].CreatedOn.DiffDays(workOrders[workOrders.Count - 1].CreatedOn) / row.count;

In looking at the rest of that method it looks like the LINQ queries can be simplified quite a bit.  Something like this should work:

public List<ReportVM> DelayReasonAverage()
{
    return (from DelayReason dr in _delayReasons
            let row = new
            {
                delayId = dr.Id,
                delayTitle = dr.Title,
                workOrders = dr.WorkOrders.ToList(),
                count = _delayReasons.Count()
            }
            orderby row.count descending
            let reportObj = new ReportVM()
            {
                DelayTitle = row.delayTitle,
                Count = (int)Math.Round(row.workOrders[0].CreatedOn.DiffDays
                (row.workOrders[row.workOrders.Count - 1].CreatedOn) / (double)row.count)
            }
            select reportObj).ToList();
}

I noticed your post has this method as void, but it's creating a list, so I changed the signature to reflect that.  I also changed the way the average is calculated, by using Math.Round to get a more accurate reflection of the actual average.


I'll add my small contribution even though I'm not really a Python developer (hopefully some day). I've taken your update method and tested it on my computer (desktop, i3-4360@ 3.70GHz × 4 ), without the SDR bit.  And my intuition was right!

Like in most languages allowing you to do it, don't ever do that:

self.fft_data = np.append(self.fft_data, self.fft_data_temp)

The reason is pretty simple: your array does not have a predefined size, so for each call to append, it has to re-allocate the memory to fit the new size. And that's terribly slow.

Let's talk numbers. Without this line of code, doing the FFT and converting the data to dB takes 300ms on my computer. Adding that line, it almost reaches 9s.

So now that we have found this, what to do about it for your application ? It seems that you would like to display the spectrum from 50MHz to 1750MHz, by decomposing it into signals with a 1MHz bandwidth. And for each slice, you generate 4096 samples. I don't know what kind of display you have, but displaying 4096 * 1700 FFT bins is gonna be difficult (especially in a 1000*600 window). You should restrict the size of the spectrum you want to display at once. And speaking just about bands, displaying the end of the HF band, the VHF band and part of the UHF band is not really gonna be interesting. Mostly because you're gonna have trouble finding an antenna that can cover all these bands simultaneously.


Printing in a Function

A function should really only be doing one thing. Yours calculates and prints. This makes it hard to reuse the function, and it also slows it down. Collect the result inside the function (ideally using a StringBuilder for performance reasons), return the result, and print it elsewhere.

Style

Your indentation is off, which makes your code hard to read. You can fix this easily with any IDE.

Duplication

Your else if and else blocks contain some duplication. You could calculate the value you pass to PSD in there, and call System.out.println and PSD outside, only once.

With these points, your code might look like this:

public static String PSD(int x, StringBuilder result) {
    if (x == 1) {
        result.append(x);
        return result.toString();
    }

    int value;
    if (x % 2 == 0) {
        value = x / 2;
    } else {
        value = (x * 3) + 1;
    }
    result.append(x);
    result.append("\n");
    return PSD(value, result);
}

Recursive Functions

Recursive functions generally perform worse than iterative approaches. An iterative approach might look like this:

public static String PSD(int x) {
    StringBuilder result = new StringBuilder();
    while (x != 1) {
        result.append(x);
        result.append("\n");
        if (x % 2 == 0) {
            x /= 2;
        } else {
            x = (x * 3) + 1;
        }
    }
    result.append(1);
    return result.toString();
}


Finding the count of negative sub-arrays for a given array

Simplifications

If you look at your main loop:

    int sum = 0, count = 0;;
    for(int i = 0; i < T; i++){
         sum = 0;
         sum += arr[i];// If the number itself is negative count++
          if(sum < 0){
                count++;
            }
        for(int j = i + 1; j < T; j++){
            sum += arr[j];
            if(sum < 0){// If the most recent sum is -ve, count++
                count++;
            }
        }
    }

you can see that there are two blocks of code that do the same thing.  You can remove one block by noticing that starting the j loop at i instead of i+1 will do the initial check of the number itself.  Another thing you could do is move the int sum declaration inside the for loop.  So the final result would look like this:

    int count = 0;
    for (int i = 0; i < T; i++) {
        int sum = 0;
        for (int j = i; j < T; j++) {
            sum += arr[j];
            if (sum < 0) {// If the most recent sum is -ve, count++
                count++;
            }
        }
    }

Complexity

As far as your complexity question, I don't believe that you can solve this problem with better than an \$O(n^2)\$ solution, so your two loops seem fine.


PHP PDO Class with multiple Select Efficiency and speed

The most important thing you have to learn about classes: every method should be responsible for one task only. Means a method that gets you a count should return you a count, not some HTML.

Two other minor improvements would be a better SQL formatting, so anyone could actually read it and a nice helper function that exists in PDO, fetchColumn():

So your methods should be like

public function getCount($sq,$bkid) {
    $sql = "SELECT COUNT(sentence)
            FROM sentence, chapters, books
            WHERE MATCH(sentence) AGAINST (:q IN BOOLEAN MODE)
                AND chapters.book_Id = books.book_Id
                AND sentence.chapter_Id = chapters.chapter_Id
                AND books.book_Id = :bk"
    $sth = $this->PDO->prepare($sql);
    $sth->execute(array(':q' => $sq, ':bk' => $bkid));
    return $sth->fetchColumn();
}

Whereas for the HTML formatting there should be another method/function. Let me suggest to you something like this:

function getLink($title, $count, $parameters)
{
    if ($count)
    {
        $qs = http_build_query($parameters);
        $title = htmlspecialchars($title);
        return "$title$total\n";
    }
}

it could be used like this:

$count = $t->getCount($search, 11);
echo getLink("Book 1", $count, ['id' => 11, 'q'=> $search]);

Here, as you can see, a handy http_build_query() would take care of encoding your keys and values.


SIMD Finding the maximum Euclidean distance to origin (c++)

The most important part of that code, the vector loop, is held up by the loop-carried dependency through vmaxps. vmaxps on eg Skylake takes 4 cycles (other modern Intel processors are similar, but AMD Ryzen is substantially different), limiting the loop to run one iteration per 4 cycles (in steady state), which leaves a lot of available throughput unused. Optimistically, in terms of throughput the expectation is 1 iteration every cycle, 4 times as much. Therefore, unroll the loop by 4, using multiple accumulators:
  // initialized max0, max1, max2, max3 as appropriate
  for (i = 32; i + 32 < len; i += 32) {
    a = _mm256_loadu_ps(x + i);
    a = _mm256_mul_ps(a, a);
    b = _mm256_loadu_ps(y + i);
    b = _mm256_mul_ps(b, b);
    max0 = _mm256_max_ps(max0, _mm256_add_ps(a, b));
    a = _mm256_loadu_ps(x + i + 8);
    a = _mm256_mul_ps(a, a);
    b = _mm256_loadu_ps(y + i + 8);
    b = _mm256_mul_ps(b, b);
    max1 = _mm256_max_ps(max1, _mm256_add_ps(a, b));
    a = _mm256_loadu_ps(x + i + 16);
    a = _mm256_mul_ps(a, a);
    b = _mm256_loadu_ps(y + i + 16);
    b = _mm256_mul_ps(b, b);
    max2 = _mm256_max_ps(max2, _mm256_add_ps(a, b));
    a = _mm256_loadu_ps(x + i + 24);
    a = _mm256_mul_ps(a, a);
    b = _mm256_loadu_ps(y + i + 24);
    b = _mm256_mul_ps(b, b);
    max3 = _mm256_max_ps(max3, _mm256_add_ps(a, b));
  }
  max0 = _mm256_max_ps(_mm256_max_ps(max0, max1), _mm256_max_ps(max2, max3));

Since the total unroll factor is so high, it becomes more interesting to try to eliminate the "scalar epilog" (the scalar loop after the main loop), for example by using the "step back from the end"-technique in which when i + 32 < len becomes false, i or the pointers x and y are adjusted so that an iteration of the main loop (or a duplicate of it) exactly handles the remaining part of the data, without reading beyond the end of the arrays. That last iteration will overlap somewhat with the second-to-last iteration, but that is OK in this case because the maximum of all results will be taken anyway, and having some duplicates won't affect that maximum.


Am I using C++ pointers and references correctly?

I'm not sure whether this should be reviewed yet or not.  I can't decide what critiques are things that you haven't learned yet but will, and things that you haven't learned yet and might not.  (Also, there's a handful of errors that should have been found with basic testing.)

Anyway here's a few things that jumped out at me:

There's no notion of const correctness at all in your code
system("pause") is bad -- it's slow, and implementation dependent

if you want to see the output, run it in a shell directly instead of using system("pause") as a hack

When pointerLastName is NULL, string LastN = *pointerLastName; is undefined behavior and will probably crash.
if(LastN == "NULL" ) makes no sense

a NULL pointer being dereferences does not turn into the string "NULL" -- it crashes (typically)

Your do {} while() loop in the second program is broken
using namespace std; pollutes the global namespace.  It's typically better to just qualify it directly like std::string or import specific things using std::string;.

In small, simple programs, it tends to not matter.  It can become a bad habit though.
#include "iostream" should be #include <iostream> -- I'm actually a bit surprised that compiles.

Also, for what it's worth, I wouldn't use pointers in either of these two programs.  References are a better choice.  Obviously this is a learning exercise though, so this critique doesn't really apply.

Based on our comments back and forth, there seems to be some confusion surrounding pointers.  I'm not sure if it's me misunderstanding what your saying, or a misunderstanding of pointers, but either way, I figure I'll elaborate a bit.

if(LastN == "NULL" )

That is checking if LastN is equal to the string "NULL".  That is not the same thing as checking for a NULL pointer:

string* pNullStr = NULL;
string nullStr = *pNullStr; //undefined behavior (almost certainly a crash)

The only way a string is going to have a value of NULL is if it is actually set to NULL:

string ns = "NULL";
if (ns == "NULL") {
    //this will happen
}

In other words, your userNames function isn't prompting the user for a last name only "if the caller passes in a NULL pointer for the last name" (as your instructions say).  What it's doing is prompting for a last name only if the caller passes in a string (not a pointer to a string) equivalent to "NULL".

Based on your code, the only way a last name is going to be prompted for is if you type "NULL" in when prompted for a last name (in the main code).

Perhaps this was by design, but it directly contradicts your exercise instructions.

Also, while I'm at it with the editing, if you wanted to be really careful, you could check all of the input operations.  In fact, really you should always check, but in a program this simple, it would be a bit of a pain.

To clarify:

cout << "FIRSTNAME: ";
cin >> firstName;

That can fail.  What if the user writes EOF or if the user pipes in an empty file?  That means the read is going to fail.

if (!(std::cin >> firstName)) {
    std::cerr << "Fatal error: reading last name failed";
    return EXIT_FAILURE; //(defined in cstdlib)
}

On a stylistic note, not sure why I didn't spot this before: if your loop in userNames is actually what you meant it to be, you can write it much more cleanly:

while (lastN == "NULL") {
    std::cout << "Again what is your last name? ";
    std::cin >> lastN; //Once again, this should be checked
}


Recursive Insertion in Hash Table (Linear Probing)

When commenting to describe a function's purpose, it's more common to have them on top of the signature of the function definition.  Having them next to the prototypes like that makes those lines harder to read and increases the code'd horizontal length.
Your curly brace usage with single-line statements is inconsistent.  It's also better to use them for all statements like these and can prevent some bugs and ease maintenance.
Instead of initializing the arrays with a loop, you can use std::fill_n():

std::fill_n(array, MAX_SIZE, 0);
std::fill_n(flags, MAX_SIZE, false);

While it may not matter in smaller programs, it's still more concise and can be safer.
You're passing C-arrays to functions, which shouldn't be done in C++ as this will cause them to decay to pointers.  Instead, pass in an object of a container class such as std::vector (dynamic) or std::array (static).  Choose whichever best gets the job done for you.


Python xml schema parsing for simpleContent and simpleTypes

Do more with literals:

def get_simple_type(element):
    return {
        element.get("name"): {
            "restriction": element.getchildren()[0].attrib,
            "elements": [ e.get("value") for e in element.getchildren()[0].getchildren() ]
        }
    }

def get_simple_content(element):
    return {
        "simpleContent": {
            "extension": element.getchildren()[0].attrib,
            "attributes": [ a.attrib for a in element.getchildren()[0].getchildren() ]
         }
    }


"Minimize" is a really bad word to use when trying to consider the quality of your code.  It's vague, and it can lead to undesirable outcomes, such as broken or unusable code.

For example, is your goal to minimize the number of bytes used storing the source code on a hard drive? That might have been important when paper tape was a popular storage medium, but it's irrelevant today.  It's so irrelevant that the difference between these two files is less than the size of a sector, so both actually occupy the same amount of storage space.

Is your goal to reduce the number of CPU cycles spent?  Given that cell phones have 100MHz processors these days, you need to do more work to figure out if the effort you expend thinking about the problem will ever be made up for in efficiency experienced by your users.  If this is run once or twice, efficiency simply is not important. On the other hand, if it could ever become part of a networking protocol, efficiency is extremely important.  Quite honestly, English word reversal seems to be too specialized to fit the test of practicality for efficiency.

In general, what most people should be striving for in their code is "correctness" and "clarity".  You want to know that it works correctly in all situations.  The answer to that is to write unit tests.  For clarity, you want the code to be readable, understandable, and usable.  Make sure you have chosen good names.  Modularize the functions.  For example, you should consider extracting the dependency on System.out.println, as outputting the string has nothing to do with reversing the string.


Finding line numbers of duplicate lines in a log file

To go through your programs:

Load the file into a list - \$O(n)\$ time and memory.
Go through the list and add to a dict - \$O(n)\$ time and memory.
Loop through the new dict: \$O(n)\$ time and memory,
if the item has duplicates, get the lines: \$O(n)\$ time, \$O(1)\$ memory.

In total \$O(n^2)\$ time, \$O(n)\$ memory.

And so it's \$O(n^2)\$ time, \$O(n)\$ memory.

Load the file into a list - \$O(n)\$ time and memory.
Loop through the file - \$O(n)\$ time, \$O(1)\$ memory.
Loop through the file for second index - \$O(n)\$ time and \$O(1)\$ memory.

In total \$O(n^2)\$ time, \$O(n)\$ memory.

It's \$O(n^2)\$ time, and \$O(n)\$ memory.

And so I'd change your program to remove the second loop through the file, to force this you can remove changing the file to a list.
You want to use what you are in (1), but to store a list of all the file indexes. After this you then want to filter all items that don't have a length greater than 1.
And so you should be able to get something like:

from collections import defaultdict

def find_dupl(log):
    output = defaultdict(list)
    with open(log) as f:
        for i, line in enumerate(f):
            output[line].append(i)
    return {k: v for k, v in output.items() if len(v) > 1}

This has \$O(n)\$ time and \$O(n)\$ memory. Yes it does use a module, but it's built in and makes your code much faster, and simpler.