Missing Header File

You need to include algorithm so that std::replace() can be accessed.

Error Checking

Rather than checking if argv[1] is null, it might be better to use argc in the error check. If argc is not greater than 1 than there is an error. This is what argc is meant to be used for, as well as for a loop control when there are more arguments. It might be good to give an example of the proper program call as part of the error message.

The else that follows the error check is not necessary because of the return statement.

The first return statement in main() should not return zero, it should return 1 to indicate a failure. What might be even better is to include cstdlib and use the system defined symbols EXIT_SUCCESS and EXIT_FAILURE.

It would be better to report errors to std::cerr.

int main(int argc, char** argv)
{
    if (argc <= 1)
    {
        std::cerr << "No path provided" << std::endl;
        return EXIT_FAILURE;
    }

    const char* path = argv[1];
    if (!DirectoryExists(path))
    {
        std::cerr << "Path doesn't exist" << std::endl;
        return EXIT_FAILURE;
    }

    std::cout << "Provided path is: " << path << std::endl;

    std::string fspath;
    fspath = replace(path);
    findVideos(fspath);

    return EXIT_SUCCESS;
}

Horizontal Spacing

A best practice in many programming languages is to put spaces between operators and operands, this makes the code much more readable and maintainable:

void findVideos (std::string& fspath) {
    while (*(fspath.rbegin()) == '/')
    {
        fspath.pop_back();
    }

    size_t i = 1;
    WIN32_FIND_DATA FindFileData;
    std::string destpath = fspath + std::string("/") + std::string("*.mp4");
    std::string ffmpegPath = "ffmpeg.exe -v error -f null - -i ";

    HANDLE hFind = FindFirstFile(destpath.c_str(), &FindFileData);

    if (hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            std::string fullpath = std::string(fspath)+std::string("/") + std::string(FindFileData.cFileName);
            std::cout << i << "-" << "Checking " << fullpath << " for errors" << std::endl;
            std::string command = ffmpegPath +std::string("\"") + fullpath+std::string("\"");
            system(command.c_str());
            i++;
        }
        while(FindNextFile(hFind, &FindFileData));
    }
    FindClose(hFind);
}

Prefer Modern C++ constexpr Over #define

In C++ creating a constant using constexpr is preferred over a macro because it it type safe and a macro is not type safe.

#ifndef INVALID_FILE_ATTRIBUTES
constexpr DWORD INVALID_FILE_ATTRIBUTES = ((DWORD)-1);
#endif

Indentation

It would be better not to mix spaces with tabs when indenting. Many programmers use 4 spaces for indenting, by default a tab is 8 spaces. This can lead to inconsistent indentation as demonstrated in the function bool DirectoryExists(const std::string& path) in the question. An IDE such as Visual Studio allows you to set the number of spaces used in a tab to prevent this problem, where notepad does not do this.

Replace

It's not clear that the function std::string replace (const std::string& path) since windows understand both the forward and backward slash in file specifications.


Raspberry PI controllable car (code for a 6-year old)

The implementation of forward is horrible. The only correct way of expressing it is to make all four motors go forward. As an analogy, how would you react if your keyboard manufacturer told you "oh sorry, we made a mistake, you have to type every second letter in uppercase to get a lowercase word"? That would be non-intuitive.

The API you provide must be as clean and simple as possible. You don't want your daughter to learn that "programmers make mistakes and are lazy about fixing them, so we have to live with that".

In which ways is your daughter supposed to change the current program? You should probably add some example code for waiting some time, to allow for composed commands like "forward, wait 1s, right, 1s, backward".

Your code seems to crash with an exception when an unexpected key is pressed. That's unacceptable for a robot, since it might harm people or pets when running uncontrolled (see Asimov's laws).

Using raw_input looks as if the user has to press the Enter key to confirm each action. That's too much of a burden. Controlling the car must be simple and immediate, to prevent accidents. How would you feel if your grown-up street car would ask you for confirmation for each step on the gas or brake?


Simple neural network implementation in Python

A more pythonic way of writing self.momentum = [0 for _ in range(input_neurons)] would be self.momentum = [0]*input_neurons


* {
    margin: 0;
    padding: 0;
    border: 0;
    list-style-type: none;
    transition: all .5s;
}

First, I wouldn't do this. This resets styles on all elements, including other elements on the page. One rule I follow in CSS is not to unnecessarily override styles, especially the defaults. Unless you have a good reason to do so or you have custom base style for everything (like bootstrap).

.gallery{...}
.gallery .button{...}
.gallery .items{...}

//or

.gallery{...}
.gallery-button{...}
.gallery-items{...}

Another good practice in CSS is to namespace your styles. Selectors after another selector only take effect to descendants of the former selector. This makes it possible to limit the coverage of the style down to a certain element's descendants. Another way to do it is to use a naming scheme that's similar to namespacing. This makes your styles mean something, appear like it has heirarchy, and does not accidentally override other elements' styles.

<div class="gallery"

The markup can also be simplified. A slider is simply a list of things. The markup should be built in a way that it does resemble a list semantically. Then you improve using JS from there. You can add the buttons dynamically in JS, as they mean nothing in the markup.

;(function(){

 // Your code here

}());

One thing I find annoying in JS is that everything you write is exposed to the global namespace by default. Your code will be prone to conflicting names, or mutating values. One thing you can do to prevent being a victim, or being the cause of conflicts is to enclose your code inside a closure. This prevents your code from being overwritten. To prevent your code overwriting stuff, you must declare stuff in this scope (use var).

var imageWidth = 300;

function generateXTranslate(index, width){
  return 'translateX(-' + (index * width) + 'px)';
}

nextBtn.addEventListener('click', function () {
  if (index === numOfImgs - 1) return;
  sliderWrapper.style.transform = generateXTranslate(++index, imageWidth);
});

prevBtn.addEventListener('click', function () {
  if (!index) return;
  sliderWrapper.style.transform = generateXTranslate(--index, imageWidth);
});

A lot of the code is redundant. You can simplify by taking out common code and moving them out to their function. In here, you can move out the setting of the transform into a function. Also, you can simply track down the current image as an index instead of the pixels, since the translated pixels is just a function of the index times the width of the images.


Using a variable in a for loop: is it proper practice or is there a better approach

Use array_chunk() to split $rows into rows. Each row will be double high $doubleRows, so store the values in a small multi-dimension array $tablerows before echoing the rows.

// One single row.
$rows = array(
    "A" => 1,
    "B" => 2,
    "C" => 3,
    "D" => 4,
    "E" => 5,
    "F" => 6,
    "G" => 7,
    "H" => 8,
    "I" => 9,
    "J" => 10,
    "K" => 11,
    "L" => 12,
    "M" => 13
);

// Split into 1 or more rows of 8 columns each.
$doubleRows = array_chunk( $rows, 8, true );

// Rows are now double high.
// Keys on the first row and values on the second.
foreach ( $doubleRows as $columns ) {

    // Reset rows.
    $tableRows = array();
    foreach ( $columns as $key => $value ) {
        $tableRows['keys'][] = "$key	";
        $tableRows['values'][]  = "$value	";
    }

    echo "
", join( '', $tableRows['keys'] ), "
";
    echo "
", join( '', $tableRows['values'] ), "
";
}

Style

You used a lot of end comments. I try to avoid them and I try to avoid obvious comments like, // Start the row. To me, the
 tag is pretty self explanatory, but if it is not to you, then I understand why you did it.

Wrap long comments and use proper punctuation and capitalization. Comments are for humans. PHP strips them out. If you are the only person who ever sees your code, write your comments for the (different) person you will be in six months. The future you may appreciate comments that look like sentences and paragraphs.

Be consistent with your indentation and white space. Always indent the same number of characters. This foreach is indented 4 spaces (or 1 tab). The conditional statement is indented 12 spaces (or 3 tabs).

    for ($index=$startIndex; $index<=$endIndex; $index++){//creates the rows
            if($rowEvenOdd == 1) {//if the row is odd, grab and display the key

I would write it like this:

    // Create table rows.
    for ( $index = $startIndex; $index <= $endIndex; $index++ ) {
        if ( $rowEvenOdd == 1 ) {
            // Row is odd. Grab and display the key.

I added some white space so it wouldn't look all scrunch up. I find it easier to read like that. The comment after the conditional tells you what the condition is instead of what the conditional does.

If this is your style for writing one line conditionals, I guess it is fine, but it looks scrunch up and harder to read.

if(array_key_exists($index, $arrayOfKeys))
    {$thisvalue = $array[$arrayOfKeys[$index]];}
    else {$thisvalue ="&nbsp;";}

I prefer this:

if ( array_key_exists( $index, $arrayOfKeys ) ) {
    $thisvalue = $array[$arrayOfKeys[$index]];
} else {
    $thisvalue ="&nbsp;";
}

Or this:

if ( array_key_exists( $index, $arrayOfKeys ) )
    $thisvalue = $array[$arrayOfKeys[$index]];
else
    $thisvalue ="&nbsp;";

I tend to not add white space near brackets [] and to add it in parenthesis ().

Except for $thisvalue and $thiskey all your variable name use camel case. $thisValue and $thisKey would be more consistent.


This looks needlessly convoluted: there is a lot happening, all at once, on top of each other.

The way to think about this is: first square each number, then sort the resulting list. The way to transform each element of a list is map. The way to sort is, well, sort. The way to compose two functions (i.e. pass the result of one as argument to the other) is . (dot)

So:

sqrarr = sort . map sq
  where
    sq x = x * x


Getting the length of a file in characters

Just seek to the end of the file and grab the value:

ifstream is;
is.open (FileName.c_str(), ios::binary );
is.seekg (0, ios::end);
length = is.tellg();


You should use your standard libraries when you can. Consider that a std::set already does all the hard work, unique, and sorted values:

#include <iostream>
#include <set>

int main() {
    std::set<int> data;

    // reads values into the set (assumed integers as input)
    int val;
    while (std::cin >> val) {
        data.insert(val);
    }

    for(std::set<int>::iterator iter = data.begin(); iter != data.end(); ++iter) {
        std::cout << (*iter) << "\n";
    }

}

Note though, that the above implementation has horrible handling of issues that may come from invalid input. Still, the entire implementation is significantly simpler than yours.


Try this:

public enum Template
{
    [StringValue("accountinfo.txt")]
    AccountInformation = 1,
    [StringValue("registration.txt")]
    Registration = 2,
    [StringValue("signed.txt")]
    Signed = 3
}

For more information: String Enumerations in C#

Otherwise, I prefer your second option.


Return a tuple from MySQL database with statements

The whole processServerResponse() method looks rather alien to me. I never seen anything like that. A server response shouldn't be so much tightly coupled with such a specific stuff like a statement class for one of PHP extensions. A server  response should be from a server, not a statement.

Besides, you are mixing two response codes here, "error occurred" and "zero results found". It should be different codes.

Usually, errors are checked by a distinct error handler, while number of results found can be checked within the same routine that returns the data.

So I would make it this way

public function getManufacturer($id) {
    $stmt = $this->dbConnection->prepare("SELECT ID, URL FROM ERP.MANUFACTURER WHERE ID = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id, $url);
    $found = $stmt->fetch();
    return [
                ACTION_RESULT => (int)$found,
                "data" =>
                [
                    "id" => $id,
                    "url" => $url
                ]
            ];
}

while errors should be checked with a site-wide handler like this (taken from my article on writing Db wrappers)

set_error_handler("myErrorHandler");
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    error_log("[$errno] $errstr in $errfile:$errline");
    header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
    header('Content-Type: application/json');
    echo json_encode(["error" => 'Server error']);
    exit;
}

So this way you will get different responses for the different scenarios.

On a side note, an obligatory suggestion: consider to use PDO instead of mysqli. This alone will do a huge refactoring for your code:

public function getManufacturer($id) {
    $stmt = $this->pdo->prepare("SELECT ID id, URL url FROM ERP.MANUFACTURER WHERE ID = ?");
    $stmt->execute([$id]);
    $data = $stmt->fetch();
    return [
                ACTION_RESULT => (int)(bool)$data,
                "data" => $data;
            ];
}


Thread that monitors a web API to get the latest announcement via JSON

Immediate observation: 201 CREATED is a really weird status code to expect here.  The GET method is supposed to be both safe and idempotent.  201 is supposed to indicate that a new resource has been created in response to the request.  Those don't go together.

Also, if you are polling for changes, you'll normally want to send a "conditional GET".  The web server should be providing you with an ETag that you can use, and your client should be sending an If-None-Match header with the previously seen ETag, allowing the server to save some work and bandwidth by returning a 304 NOT MODIFIED

This implementation is also blasting the host with new connections.  Check your requirements -- given that you are talking to the server across the network, there is clearly some acceptable latency.  If the SLA really is so tight that you have to poll the host constantly, then you should look into Long Polling; if it isn't, then your loop should be spacing out the requests.

You didn't include anything but your run method, but this code fragment

    e.printStackTrace();
    this.interrupt();
    try {
        this.join();
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

Stongly suggests that you've written a Thread.  Don't do that.  Let the standard libraries do the work of managing the threads.  Instead, you should create a Runnable, and submit it to an ExecutorService to do the work.

A ScheduledExecutorService supports scheduledAtFixedDelay.  You could use that to poll the server at a nice friendly interval, rather than writing a tight loop that tries to DOS the host all by its lonesome.

Your run() method is doing too many different things, and should be refactored.  Single responsibility principle suggests that methods should either create, coordinate, or calculate.  This code is doing all three -- you are coordinating the client server protocol, managing an http connection and an http input stream, creating a string buffer and a json parser, reading the response entity, parsing the entity, doing some unspecified work with the result.... Create different methods (possibly in different objects) to share the work.


Tesing a simple calculator class with JUnit/JMock

This is technically correct code, whether it's right depends...

This might be the first test for an object that will become more complicated. It's reasonable to start small and work your way up.

If the Calculator is a self-contained implementation that doesn't pull in other dependencies, it might be better to just use a real one. In this case, it looks more like a function.

In the end, there might well be more test than production code because you want to exercise all the paths. These days, I find myself writing unit tests with mocks at a slightly higher level, around a small cluster of objects.

If the call to the Calculator doesn't change the state of the world outside the Machine, I'd probably use an allowing clause, we "Stub Queries, Expect Actions"

allowing(calculator).add(1,2); will(returnValue(3));

it's the same implementation underneath but expresses the intent more clearly.

You might try the JUnitRuleMockery with JUnit's @Rule. It takes care of the assertion housekeeping at the right time.

And before someone jumps in with their favourite alternative mocking framework, I'm not sure that's really the point. We can shave a few lines off here and there, but it's more important to understand the design issues. And everything will change with Java 8.


class interest

In Java, class names are CasedLikeThis (pascal cased). Interest would be a proper name.

Name those strings more appropriately.

String firstNumber = JOptionPane.showInputDialog( "Enter QuantitySold Double " );

is a case of inappropriate naming. firstNumber is not a numeric value, it's a string. It's also not a "first string", it's a string that is supposed to represent the sold quantity, which is to be parsed as a double.

String rawQuantitySold = JOptionPane.showInputDialog("Enter QuantitySold Double");

would be a first step towards improvement.

You don't check for input validity. What if the user inputs some garbage, and not a valid string representation of a numeric value? Consider extracting the input bits, and forming a loop that continues for as long as the user inserts invalid data.

NumericType getNumericValue(String messageForUser)
{
     while (true)
     {
          String rawInput = JOptionPane.showInputDialog(messageForUser);
          if (canBeParsedToNumericType(rawInput))
          {
                return parseToNumericType(rawInput);
          }
          else
          {
               showMessage("Value has an invalid format. Please enter a valid value.");
          }
     }
}

and use it like:

Double quantitySold = getNumericValue("Enter the quantity that's been sold (floating point value).");

This also makes you get rid of the extra temporary strings there.

Tip! The else branch there is unnecessary, due to the fact that return will return immediately. You may or may not want to remove it.

Consider improving the messages you're showing to your users.

  Enter OriginalPrice Double

is not exactly a properly formatted and user aimed message.

  Enter the original price.

With, maybe, some info about the format that it has to have, and/or some examples would be a huge improvement.

Keep naming consistent.

String fourthNumber = JOptionPane.showInputDialog( "Enter lowedPercentagePrice Double " );
Double QuantitySold = Double.parseDouble( firstNumber );

Why is QuantitySold pascal cased, and fourthNumber camel cased? quantitySold should be your choice there.

Improve your formatting.

JOptionPane.showMessageDialog( null, message );

could become

JOptionPane.showMessageDialog(null, message);

Also,

class interest
{
public static void main(String[] args){

could be turned into

class Interest {

    public static void main(String[] args) {

and you should take a look at where you drop your braces, as well as where you drop random empty lines. If you need to separate your code in pieces with empty lines for readability, chances are you have to extract methods from there.

Consider, for example, extracting

Double PercentagePrice = LowedPercentagePrice / 100;
Double PricePercentage = OriginalPrice * PercentagePrice;
Double TotalPrice = OriginalPrice - PricePercentage;

into a function that calculates the total price based on some parameters that you set to it.

Double totalPrice = calculateTotalPrice(...);

Rule of thumb: if you have to split your functions in chunks using empty lines or verbose comments, you should first take a look if you couldn't extract those chunks in separate functions.


Displaying a new image document in Picturebox

Let's start here:

string[] filename = Directory.GetFiles(path, "*.tif");

If you know there can be only one file then you can try to get it right away with SingleOrDefault

var imageFileName = Directory.GetFiles(path, "*.tif").SingleOrDefault();

the condition will then become

var fileExists = !string.IsNullOrEmpty(imageFileName);
if (!fileExists)
{
   return;
}

Further you don't need all this code

FileInfo fi = new FileInfo(filename[0]);
byte[] buff = new byte[fi.Length];
using (FileStream fs = File.OpenRead(filename[0]))
{
  fs.Read(buff, 0, (int)fi.Length);
}
MemoryStream ms = new MemoryStream(buff);
Bitmap img1 = new Bitmap(ms);
//opened = true; // the files was opened.
pictureBox1.Image = img1;

instead you can just use

pictureBox1.Image = Image.FromFile(imageFileName);

besides there is a memory leak, you need to dispose the old image so before assigning a new one:

if (pictureBox.Image != null)
{
     pictureBox.Image.Dispose();
     pictureBox.Image = null;
}
pictureBox1.Image = Image.FromFile(imageFileName);

About the timer...

time1 = new Timer();
time1 .Tick += new EventHandler(timer1_Tick); //calls method
time1 .Interval = 2000; // in miliseconds (1 second = 1000 millisecond)
time1 .Start(); //starts timer

You have too many obvious comments here. There is no need to comment start as start ;-) One of them can even be replaced by a helper variable that makes the comment unnecessary. Meaningful variables are always better then comments.

const int oneSecondInMilisecods = 1000;

time1 = new Timer();
time1.Tick += timer1_Tick;
time1.Interval = 2 * oneSecondInMilisecods;
time1.Start();

Notice that you can also use a short event handler assignment.

Other suggestions:

You should use full names instead of abbreviations like fi or buff, imageFileInfo and imageBytes sounds much better and you don't have to think first what those variables are for
Collections should have plural form so string[] filename should be string[] imageFileNames
File_Length is not a good name becuause it doesn't tell us anything about what the method does and in your case it does a completely different thing. LoadImage would be much better here, we also don't put _ in method names unless they are event handlers or tests.
I would also change the name of the timer1 to loadImageTimer
You didn't put all the image loading code inside the time1_Tick event handler which is good ;-)


Implement Factory pattern with multiple parameters and each parameters are interface

If I understand your intent and code properly then you rather have an abstract factory implementation than a factory method pattern implementation.

The Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition.

The Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.

Reference 24th slide | Detailed discussion about the differences
Your FactoryFP exposes several methods to create multiple different objects (so called object family). Whereas a Factory Method's scope is a single object. And because of this an Abstract Factory can rely on multiple Factory Methods.

"Is there a better way to get what I want than that?"
As always it depends what do you want.

Do you want to hide direct object creation possibility? (Factory method refactoring)
Do you want to ease complex object creation? (Builder design pattern)
Do you want to have an easy to read complex object creation interface? (Fluent interface pattern)
etc.


Firstly, I think you need to clarify why you are wanting to show the payment form and hide the main form. In most applications, when you want to show a dialog of some description, you would show it modally (using dialog.ShowDialog()) so that it appears over the top of your current form and prevents the user from interacting with the other form until the opened dialog is closed.

Secondly, if you are wanting your current main form and payment dialog as two screens as opposed to a form and a dialog, then you may be better off creating some shell form that can contain a UserControl. You can then build the main form and payment form as two UserControl's and simply switch which is being displayed on your window.


Things you could improve

Using Headers

Right now you are defining some items at the top of your source file.

#define RED     "\x1b[31m"
#define GREEN   "\x1b[32m"
#define YELLOW  "\x1b[33m"
#define BLUE    "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN    "\x1b[36m"
#define RESET   "\x1b[0m"

These are all relatable, and reusable ANSI escape codes to color your text in a terminal, so you could put them all in their own header (color.h) for easy use with other files.

#define BLACKTEXT(x) "\033[30;1m" x "\033[0m"
#define REDTEXT(x) "\033[31;1m" x "\033[0m"
#define GREENTEXT(x) "\033[32;1m" x "\033[0m"
#define YELLOWTEXT(x) "\033[33;1m" x "\033[0m"
#define BLUETEXT(x) "\033[34;1m" x "\033[0m"
#define MAGENTATEXT(x) "\033[35;1m" x "\033[0m"
#define CYANTEXT(x) "\033[36;1m" x "\033[0m"
#define WHITETEXT(x) "\033[37;1m" x "\033[0m"

Then you can just #include "color.h" in all of your files where you need some color in your terminal.
As you can see from my own color.h header file, I don't have a RESET macro.  I didn't find a use for it, since I would always end up resetting the color right after I used it.  The way I have it defined, my macros can do that for me.

User Experience

I find it useless to have to enter a first and second number.

        printf("Enter first number > ");
  scanf("%d",&n1);
        printf("Enter the seconed number > ");
  scanf("%d",&n2);

What is the point of this?  Just start from \$ 0 \$ and \$ 1 \$, and go to \$ n \$ number of terms.

Efficiency/Algorithm

Right now you can't compute that many fibonacci numbers, because of the maximum size of an int; you can only calculate numbers up to 32767.

We aren't expecting negative numbers in our sequence, so we easily increase this restriction, you could use an unsigned int which has a maximum value of 65535, or even better, a long long unsigned int with a maximum value of 18446744073709551615. That's 562967131565294 times larger than your current program!
Your algorithm can be simplified down using method extraction and recursion.

  for (i; i < limit; i++ ) {
                if (n2 >=1) { pos ++; printf( RESET "%i\n" RESET, n2); }
                if (n2 <=0) { neg ++; printf( MAGENTA   "%i\n" MAGENTA,  n2); }
    int temp = n2;

    n2 += n1;
    n1 = temp;
  }

Move the computing of the fibonacci sequence to it's own method.  All you should be passing it is the number of the term you want to compute.

unsigned long long int fibonacci(unsigned long long int n)
{
    if (memoization[n] != -1) return memoization[n];

    return (n < 2)? n : (memoization[n] = fibonacci(n-1) + fibonacci(n-2));
}

You might notice that I have included an array in my previous point named memoization.  We want to use this to decrease computation time with the recursion.  Basically, if we have already computed a number, we put it into the array so we don't have to calculate it the next time we want to find a fibonacci number.  If we haven't found the number, we can indicate that in the array by storing a -1 there instead.

Style

Put all of your variable declarations to separate lines. From Code Complete, 2nd Edition, p. 759:

  With statements on their own lines, the code reads from top to bottom,
  instead of top to bottom and left to right. When you’re looking for a
  specific line of code, your eye should be able to follow the left
  margin of the code. It shouldn’t have to dip into each and every line
  just because a single line might contain two statements.

I can't follow your tabbing scheme.

        printf("Enter first number > ");
  scanf("%d",&n1);
        printf("Enter the seconed number > ");
  scanf("%d",&n2);
        printf("Enter the number of terms > ");
  scanf("%d",&limit);

This makes it harder for me to read.  You should align all of the left characters in a block to make them more readable.
You should declare your parameters as void if you don't take in any arguments.

int main(void)

Standards

You should be declaring i inside of your for loops.(C99)

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

Final code:

Iterative: \$ O(1) \$

The calculation of the fibonacci sequence here is a bit different than my point I made above.  I didn't mention it, since it was so different than how you were calculating your sequence.  This is one of the most optimal solutions for calculating a fibonacci sequence.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

long long unsigned int fibonacci(long long unsigned int n)
{
    return round((1/sqrt(5)) * (pow(((1 + sqrt(5)) / 2), n) - pow(((1 - sqrt(5)) / 2), n)));
}

int main(void)
{
    unsigned int num = 0;

    printf("Enter how far to calculate the series: ");
    if (scanf("%i", &num) <= 0)
    {
        puts("Invalid input.");
        return -1;
    }

    for(unsigned int n = 1; n < num + 1; ++n) printf("%llu\n", fibonacci(n));
}

Recursion: \$ O(n) \$

#include <stdio.h>
#include <stdlib.h>

#define ARRAYLENGTH 100 // keep in mind the result must fit in an llu int (fibonacci values grow rapidly)
                        // you will run into issues after 93, so set the length at 100
long long int memoization[ARRAYLENGTH];

long long unsigned int fibonacci(long long unsigned int n)
{
    if (memoization[n] != -1) return memoization[n];

    return (n < 2)? n : (memoization[n] = fibonacci(n-1) + fibonacci(n-2));
}

int main(void)
{
    unsigned int num = 0;

    for(unsigned int i = 0; i < ARRAYLENGTH; i++) memoization[i] = -1; // preset array

    printf("Enter how far to calculate the series: ");
    if (scanf("%i", &num) <= 0)
    {
        puts("Invalid input.");
        return -1;
    }
    if (num < ARRAYLENGTH)
    {
        for(unsigned int n = 1; n < num + 1; ++n) printf("%llu\n", fibonacci(n));
    }
    else
    {
        puts("Input number is larger than the array length.");
        return -2;
    }
}


In Memory Database in Unit tests, isolate the tests

Generally speaking whenever we are about to write unit tests we should follow the F.I.R.S.T. principles. It is an acronym, which stand for:

Fast: The execution time should be measured in milliseconds. If it takes a second or two then it can be considered as slow and should be revised.
Isolated: Each test is self-contained and does not rely on any other data. They can be run in any order.
Repeatable: The test runs must be repeated over and over again. In each and every run they should either pass every time or always fail.
Self-validating: There is no need for human interpretation whether or not the test succeeded or failed. The test result should be self-explanatory.
Timely: The code and related tests should be written in almost the same time. A new code without relevant unit tests should not be deployed.

Let's examine these ideas for your proposals:

Single database and cleanup

Fast: If for whatever reason a previous cleanup phase missed / failed then your database will have some trash data in it, which might impact the performance of your database operations. Executing the cleanup during setup and teardown might solve the problem, but it will definitely have performance impact.
Isolated: They are sharing the same database, so they are not truly isolated. It might be the case that they can't run in parallel, because ordering might matter.
Repeatable: Because they are using the same database, that's why order might affect the result of your assertions. In case of MSTest you can define ordering but if you need to use them that means your tests are not really isolated.
Self-validating: Because there is a chance for race condition your test results are non-deterministic, which means human-intervention is needed to interpret several resultsets, reproduce the issues (if it is even possible) and fix them.
Timely: It is irrelevant in our discussion

Separate database for each test case

Fast: Creating new in-memory database for each test should not impose performance penalty onto tests if there not too many tables and constraints.
Isolated: Separate databases are used for each test, means no shared resource is being used, which helps isolation.
Repeatable: Because each and every time you run your test against a brand new database, there won't be any trash data, which could cause race condition.
Self-validating: By being deterministic, no human intervention is needed to understand the test results.
Timely: It is irrelevant in our discussion

If you don't want to examine the test data manually, then you don't really need use the test name in the database name. You can use any random value:

int jitter = idGenerator.Next();
var condigBuilder = DbContextOptionsBuilder<TestContext>()
    .UseInMemoryDatabase(databaseName: $"TestDb{jitter}")
    .Options;

or

Guid jitter = Guid.NewGuid();
var condigBuilder = DbContextOptionsBuilder<TestContext>()
    .UseInMemoryDatabase(databaseName: $"TestDb{jitter}")
    .Options;


HAI 1.2

    I HAZ A REVIEW ITZ "Following" BTW Let's roll ;)

I got a few points I want to make here and the first is actually quite simple. Don't name your names in INTORN3TZP34KZ...

Yes I know it's an esoteric language, and I know that all the instructions are defined to be "Internet-Speaks". But that doesn't mean you absolutely have to make your code follow the spec definitions.
(Who makes their Stack a class anyway..)

CHEEZ, BURGR, WAFLZ, SEEKRITMOOV, ... these names are suboptimal. (Pardon my non-french).

You had it pointed out to you in your previous question, that the documentation uses lowercase for variables. (Seems the specs changed that...)
I think you should adopt either that or at least anything
but SHOUTCASE! There is no need to give a darn about convention when convention is dumb ;)

Especially with the missing syntax highlighting it is hard to read your code and differentiate between instructions and identifiers.

Additionally to that I want to suggest using non-speakzified variable names. Simply because it's easier on the brain to not have to unwrap the variable name before being allowed to think about what the variable name means in the first place.

Moving swiftly on from names to... names..

PIKAMOVE - Is it just me or does that call associations with Pokémon to your head??
VALID8MOOV - What's the 8 anyways???

The names you chose are confusing. Might (wink wink) be because you actually made them Internetspeakz again :(

Next!

Whitespace / Newlines

    OIC

    FOUND YR ULTIMAETMOOV

  IF U SAY SO

  HOW IZ I WINTEHGAEM YR MOOV AN YR ULTIMAETMOOV

let's see how you'd put braces in Java (or C# for that matter) for this code:

    }
    return ultimateMoov;
}

void winthegaem (Object moov, Object ultimatemoov) {

You might want to additionally differentiate the "difference" between IF YOU SAY SO and HOW IZ I. I'd either add an additional newline between these or remove them on "closing the braces".

Comments

  OBTW
    was going to make a GAEMLOOP,
    but stupidly I can't seem to figure out
    how to pass multiple values to STDIN with this "IDE"...
    so this program will only run a single round.
  TLDR

Hmm.. Interesting. But completely irrelevant for the code This comment is not helping. You did mention it in your explanation, so in the code it's meaningless.

Reading the code does not become easier with reading this comment. Remove it.

OMGWTF

Y U NO?

    OMG "ZPOCK", OMG "zpock"
        MOOV R SEEKRITMOOV
        GTFO

    OMGWTF
        MOOV R SMOOSH "... WUTS " AN MOOV AN " ANYWAI" MKAY
  OIC

KTHXBYE

BTW End of review ;)


Php

I'm not a big Php guy so I can't be too thorough in this section. The biggest thing is that you seem to be writing ... well ... a php script. While that absolutely works it's incredibly old-school and doesn't do anything as far as guiding you into the pit of success. So first bit of advice: use a framework. At time of writing, the two I've been hearing most buzz about are Laravel and Codeigniter. This is constantly changing but just pick one which you've heard about and use it, that will help you learn enough concepts to make an educated choice next time you need to select one.

Second, at the bottom you seem to have some invalid php. You have some missing braces in that if statement toward the bottom and it has two else clauses in a row. I'm not sure if that will cause an error but it will definitely never run the third clause.

Finally, your design leaves open a huge security hole if the site is ever opened to the public. You accept the message as an input parameter, much worse, you accept the email. Think of what happens when someone does a query to yoursite.com/yourpage.php?email=yourgrandma&message=Send%20me%20all%20the%20moneyand again, and again. Spammers love finding unsecured services like this!

A much better approach is to have the emails (and maybe message) stored on the server already in the database or a text file. Then you could supply parameters like email=1 indicating "email the person with id=1".

Having this behind a login page is not a (good) defense either. Someone could easily put the above url in the src of an  element and every time someone who had recently logged into your site visits a page they put that on (like a comment or forum page) you will be sending spam! To defend against this make sure that page does not accept the Http GET verb (in this situation POST would be appropriate). This is exactly the kind of error that a framework shoudl help defend you from.

Finally, I see what you're doing with the ajax flag but that's not the typical thing to do. Whether the operation succeeded or not should be determined by the returned Http code (200 for success and maybe 400 for error). Whether you should be returning json or html should be determined by a concept called content negotiation. This is again, something that your framework should be handling for you.

Html

name is not a valid attribute for the <form> element. But also don't put ids on things unless you absolutely know there will be only one of these elements on the page. The spec says ids must be unique across the page and lots of javascript libraries cause errors when the assumption is broken. In this case can you guarantee there will not be two contactForm elements on the page at once? What if you have 2 offices and each one wants its own contact form? What about elements with id=message or id=submit? A better approach I think in this case is to use a class. That is not to say that you should never use ids but in most cases the benefit isn't worth the risk.

Next, you don't technically need <button type=submit>, it's optional but submit is the default behavior.

Finally, I'm not 100% sure of the spec for  but I don't think it works by associating the label with the following <input>. Instead you have to use the for attribute and ids (which I've already argued is bad). Or do what I recommend, something like:

        Email Address
        <input id="email" type="email" placeholder="Enter Email" required>

Javascript

Javascript naming convention are to use camelCase with no underscores. It's not a big deal but it's pretty standard. The only exception is to use PascalCase for variables that are intended to be used with the new keyword (which you don't have here).

To a lesser extent than php, but with the javascript community where it is, its probably time to start considering choosing a javascript framework (like angular, backbone, knockout, or the like rather than using jquery directly.

In my opinion you are over-specifying your selectors, no need to do input[id=foo] when id is already specified as unique, no need to span.blah when span holds no semantic nor structural meaning. Consider that all this stuff is indexed in the browser so by adding more selectors you might actually be slowing things down however slightly.

You don't need to use $('id=something') to select, you can just say $('#something')

Your scope management looks pretty good, I'm happy to see you using find - another syntax which achieves the same purpose and you might find flows better (or not) is $('[name=email]', $form).

You've got inline styling and html. Why? Just put the element on your html page and show or hide it from javascript.

Finally, just about everything you're doing in js is handled in a very elegant manner by the jquery.form plugin. Just use that.


Reduce as many adjacent chars as possible in string

This is related to the task of checking for matching parentheses. You can solve it in a single pass if you compare the current org_char to the latest new_char, and if they are the same, remove the latest new_char and skip the current org_char.

The do_deletions function already defines the org_chars and the new_chars. Instead of comparing only the org_chars, you should check whether len(new_chars) > 0 and org_chars[i] == new_chars[-1].


It seems your implementation is correct. You also touch a common discussion of MVVM.

In MVVM should the ViewModel or Model implement INotifyPropertyChanged?

One could argue you could let the model implement INotifyPropertyChanged. I'm not experienced enough with MVVM to answer this with a pro/contra argumentation.

The main intent however is implemented and the separation is there either way.


Batch upload users to nextcloud on docker with bash csv

Review
This code looks pretty good.  I know very little about the docker-compose command being executed, but I can look at the script style.
Shellcheck spots no issues, which is always a good start.
I see nothing in here that really demands Bash rather than standard (POSIX) shell - all those [[ can be easily converted to [.
I recommend setting -u and probably -e.  In any case, consider what the effects of any individual command failing should be.  Within the loop, I recommend continuing to the next iteration, but remember whether any iteration failed.  One way I do that is
status=true   # until a failure
for i in ....
do
    some_command  || status=false
done

# terminate with appropriate exit code
exec $status

Instead of using many echo commands in usage(), it's easier to copy a single here-document:
usage() {
    cat <<'EOF'
batch_users.sh
SYNOPSIS
...
EOF
}

if [[ ! -e $1 ]]
then
  die "Couldn't find file ${1}."
  exit 1
fi

Braces not required here for $1, and exit 1 is unreachable.  Mere existence of the file is insufficient: we need it to be readable.  Here's my version:
[ -r "$1" ] || die "Couldn't find file $1."

We need to be very careful when composing strings to be interpreted by other commands, especially shells:

    sh -c "docker-compose exec -T --env OC_PASS=${password} --user www-data app php occ \
      user:add --password-from-env --display-name=\"${f2}\" --group=\"${f3}\" \"$f1\" " < /dev/null

$password in particular could contain almost anything (including quote characters), so that's really not safe in the inner sh instance.  Do we really need that shell, or can we simply invoke docker-compose directly?  The latter is much easier to get right.  If we really need the sh, then we'll need to be a lot more careful about constructing that command (I think we need to use a printf that supports %q conversion).
We can avoid the repetition by using ${var+} to conditionally include the optional arguments:
if [ "$f1" ]
then
    docker-compose exec -T --env OC_PASS="$password" \
                   --user www-data app php occ \
                   user:add --password-from-env \
                   ${f2:+"--display-name=$f2"} \
                   ${f3:+"--group=$f3"} \
                   "$f1" \
                   </dev/null \
         || status=false
else
    #error
    echo "Expected at least one field, but none were supplied." >&2
    status=false
    continue
fi

I think we have an unnecessary password exposure,. --password-from-env allows passing the password in environment, so that it doesn't appear in command-line arguments.  But we've immediately lost that advantage when we wrote --env OC_PASS="${password}".  I think the correct thing to do is to put the password into environment before the loop:
OC_PASS=$password
export OC_PASS

And then specify to copy it without giving a new value: --env OC_PASS.  We could also ditch $password and assign directly to OC_PASS.  It would be worth not setting a default, so that users can use the same environment variable to avoid exposing the password using when invoking the script.

Modified code
#!/bin/sh

set -eu

# Handle printing errors
die () {
    printf '%s\n' "$1" >&2
    exit 1
}

usage () {
    cat <<'EOF'
batch_users.sh
SYNOPSIS
batch_users [-p] [file]
DESCRIPTION
The batch_users script adds a batch of users to an instance of NextCloud
running inside of a docker container by reading a list from a csv file.

-p, --password    Set user password. If no option is passed, the password
                  should be passed in the OC_PASS environment variable.

csv file should be formatted in one of the following configurations:
username,Display Name,group,email@address.domain,
username,Display Name,group,
username,Display Name,
username,

EXAMPLES
The command:
    batch_users.sh -p 123password321 foobar.csv
will add the users from foobar.csv and assign them the password 123password321
The command:
    batch_users.sh foobar.csv
will add the users from foobar.csv and assign them the default password.

batch_users will return 0 on success and a positive number on failure.
EOF
}

# flags
while true
do
    case $1 in
        -h|-\?|--help)
            usage # Display a usage synopsis.
            exit
            ;;
        -p|--password)
            if [ "$2" ]; then
                OC_PASS=$2
                export OC_PASS
                shift
            else
                die 'Error: "--password" requires a non-empty option argument.'
            fi
            ;;
        --password=?*)
            OC_PASS=${1#*=} # Delete everything up to = and assign the remainder.
            export OC_PASS
            ;;
        --password=) # Handle the case of empty --password=
            die 'Error: "--password" requires a non-empty option argument.'
            ;;
        --)
            shift
            break
            ;;
        -?*)
            printf 'WARN: Unknown option (ignored): %s\n' "$1" >&2
            ;;
        *) # Default case. No more options, so break out of the loop
            break
    esac
    shift
done

# Was exactly one filename argument passed?
[ $# -eq 1 ] || die "$0: Expected a filename argument"

# Is the file readable?
[ -r "$1" ] || die "$1: missing or not readable"

[ "$OC_PASS" ] || die "$0: No password specified. Run with --help for more info."

status=true                     # until a command fails

while IFS=, read -r f1 f2 f3 f4
do
    if [ "$f1" ]
    then
        docker-compose exec -T --user www-data --env OC_PASS \
                       app php occ \
                       user:add --password-from-env \
                       ${f2:+"--display-name=$f2"} \
                       ${f3:+"--group=$f3"} \
                       "$f1" \
                       </dev/null \
            || status=false
    else
        echo "Expected at least one field, but none were supplied." >&2
        status=false
        continue
    fi

    # If there is a fourth value in the csv, use it to set the user email.
    if [ "$f4" ]
    then
        docker-compose exec -T \
                       --user www-data app php occ \
                       user:setting "$f1" settings email "$f4" \
                       </dev/null \
            || status=false
    fi
done <"$1"

exec $status

Further suggestions

Perhaps it would be useful to add a --verbose option that shows what is to be done for each input line.
Does the input really need to come from a file?  It would be useful to be able to provide it on standard input (so we could filter a list using grep, for example).


Parsing and saving JSON result from GoEuro API

The Python documentation recommends using with when dealing with
files at the bottom of 7.2.1 of the Python tutorial, this has the benefit that you do not have to close the file yourself.
Although not necessary often a main function is made, so that the
other functions also can be used as a module. (6.1.1. Executing
modules as scripts)
The long line with the write statement can be split over multiple
lines, you do not need the line joining character (\) in this case
because, a closing bracket is still expected at the end of the
line.
The newline problem, and simular problems can be solved with the
join function of strings

I took the liberty to create an extra function and all and all i changed your code to:

from urllib2 import urlopen
import json

def get_json(url):
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)

def json_to_formatted_text(geo_data):
    formatted_lines = []
    for x in geo_data:
        gp = x["geo_position"]
        l = gp["latitude"]
        o = gp["longitude"]
        line = (unicode(x["_id"]).encode("utf-8")  + ", " +
                unicode(x["name"]).encode("utf-8") + ", " +
                unicode(x["type"]).encode("utf-8") + ", " +
                unicode(l).encode("utf-8")         + ", " +
                unicode(o).encode("utf-8")         +
                unicode("\n").encode("utf-8"))
        formatted_lines.append(line)
    return unicode("\n").encode("utf-8").join(formatted_lines)

def main():
    url = ("http://api.goeuro.com/api/v2/position/suggest/en/Berlin")
    json_array = get_json(url)
    out_text   = json_to_formatted_text(json_array)
    with open('data.txt', 'w') as f:
        f.write(out_text)

if __name__ == "__main__":
    main()


Introduction
After reflecting and reading other answers, I found that Adam Smith is right: we should get rid of the class. For this problem I think that it's better to structure the program as a group of functions. This is my new answer.
Style
Variable names should be lowercase, so your variable BMI should be renamed bmi.
Modularity
According to Wikipedia, "In software design, modularity refers to a logical partitioning of the "software design" that allows complex software to be manageable for the purpose of implementation and maintenance. The logic of partitioning may be based on related functions, implementation considerations, data links, or other criteria." So you should divide your code into smaller units, for this purpose we will divide your code into a group of functions.
This is better, because it's a bad practice, IMHO, to write all your code as a single whole without dividing it into units. This makes your code reusable, readable, and maintainable.
Documentation
It's a good practice, IMHO, to document your code, this makes it more readable and easier to use. For this purpose we will use docstrings to document the functions that we'll define. Docstings are indented and contained into triple quotes, they describe what the function does, its arguments, the type of its arguments, its return value and the type of the return value (when used with functions). Docstrings are the right way to document functions, not comments, because if you need help about using the function, you can use help(name here) to display the docstring and get help, which you can't do with comments.
Dividing the Code into Functions
To achieve modularity, we'll divide the code into functions. We'll define:

a boolen-valued function (a function that returns only True or False) that asks whether the user wants to start. We will rename to_start to answer. Using upper method, we'll make the input uppercase, so we can compare it to 'Y' and 'N' easily if the user entered 'y' or 'n' instead.

a function that handles both weight and height.

a function that takes calculates the BMI and returns it.

a function that returns the weight status.

a function called main that contains all the code that will be executed. We'll use it as the body of if __name__ == '__main__' by calling it.

Return Value
Instead of making our new functions print the output, we'll make them return it. You can read about return values here (this is a link to chapter in Think Python 2e, I recommend that you read the whole book). Just printing the output gets the job done but makes functions less reusable. Suppose that you want to store the BMIs associated with users in a textfile, what will you do? Sure you can make other functions to get this done, but if you make your functions return the result you can reuse many cases.
Code after Refactoring
def body_mass_index(weight, height):
    """Returns the BMI based on weight and height.

    weight: float or int

    height: float or int

    Returns: float or int
    """
    return round(weight / height ** 2 , 2)

def weight_category(bmi):
    """Returns the weight category of the user based on their BMI.

    Returns: str
    """
    if bmi < 18.5:
        return 'underweight'

    elif 18.5 <= bmi <= 24.99:
        return 'healthy weight'

    elif 25.0 <= bmi <= 29.99:
        return 'overweight'

    elif bmi > 30:
        return 'obese'

def wants_to_start():
    """Asks whether the user wants to start.

    Returns: bool
    """
    while True:
        answer = input("Y to start N to exit: ").upper()

        if answer == 'Y':
            return True
        elif answer == 'N':
            return False

        print('Please try again.\n')

def get_user_data():
    """Asks for the user's weight and height.

    Rerurns: tuple of 2 floats or integers
    """
    while True:
        try:
            weight = float(input('Enter your weight in kilograms: '))
            height = float(input('Enter your height in meters: '))

            if 0 < weight and 0 < height:
                return weight, height
            else:
                raise ValueError()

        except ValueError:
            print('Invalid input for weight or height')
            continue

def main():
    if wants_to_start():
        weight, height = get_user_data()
        bmi = body_mass_index(weight, height)
        category = weight_category(bmi)
        print('Your BMI is: ', bmi)
        print('Your are ', category, '.')

    else:
        quit()

if __name__ == '__main__':
    main()

Notes
The function get_user_data is adopted from Lukasz Salitra's function _get_user_info in his answer to the OP's previous question. You can find the question here.
I'm no expert on BMI, so I've no idea if the program does what it's supposed to do properly. I focused on making the code more reusable, readable, and well-structured, according to what I know as a beginner.


PHP Factory Pattern : Should I use `create()` or `__invoke()`?

The only benefit of using __invoke() is that you can store the instance of the class in a variable as a callback and then use it without call_user_func_array(). But in my opinion using create() is more readable so you can guess easily what is the code doing.


Determine the longest segment of integers within an inclusive range that doesn't contain a bad number using Python

PEP 8
The Style Guide for Python Code lists many recommendations:

variables & functions should be snake_case
commas should be followed by a space
binary operators should be surrounded by a space (eg, l == r instead of l==r, and r + 1 instead of r+1)

Some of the function/variable names may be dictated to you by the coding challenge, but for all others you should follow the PEP 8 conventions.
Optimizations
Loop range
for i in range(l, r + 1):
Assuming your range is 1 to \$10^9\$, this loop will take more than 10 seconds if the code inside the loop takes more than 10 nanoseconds per iteration.  That's asking a lot for an interpreted language.  You would do better if that loop can be removed.
More on this in a moment.
Counting -vs- existence
if badNumbers.count(i)==0:
You are searching the list of bad numbers counting the number occurrences of the value i in the list.

badNumbers contains distinct elements

Because badNumbers contains unique elements, the count will be either 0 or 1.  More over, as soon as we find the first match, we can stop counting even if uniqueness was guarenteed, since we are testing the count against zero.  What you really want is simply to ask if the value i is in badNumbers.  You write that exactly how we said it:
if i in badNumbers:
This is still an \$O(n)\$ operation, but would be faster.  As mentioned in another answer, turning badNumbers into a set would speed that up into an \$O(1)\$ operation.  But let's investigate another option.
Reducing data
Your example badNumbers = [37, 7, 22, 15, 49, 60] with limits l=3 and r=48 reveals more inefficiency.  The badNumbers contains numbers outside of the limits.  Looking at those numbers over and over again (such as in badNumbers.count(i) == 0 or i in badNumbers) is wasted time.
We can filter out the "bad" bad numbers which end up just wasting time.
badNumbers = [number for number in badNumbers if l <= number <= r]
Organizing your data
You are looping over your candidate numbers, and then effectively searching to see if the candidate number is in the bad numbers list.  If that list was sorted, you could just maintain an index to the next unmatched bad number, and increment it each time a match was found.
Combining that with the previous step:
badNumbers = sorted(x for x in badNumbers if l <= x <= r)
Now in your example, the badNumbers would be [7, 15, 22, 37]
Now, it = iter(badNumbers) would create an iterator which could walk over the list, in order, bad_number = next(it) could extract the next bad number from the list, and we've gotten rid of that pesky index I mentioned above, too.
But I'd really like to get rid of that first loop, so lets take a different approach.
Gap Length and End Posts
[7, 15, 22, 37]
In this array, we can immediately see there are 15-7-1 good numbers between the first two bad numbers, 22-15-1 between the next pair, and 37-22-1 between the last pair.  This is almost all we need to get the longest run of good numbers!
What is missing is the good number runs at the beginning and end of the list.  We can fix that by adding some "end posts", extra bad numbers one beyond the good range end points:
badNumbers = [l - 1] + sorted(x for x in badNumbers if l <= x <= r) + [r + 1]
With limits of l=3 and r=48, this creates badNumbers = [2, 7, 15, 22, 37, 49].
Now, every pair of numbers can be used to determine the length of a run of good numbers.
pairwise
Since we want to take the numbers in pairs, it makes sense to consult the Python itertools library for an appropriate function.  It isn't built-in, but the pairwise recipe  can be installed from more-itertools.
Take the numbers as pairs, computing the number of good values between the pair of bad values, and remember the maximum value.  The "minus 1" from the internal calculation can be delayed till the end, for efficiency, since \$\max{(x_i-1)} == \max{(x_i)} - 1\$
from more_itertools import pairwise

def goodSegment(bad_numbers, l, r):
    bad_numbers = [l - 1] + sorted(x for x in bad_numbers if l <= x <= r) + [r + 1]
    gap_lengths = (b - a for a, b in pairwise(bad_numbers))
    return max(gap_lengths) - 1

badNumbers = [5, 4, 2, 15]
l = 1
r = 10

result = goodSegment(badNumbers, l, r)
print(result)

If more-itertools is not available, you can make something almost equivalent
def pairwise(numbers):
    return zip(numbers[:-1], numbers[1:])

It may even be faster, although it will use up to three times more memory.


Page Enum with overridden methods for the first and last members

Interesting question. Overriding methods in enum instances is not something I have encountered (that I recall). This is not to say it's a bad thing, just not very common. (P.S. having just claimed not to have encountered enum overrides, I see it is used in this answer given shortly before you asked this very question

The concept is something I have solved using different mechanisms before, but I can understand why having the override makes sense to you.

What I don't understand is why you did not just use a regular bound-clipping system. Why do you need the overrides at all?

Consider these methods:

  public Page next() {
    if (ordinal() == values().length - 1) {
        return this;
    }
    return values()[ordinal() + 1];
  }

  public Page previous() {
    if (ordinal() == 0) {
        return this;
    }
    return values()[ordinal() - 1];
  }

There is no reason to override them at all.

On the other hand, if you do override them, then please use a standard indentation for the override methods. Cramming it all on one line is not helpful:

public enum Page {
    INTRO {
        @Override
        public Page previous() {
            return this;
        }
    },
    PUBLIC_PROFILE,
    PRIVATE_PROFILE,
    SOCIAL_ACCOUNTS,
    LOOPS,
    INVITE,
    FINISHED {
        @Override
        public Page next() {
            return this;
        };
    };


There isn't really a reason to make this "more object-oriented" if you don't need to. To add more AI constructs, for example, you can do:

switch ($aiLevel) {
   case 1: $values = $OsTurn($values);
   case 2: $values = $betterAi($values);
   case 3: $values = $unbeatableAi($values);
}

Adding more features could be done in a similiar manner. I'm not sure exacly wht you have in mind, so I can only make some general comments. Break down everything into functions, and make sure that it's easy to see the flow of the program. The way you've structured your code is good. It should not be difficult to add more features if you use similiar style.

CSS won't affect your script; it just changes how the page looks. You'll just need to be sure you use the right elements when outputting html. Javascript may be trickier, but there are many ways of doing that including form elements (possibly hidden) and page submits. There may be other ways that I'm not aware of as I'm not primarily a web programmer.

I believe when you are talking about cheating, you're saying that you can send a winning board value set to the script by typing the URL yourself. To prevent this you need a way to preserve state. A cookie would be an easy way to start; store the current state of the board in it after every page call, and check that the only change was the placing of another piece. A more robust, but somewhat more involved, solution would be to use session variables to store the state. This would avoid the "cookys are bad" problem and the possibility that someone might fake the cooky!


Counting the number of occurrences of chars in one string, in another string

Style

There are a few bad habits in here that should be resolved. Here's your core method:

public static int countChars(String target, String source){
    char a[] = source.toCharArray();

    int loc = 0, count = 0;
    boolean charRepeat = false;

    for (loc = 0; loc < source.length(); loc++) {
        charRepeat = false;
        for (int z = 0; z < loc; z++) {
            if (a[loc] == a[z]) {
                charRepeat = true;
                break;
            }
        }

        if (charRepeat == false) {
            int i = 0;
            while ((i = target.indexOf(a[loc], i)) != -1) {
                count++;
                i++;
            }
        }
    }
    return count;
}

let's go through some things that are style-based.

source comes before target. The natural thinking is that you go from the source to the target, your naming, and the order of the parameters, is awkward. I would call the source something like searchFor, and the target I would call searchIn. Note, you have confused these values so much that your description does not match your code. In your description you have:

E.g Source String - "Hello World"
Target String - "ooood"
Output = 3

but in your code you have:

String target = "Hello World";
String source = "oood";
int count = countChars(target, source);

Note how you have swapped the source/target between the example and the code.

source and target are basically bad names to have...
Your code uses a number of small variables that are unconventional. loc is not a terrible name, it is clearly short for location, but using the fill location would be better. I have a habit of using pos so I can't really complain. On the other hand, the variables a for the char array, and z for an index, are bad names. You already use charRepeat, so you know how to use meaningful names, use them. The z is interesting because it is common to use x, y, and z as names for coordinate space, so seeing z automatically implies there's an x and y too. You should rather just use the standard index variables i, j, and k (but don't use j unless you are already using i, and don't use k unless you are using j too).

Algorithm

Your algorithm is a bit messed up too. Basically, you scan the searchFor chars, and find the first occurrence of each char value. If it's the first one, you then use that to scan the searchIn value, and you count the 'hits' in there. There are two issues here. The first issue is the performance of the 'first check'. The performance is \$O(n^2)\$ where \$n\$ is the number of chars in the searchFor value.

Then, for each unique char, you then do a loop through all the searchIn chars. The loop through all those are disguised in two steps, first the while loop, and then inside that, the indexOf search.

The net result is that you have a performance of \$O(nm)\$ or \$O(n^2)\$ depending on whether there are more characters in the searchIn or searchFor strings.

There is a better solution for both the uniqueness testing, and for the searching. Consider sorting the chars in each string:

char[] lookFor = searchFor.toCharArray();
char[] lookIn = searchIn.toCharArray();

Arrays.sort(lookFor);
Arrays.sort(lookIn);

The two sorts are \$O(n \log n)\$ performance, so this is, so far, significantly less complicated... now, how do we compare? Well, with a 'simple' loop over all the lookIn characters:

int forpos = 0;
int count = 0;
for (char c : lookIn) {
    // advance the searchFor cursor to the next usable position
    while (forpos < lookFor.length && lookFor[forpos] < c) {
        forpos++;
    }
    if (forpos >= lookFor.length) {
        //nothing left to look for.
        break;
    }
    if (c == lookFor[forpos]) {
        count++;
    }
}
return count;

With the above code, you do two sorts, and 1 loop through each value. The net result is that your performance complexity is simply \$O(n \log n)\$ where \$n\$ is the longer of the searchIn or searchFor variables.

By sorting each side, you give yourself a significant algorithmic advantage.


How to download tgz file from a url and decompress it efficiently?

DownloadTGZFile does two things, which is one thing too many.

It does what it name says it does (download a .TGZ file),
but it also unpacks the TGZ file, and that is not in the method's name.

Unpacking the file should be a different method. You should then have a new method that calls both methods.

Also, please follow the Microsoft guidelines:

The PascalCasing convention, used for all identifiers except parameter
names, capitalizes the first character of each word (including
acronyms over two letters in length), as shown in the following
examples:
PropertyDescriptor HtmlTag
A special case is made for two-letter acronyms in which both letters
are capitalized, as shown in the following identifier:
IOStream

Thus the method name should be DownloadTgzFile.


How can I implement the generic repository pattern and improve the performance for the code below?

The only way DI (IoC) is going to improve this code is by extracting the creation and disposal of your data context. This also means you can mock it for your unit tests.

You could argue the DataContext already is a Repository.

You could do one of:

Leave it as it is. No reason to complicate it just for the sake of it. It's small, pretty easy to follow and easily found.
Extract a Query object (Query Pattern)
Wrap the query and creation of the OfficeDTO in an OfficeDTO factor


CRUD (database layer) for F# with TypeProviders

new() = new Item()

This is infinite recursion, in order to call the parameterless constructor, you call the parameterless constructor. It's not quite clear to me what the default values of id and name should be. In C#, it might be okay to use null, but that's not the common approach in F#.

query {
    for row in db.ItemsTable do
    select row
}

Wouldn't just db.ItemsTable work here too?

query {
    for rows in db.ItemsTable do
    where (rows.ItemId = itemId)
    select rows
}
|> (fun s ->
        if Seq.isEmpty s then
            None
        else
            s |> Seq.head |> this.Record2Item |> Some)

That second part could be simplified to:

|> Seq.tryPick Some
|> Option.map this.Record2Item

try
    db.DataContext.SubmitChanges()
with
    | exn -> printfn "Exception: \n%s" exn.Message

Are you sure that it's okay for your DB layer to just print any errors to the console and then continue as if everything was fine? That doesn't sound like a very robust approach to me.

If you're sure you want to do it this way, then consider extracting this code into a separate function, since you're repeating it at several places.

|> (fun e -> e.ItemName <- item.ItemName)

I personally don't like this style of code. Pipelining using |> should be used for code that doesn't mutate anything.

if Option.isSome item then
    (Option.get item).ItemName |> should equal "two"

I would probably use pattern matching here.


The result function can be much shorter:

def result(user_choice, cpu_choice):
    game_result = (3 + user_choice - cpu_choice) % 3
    user_score = (0.5, 1.0, 0.0)[game_result]
    return (user_score, 1.0 - user_score)

I changed the following things:

Since the result of a single game does not depend on the previous results, it is easier to only compute a single result.
The result of a game can be computed by taking the difference of the choices.
The 3 + prevents the difference from getting negative. This is done because different programming languages choose to produce different results for the expression -2 % 3. Adding 3 prevents that.
game_result is now either 0, 1 or 2
This can be used in a small lookup table to produce the correct user_score.
Since user_score + cpu_score == 1.0 for a single game, there's no need to do the complicated calculation twice.
Returning a tuple (1.0, 0.0) instead of a list [1.0, 0.0] is more appropriate, since lists can change their size. This return value has always size 2, since there are only 2 players.

The code is a little trickier to understand, but it works. And it is more concise.

def choice_to_string(choice):
    return ('rock', 'paper', 'scissors')[choice - 1]

With that function, you can write:

print("{0} chose {1}".format('The player', choice_to_string(2))

The rest of the code is fine, except for the variable names. You are using way too many synonyms.

computer, cpu, ai all mean the same. Choose one of them and only use that.
human, user, player all mean the same. Choose one of them and only use that.

Writing technical documents and code is very different from writing a novel. In a novel, using different terms for the same thing is generally accepted, in code it is not.

Instead of asking the user alternatingly to type "1 to 3" and "0 or anything else" is too much of a burden. You can combine these into "type 1 to 3 to play, or 0 to quit". This allows a game to be played with 2 key strokes instead of 4.


Inserting new rows into an existing table

Before I continue, the following must be said:

Stop using mysql_query.

Seriously.  There have been very good replacements for going-on a decade now.  And considering this code does not appear to escape anything at all, you'd do well to learn to use parameterized queries so that it doesn't have to.

With all that said, though, the SQL might not even be necessary.  Is there a good reason you're not using wp_insert_post to, well, insert a post?  Looks like it lets you set everything you want to set, and then some.  It also returns the post ID, so you don't even have to touch the database directly to get it.

It sounds like the problem is not SQL or WordPress, really.  This code should not be as slow as you're describing.  If you have a DB server that's not your web server (which is generally the case in shared hosting and such), there will naturally be a bit of slowdown.  Generally not that much delay, though, unless the DB is hosted in a totally different place (ie: not from your web hosting company).  That, and the possibility that the server (DB or web server, either one) is simply overloaded, are more likely possibilities.


I've written remainder(x,y) in OCaml. Is there more efficient than O(n)?

I don't know OCaml, but I know enough similar languages that I think I can read that well enough to answer.  Still, take this with a grain of salt.

That is tail recursive.  You either return a value, or return the result of a recursive call that depends only on its input parameters that are known at the time of the call.

There is a more efficient algorithm.  Hint: repeated subtraction.  (That may not be the most efficient algorithm.)

You don't actually use the parameter n, you could just use x directly in the same way you use y directly.  The name rem isn't the most descriptive; remainder would be better, but that particular function is mostly known as mod or modulus.

I would find this formatting more readable:

if i = n
then acc
else if acc+1 = y
     then aux      0  (i+1) n
     else aux (acc+1) (i+1) n


Three other answers, and none have picked up on the bug yet, so, here's the bug, in the second version:

The input array new int[]{4} is sorted, right? The first method will return true. The second method will return true, fine... but, what about the array new int[]{} (the empty array)? The first method will return true. The second method will throw ArrayIndexOutOfBoundsException

The two methods are not the same. The second is buggy.

To me, this makes the first method the clear winner.

Now, while you are reading this, also note that in Java, the { brace should, by convention, be at the end of a line, not on a new line. What you have in your code is C* style coding (C, C++, C#, etc.).

Also, use final when appropriate....

Your code should look like:

public static final boolean checkSortedness(final int[] data) {
    for(int i = 1; i < data.length; i++) {
        if(data[i-1] > data[i]) {
            return false;
        }
    }
    return true;
}


Solve quadratic equation in standard form

welcome to code review!

The first thing I want to do, is to put the code into a function. This separates it from anything else you might run, and allows you more control. I've used the name quadratic_solver and instead of taking input(), it now takes three arguments which are the coefficients. I've also added a docstring which briefly explains the function's purpose.

My German's not very good so I've just left your comments in; apologies if they're now incorrect. As per PEP8 (python's style guide), I've put your import before the function at the start of the file.

import time

def quadratic_solver(a, b, c):
    """
    Solves quadratic equations of the form ax**2 + bx + c
    """

    print("ax^2+bx+c ausrechen UwU, Bitte Achte!!! Bei Kommazahlen . benutzen, nicht , Beispiel: 0.5 0.7 1.6")

...

Now, if you want to check the type of your arguments you can do a simple:

type(val) is int or type(val) is str for example.

To loop over several values we can use a generator. Here, we loop over all values in a list [a, b, c] and ensure they are NOT all ints:

if not all(type(coeff) is int for coeff in [a, b, c]):

I'm not 100% sure why you're checking the type but perhaps your inputs are delicate in some way.

The rest of the code is fairly unchanged. I have however removed a lot of the casting to floats and strings.

If you want to concatenate strings with variables, you can use an fstring. This is of the form:

print(f"Nullstelle1= {result1}")

Where any variables are given in {} and an f at the start of the string denotes to put the variable inside the string as a string.

fstrings can also contain code, so I've used a ternary operator instead of your if else statement:

print(f"Nach {'oben' if a > 0 else 'unten'} geöffnete Funktion")

I've eliminated a few extra variables and brackets too, just for neatness. I'd recommend changing your variable names perhaps to something clearer, and adding a few comments to show what's going on.

Putting this all together, we get:

import time

def quadratic_solver(a, b, c):
    """
    Solves quadratic equations of the form ax**2 + bx + c
    """

    print("ax^2+bx+c ausrechen UwU, Bitte Achte!!! Bei Kommazahlen . benutzen, nicht , Beispiel: 0.5 0.7 1.6")

    if not all(type(val) is int for val in [a, b, c]):
        print("doing some math")

        numer = b * b - 4 * a * c
        if numer > 0:
            q = numer ** (1 / 2)

            result1 = (-b + q) / (2 * a)
            result2 = (-b - q) / (2 * a)

            print(f"Nullstelle1= {result1}")
            print(f"Nullstelle2= {result2}")

            abc = -b / (2 * a)
            moo = (4 * a * c - b ** 2) / (4 * a)

            print(f"Scheitelpunkt: ({abc}|{moo})")

            print(f"Nach {'oben' if a > 0 else 'unten'} geöffnete Funktion")
            print(f"Schnittpunkt mit der Y-Achse ist {c}")

        else:
            print("sorry, geht nicht da eine negative zahl unter der wurzel sein würde")
            time.sleep(3)
    else:
        print("nur Zahlen bitte")

Finally, to call your function, you can now put the following:

if __name__ == '__main__':
    quadratic_solver(1.0, 2.0, 3.0)

Wrapping the function in the if __name__ == '__main__': ensures the function is being run from the right place and not externally. 1.0, 2.0 and 3.0 are just some example coefficients.

I would also consider removing the time.sleep(3); what is it for?

EDIT:

For the type checking, per @AlexV's comment, if you're checking an input is of a valid type, it's better to check it IS that type, rather than ISN'T another type. So the condition would actually become:

if all(type(coeff) is float for coeff in [a, b, c]):

You could even use Python's new type hinting if you like:

def quadratic_solver(a: float, b: float, c: float):
    ...

```


There are Data.List.Split.chunksOf and Data.List.Grouping.splitEvery implementations of this routine in specialized packages (and a number included in other application packages: search by Int -> [a] -> [[a]] signature on Hayoo).

I think splitEvery implementation is pretty elegant:

splitEvery :: Int -> [a] -> [[a]]
splitEvery _ [] = []
splitEvery n xs = as : splitEvery n bs
  where (as,bs) = splitAt n xs


Does this C binary search tree have memory leaks?

The code looks nice.  Just a few comments:

In new_node, your word-copying is wrong as you use sizeof(nword) where
nword is a pointer.  Using sizeof on a pointer gives only the size of the
pointer itself, not the size of what it points to.  try it with some long
words.  Your word copying could either use strdup or if you don't have that,
write your own.

In main, set n to NULL before using it.

There are no checks for malloc failure.  It is good practice to check, but the
only thing one can do is often to exit.

It is best to avoid leading underscore on identifiers (they are reserved).  And it is generally better to use explicit braces around statements even when strictly unnecessary.


Avoiding code duplication in mapping layer between dataRecord and

I believe the easiest way to avoid duplication each time you read from the database is to create a constructor which receives a DataRecord as a parameter, and does the heavy lifting:

public class User {

    public User() {}

    public User(DataRecord dataRecord) {
        IDUser = dataRecord.GetInt("IdUtente");
        FirstName = dataRecord.GetString("Nome");
        LastName = dataRecord.GetString("Cognome");
        //[...]
    }

    //...
}

And then:

public IEnumerable<Model.Accounts.User> GetUsers(int IDUser)
{
    using (var sqlClient = CreateSqlManagerInstance("ListUser", CommandType.StoredProcedure))
    {
        sqlClient.AddParameterWithValue("IDUser", IDUser);
        return sqlClient.ExecuteResultSet().Select(
           dataRecord => new GModel.Accounts.User(dataRecord)).ToArray();
    }
}

You could also use an automatic mapping library, but before you choose to do that, you might  want to look at some O/R mapping library, like NHibernate for c#, which should replace the mapping in your code altogether.


Random walk generator - looking for optimizations (Python)

Here's one suggestion; other readers will probably offer more.
Several times, you need to get an integer from the user. You
could create a function to handle such details. The code
below shows what the function might look light and how you
would use it.
def int_from_user(prompt):
    while True:
        try:
            n = int(input(prompt + ' '))
            if n > 0:
                return n
            else:
                raise ValueError()
        except ValueError:
            print('Invalid input! Enter a positive number.')

steps = int_from_user('How many steps should be done?')
print(steps)


Use the argparse module for getting user input
Validate user input
Use f"{string}" or "{}".format(string) instead of manually concatting
No need to do i.close() as the with automatically closes the file
Use a if __name__ == '__main__' guard
Add functions for re usability

Revised Code

import subprocess
import datetime
import re

import argparse

def write_result(filename, ping):
    with open(filename, "w") as f:
        f.write(f"Start time {datetime.datetime.now()}")
        for result in ping:
            f.write(result)
        f.write(f"End time {datetime.datetime.now()}")

def ping_subnet(subnet):
    for addr in range(1, 255):
        yield subprocess.Popen(["ping", f"{subnet}.{addr}", "-n", "1"], stdout=subprocess.PIPE) \
                        .stdout.read()                                                          \
                        .decode()

def main(subnet, filename):
    write_result(filename, ping_subnet(subnet))

def parse_arguments():
    parser = argparse.ArgumentParser(usage='%(prog)s [options] <subnet>',
                                     description='ip checker',
                                     epilog="python ipscanner.py 192.168.1 -f somefile.txt")
    parser.add_argument('subnet', type=str, help='the subnet you want to ping')
    parser.add_argument('-f', '--filename', type=str, help='The filename')
    args = parser.parse_args()

    if not re.match(r"(\d{1,3}\.\d{1,3}\.\d{1,3})", args.subnet) \
       or any(a not in range(1, 255) for a in map(int, args.subnet.split("."))):
        parser.error("This is not a valid subnet")

    if " " in args.filename:
        parser.error("There cannot be whitespaces in the filename")

    return args.subnet, args.filename

if __name__ == '__main__':
    main(*parse_arguments())


Bookmarklet for selecting code snippets on Code Review

You inject the button using jQuery.prepend(), which inserts the button as the first child of the .prettyprint code block.  Therefore, when the bookmarklet is invoked, and it selects the contents of the code block, the "Select Code" button is inadvertently included in the selection.  I recommend using jQuery.before() instead.


As you noted, a more functional solution could be better.  Here is a way to write it using lodash.js:

var data = [
             { userId: 1, postId: 1, postData: "first post first user" },
             { userId: 1, postId: 2, postData: "second post first user" },
             { userId: 2, postId: 3, postData: "first post second user" }
           ];

posts = _
  .chain(data)
  .groupBy('userId')
  .mapValues(function(x) {
    return _.extend.apply(this, _.map(x, function (y) {
      return {[y.postId]: y.postData };
    }));
  })
  .value();

The .groupBy('userId') makes the intention clearer, but whether it is a better solution than the original is debatable.  Therefore, you may be better off leaving the code as it is.


This error handling looks pretty useless to me:

The log message doesn't record which URL was inaccessible.
If an error occurs, then the code will continue to execute. That means that whoever calls this function will have to handle the possibility of a null result. If that isn't done, then it will cause a NullPointerException.

A better idea would be to simply propagate the exception, so that the caller will stop trying to process a Document that isn't there.

Furthermore, what does it mean to "prepare a connection"? It looks like this code goes way beyond preparing a connection — it actually makes the connection and fetches the content as a Document!

So, the class should look more like this:

public class JSoupConnector {
    public static Document connect(String url) throws IOException {
        try {
            return Jsoup.connect(url).get();
        } catch (IOException e) {
            log.warn("Cannot connect to URL " + url);
            throw e;
        }
    }
}

At that point, this wrapper is hardly doing anything at all, and you might consider eliminating this helper functional altogether.


Without seeing the rest of your code it's difficult to say how this is used, but I think your function has conflated logic and formatting, and formatting is being done too soon. You should hold onto real date information right up until the edges of your program when that's possible. The following demonstrates one way of keeping dates and moving them to the current year.
from datetime import date, timedelta
from typing import Iterable, Tuple

QUARTER_DATES = (
    date(2000, 3, 31),
    date(2000, 6, 30),
    date(2000, 9, 30),
    date(2000, 12, 31),
)

def get_current_quarters() -> Iterable[date]:
    year = date.today().year
    for quarter in QUARTER_DATES:
        yield quarter.replace(year=year)

print('\n'.join(d.strftime('%d/%m/%Y') for d in get_current_quarters()))

dd-mm-YYYY is also an ambiguous and non-sortable format. Your usage (which you have not shown) will either need this to be "machine-readable" - e.g. for logs, REST payloads, etc. - or human-readable, e.g. for a UI. If you need machine readability, the ISO yyyy-mm-dd format is strongly preferred. If you need human readability, rather than hard-coding dd/mm/YYYY, your code should obey the current locale (not shown above).


There is actaully another solution that utilizes the Except extension. This means you first select all reviews with at least two users but remove those where the restaurant does not have at least three reviews.

This requires to write a new IEqualityComparer that I find is an overkill for this but on the other hand the Except clearly tells what kind of results we don't want to have. Anyway, the alternative solution:

reviews
    .GroupBy(r => r.UserId)
    .Where(g => g.Count() > 1)
    .Except(
        reviews
            .GroupBy(r => r.RestaurantId)
            .Where(g => g.Count() < 3),
        new ReviewComparer()
    );

where

class ReviewComparer : IEqualityComparer<IGrouping<Guid, Review>>
{
    public bool Equals(IGrouping<Guid, Review> left, IGrouping<Guid, Review> right)
    {
        // left - user-group
        // right - restaurant-group
        // exclude the user group
        // if it contains any restaurant-id of the excluded restaurant-ids
        return left.Any(x => right.Any(y => y.Id == x.Id));
    }

    public int GetHashCode(IGrouping<Guid, Review> reviews)
    {
        return 0; // treat all groups equally
    }
}


What is the best way to use the database connection file in PHP?

Good question. Although the connection code itself is good, some improvements can be made.
A separate config file
When your code goes live, most likely database credentials will be different from those at home. Therefore, having them hardcoded in the script will make it extremely inconvenient. Instead, create a separate file for your configuration as follows:

add the config.php line in .gitignore (in case you are not using git yet, you definitely should)

create a file called config.sample.php with all variables set to empty values like this:
  return [
      'db' => [
          'host' => '127.0.0.1',
          'username' => '',
          'password' => '',
          'dbname' => '',
          'port' => 3306,
          'charset' => 'utf8mb4',
      ],
      'base_url' => 'http://example.com/',
  ];

add it to the version control

then in your application bootstrap file have a code like this:
  <?php
  if (!file_exists('config.php'))
  {
      throw new \Exception('Create config.php based on config.sample.php');
  }
  $config = require __DIR__.'/config.php';

  define('BASE_URL', $config['base_url']);

  $options = [
      PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
      PDO::ATTR_EMULATE_PREPARES   => false,
  ];
  $dbconf = $config['db'];
  $dsn = "mysql:host=$dbconf[host];dbname=$dbconf[dbname];charset=$dbconf[charset]";
  try {
          $pdo = new PDO($dsn, $username, $password, $options);
  } catch (PDOException $e) {
      throw new PDOException($e->getMessage(), (int)$e->getCode());
  }
  unset($dbconf, $config['db']);

then, as suggested, create config.php on the every server that your application runs, each with its own set of values.

Actually using the connection
Just use this $pdo variable. When PDO is needed in a function - then pass it as a function parameter. If some function do not need PDO but it calls some other function that needs PDO - then pass $pdo into both. Yes it seems a bit a nuisance but this way you will always know what's going on and where. Avoid using dirty tricks like declaring variable global, singletons and such.
Some minor issues

closing PHP tag is not necessary and forbidden by the standard
// HTML code start reveals completely wrong approach to structure the code. Never an HTML code should start from the very beginning. Your PHP code should perform all the data manipulations first, and only then start the output
require should be always used for the files that are vital for the application. As this file surely is, then it must be require'd. Note that you should avoid using require_once and the likes - nowadays it's not more than a dirty hack to cover an inconsistent code


Finding array indices that add up to another number

There's nothing wrong with a break statement used outside a switch statement. (2nd example)

If a professor or some other authority figure is enforcing that rule, that's a pain, but the code is perfectly fine. There's even a similar example in the Java Tutorials on Branching


The main single advantage of quicksort is that it sorts in-place. Your implementation does not. It requires an additional memory for left and right lists, linear in terms of the initial array length.
Returning the concatenation of the three lists also doesn't help performance.
An obvious improvement is to reimplement it in-place.


getRandom() - Randomize array and get result

This function shouldn't be needed.

I have a feeling that you wrote it for some imaginary people and without any particular use case in mind. And out of the false assumptions too. Neither more than one shuffle is required and you never need to shuffle an associative array. So just raw shuffle() is enough.

And you can always use $arr[array_rand($arr)]; instead of getRandom($arr); to get just a single value.


for index, unique_letter in enumerate(sorted(set(text), key=text.index)):
    text = text.replace(unique_letter, str(index))
return text

You don't need to go through the set and sort, you can do:

for index, letter in enumerate(text):
    text = text.replace(letter, str(index))
return text

By the time it gets to the last "e" in "estate" and tries to replace it with "5", it will already have replaced it with "0" earlier on, and there won't be any "e"s left to replace. And it's not changing something while iterating over it, because strings are immutable.

More golf-ish and less readable is:

return ''.join(str(text.index(letter)) for letter in text)

Edit: Note for posterity: the above two methods have the same bug Gareth Rees identified, comparing 'decarbonist' and 'decarbonized', where one ends by adding number 10 and the other is a character longer and ends by adding numbers 1, 0 and they compare equally.End Edit

But @jonsharpe's comment asks if you need it to return a string; if you don't, then it could be a list of numbers, which is still very readable:

return [text.index(letter) for letter in text]

Minor things:

are_isomorph is a mix of plural/singular naming. Maybe isomorphic(a, b)?
Your code doesn't take uppercase/lowercase into account - should it?
This approach will break without warning for an input with numbers in it, e.g.

repetition_pattern('abcdefghi1') is 0923456789. "b" changes to 1, then changes to 9 because the "1" at the end catches it, then it appears the two were originally the same character. (It might be outside the scope of the question and not a problem).


In case n == 0 the loop body of calculateFactorial wouldn't be executed at all, and factorialValue would remain 1. You may safely remove the special case test.
The calculations of the binomial wastes time by recomputing factorials of the same number over and over again. The way the main loop in calculateRowValues is set up exaggerates the problem. Consider precomputing the list of required factorials once.
The code begins to fail at fairly small n: \$14!\$ is already beyond the 32-bit range. I recommend drop the factorial approach whatsoever, and compute the next row directly from the previous, using an \$\binom{n+1}{k} = \binom{n}{k-1} + \binom{n}{k}\$ identity.


@Loki Astari is correct in his comment:

  rand() is well know for its bad distribution. But you are using it correctly. Note: rand() % currentIndexCounter does not give you a perfect distribution unless currentIndexCounter is an exact divisor of RAND_MAX. You may want to look at C++11 random header and the generators provided inside.

Since you're using C++11, you should instead utilize the <random> library.  It includes things such as pseudo-random number generators and random number distributions.

Beyond that, I'll just point out some additional things:

With C++11, you should now be using nullptr instead of NULL.

This should be changed in srand():

std::srand(std::time(nullptr));

However, as mentioned above, you should not be using this with C++11.  But in any situation where you must stay with rand, the above would be recommended.
With C++11, you should also have access to initializer lists.  This will allow you to initialize the vector instead of calling push_back() multiple times:

std::vector<int> elements { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Also note that your push_back() was only pushing numbers 1-8 into the vector, despite what your comment said.  You've used < instead of <= in the loop statement, so the 9 was excluded.
currentIndexCounter should be of type std::vector<int>::size_type, which is the return type of size() (or you can just use auto).  This should've given you compiler warnings as it's a type-mismatch and a possible loss of data.  Make sure your compiler warnings are turned up high.
currentIndex is a misleading name because it's being used with iterators, not indices.

Here, auto gives currentIndex the type std::reverse_iterator from std::rbegin().  You could simply name this something like iter.  It's okay for iterator names to be short.
In the second for loop, you just need elements.rend(), without the - 1.  The iterator will already go through the entire vector and stop at the last reverse element.
The iterator increment should be prefix instead in order to improve performance a bit by avoiding a copy.  It's best to do this with all nontrivial types such as iterators.
I've tested this by giving randomIndex a value greater than elements.size(), causing an exception to be thrown.  Even if std::rand() or another RNG is guaranteed to give you an intended value, it may be best to handle this properly.

Here's the final version with my own given changes, which I've also ran here.  I've also included a concise way of displaying the vector before and after the shuffling.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>

int main()
{
    // seed the RNG
    std::random_device rd;
    std::mt19937 mt(rd());

    std::vector<int> elements { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    std::cout << "Before: ";
    std::copy(elements.cbegin(), elements.cend(),
        std::ostream_iterator<int>(std::cout, " "));

    auto currentIndexCounter = elements.size();

    for (auto iter = elements.rbegin(); iter != elements.rend();
        ++iter, --currentIndexCounter)
    {
        // get int distribution with new range
        std::uniform_int_distribution<> dis(0, currentIndexCounter);
        const int randomIndex = dis(mt);

        if (*iter != elements.at(randomIndex))
        {
            std::swap(elements.at(randomIndex), *iter);
        }
    }

    std::cout << "\nAfter: ";
    std::copy(elements.cbegin(), elements.cend(),
        std::ostream_iterator<int>(std::cout, " "));
}

Output:

Before: 1 2 3 4 5 6 7 8 9
After: 7 9 3 2 4 5 6 1 8


Get tuple of the first and last days of the last N months

def last_n_months(n=12, ending=None):
    """Return a list of tuples of the first/last day of the month
    for the last N months
    """
    from datetime import date
    from dateutil.rrule import rrule, MONTHLY
    from dateutil.relativedelta import relativedelta

It is better to import outside of the function. Typically imports go at the top of the file.

    if not ending:

You should check for none like: if ending is not None: just to be explicit about what you are checking for.

        ending = date.today()

    # set the ending date to the last day of the month
    ending = ending + relativedelta(months=+1, days=-ending.day)

Modifying ending rubs me the wrong way.

    # starting is the first day of the month N months ago
    starting = ending - relativedelta(months=n, day=1)

    months = list(rrule(MONTHLY, bymonthday=(1, -1), dtstart=starting,
                        until=ending))

    # we return pairs of dates like this: (1st day of month, last day of month)
    months = zip(months[::2], months[1::2])

    return months

You can combine these two lines