I hope some late help will still be helpful!
I've erred on the side of providing a bit too much feedback, but this may give you a sense of some of the styles and conventions that Rust uses even if they are overkill for this simple program.

Nicely organized code overall, very understandable and clear use of functions.

In function arguments, it's generally cleaner/more efficient/more idiomatic to accept &str instead of String. This is usually confusing for beginners, but &str is read-only string data and String is an owned, dynamically growable string, so basically if you only need read-only, you should use &str. As a rule of thumb, it's a good starting point to just make all function arguments &str and the return value String. Here's output fixed; noticed that this means you don't have to to .to_string() in your other functions:
fn c_to_f(c: f32) {
    output(c * 1.8 + 32.0, "F");
}

fn f_to_c(f: f32) {
    output((f - 32.0) / 1.8, "C");
}

fn output(t: f32, u: &str) {
    println!("The output temperature is: {}{}", t, u);
}

Although it doesn't make a huge difference for a small project like this, another good rule of thumb is to avoid functions with printing behavior; instead functions should return Strings, and only the top-level program (i.e. main function) prints. So let's change fn output again. All we need to do is use format! instead of println! (and print in main):
fn c_to_f(c: f32) -> String {
    output(c * 1.8 + 32.0, "F")
}

fn f_to_c(f: f32) -> String {
    output((f - 32.0) / 1.8, "C")
}

fn output(t: f32, u: &str) -> String {
    format!("The output temperature is: {}{}", t, u)
}

The let value: f32 logic is a bit verbose, the usual function for this is unwrap_or_else:
let value: f32 = value.trim().parse().unwrap_or_else(|_| {
    panic!("{} is not a number", value)
});

In the line let (value, unit) = temperature.split_at(temperature.len() - 2), this use of split_at is considered fragile and mostly discouraged. Remember that in Rust strings are not just sequences of bytes, but valid UTF-8 data where the characters may not correspond to bytes. So this code introduces a silent failure (i.e. one that is not explicitly exposed and dealt with by the application): I tried running your program on input 4  and I got
thread 'main' panicked at 'byte index 5 is not a char boundary; it is inside ''

In fact, there is actually a second similar issue in the same line: when run with an empty input line in release mode, you have integer underflow:
thread 'main' panicked at 'byte index 18446744073709551615 is out of bounds of `
`'

These edge cases do not introduce a bigger problem for your case, but in production code such failures could cause an unexpected crash, or worse, a security vulnerability. So the preference in Rust is always to be explicit about handling errors. You can browse the functions available in the documentation https://doc.rust-lang.org/std/primitive.str.html for some ideas of how to parse strings in general; here the easiest is probably to explicitly check for both errors:
let mid = temperature.len().checked_sub(2).expect("Input string was empty");
if !temperature.is_char_boundary(mid) {
    panic!("Input should end in a single-byte char (the unit)");
}
let (value, unit) = temperature.split_at(mid);

If you only need mutability for a temporary amount of time (as with temperature), it's good practice to declare the variable immutable after that: let temperature = temperature

The last part of main can be reduced a bit by using match instead of if: match unit.as_str() {

Finally, for extensibility it would be great to abstract temperature into an appropriate type; Rust programmers like to leverage static types to make sure they keep for example Celsius and Fahrenheit values separate, without any actual overhead at runtime. Although I won't change your code for this, you would define types like so:
struct Fahrenheit(f64);
struct Celsius(f64);

You could alternatively have a Temperature type if you want a lot of functionality related to temperatures in general:
enum Temperature {
    Fahrenheit(f64),
    Celsius(f64),
}

Then, you would define parsing functions (parse from &str), display functions (convert to String), and so on on those types, rather than including all of this in main.

Here's the final code incorporating all the suggestions except the last one:
use std::io;

fn main() {
    println!("Enter a temperature.");

    let mut temperature = String::new();
    io::stdin()
        .read_line(&mut temperature)
        .expect("Failed to read temperature");
    let temperature = temperature;

    let mid = temperature.len().checked_sub(2).expect("Input string was empty");
    if !temperature.is_char_boundary(mid) {
        panic!("Input should end in a single-byte char (the unit)");
    }
    let (value, unit) = temperature.split_at(mid);

    let value: f32 = value.trim().parse().unwrap_or_else(|_| {
        panic!("{} is not a number", value)
    });
    let unit = unit.trim().to_lowercase();

    println!("The input temperature is: {}", temperature);

    match unit.as_str() {
        "c" => println!("{}", c_to_f(value)),
        "f" => println!("{}", f_to_c(value)),
        _ => panic!("Unsupported unit"),
    }
}

fn c_to_f(c: f32) -> String {
    output(c * 1.8 + 32.0, "F")
}

fn f_to_c(f: f32) -> String {
    output((f - 32.0) / 1.8, "C")
}

fn output(t: f32, u: &str) -> String {
    format!("The output temperature is: {}{}", t, u)
}


Function to split either a string array or string into a string array

if (delimiter == "<newline>") delimiter = "\n";

Why do you need this? Why not use normal strings?

if (thevar.GetType() == typeof(string)) {

What's wrong with normal method overloading?

if (thevar.GetType() == typeof(string)) {...}
if (thevar.GetType() == typeof(string[])) {...}
return null;

If arguments is not valid throw an ArgumentException. Don't say "I'll just return null, and see where it will go wrong."

temp.Split(new string[] {delimiter}, System.StringSplitOptions.None);

This bit repeats, and should be extracted into a method.

for (int i = 0; i < tempr.Length; i++) {
    for (int j = 0; j < tempr[i].Length; j++) {

Use Linq to simplify loop operations.

Here is the cleaned up version:

    public IEnumerable<string> Split(string str, string delimiter)
    {
        return str.Split(new[]{delimiter}, StringSplitOptions.None);
    }

    public IEnumerable<string> Split(IEnumerable<string> arr, string delimiter) {
        return arr.SelectMany(s => Split(s, delimiter));
    }


@demrks please take a look at the code below. It's a result of multiple refactoring iterations.

While the original code does the job, I find it very hard to read. Hopefully, you agree that the improved version reads better, even though there's very little new in it. Many developers including myself believe that readability is a super important aspect of coding because it directly affects complexity, and thus correctness of the code.

Here's the list of techniques I applied (in order of importance as I understand things):

Naming

Name things properly and do not abbreviate words. createNewRowElementAndInsertIntoForm(...) is definitely not a short name, but it's describing what it does with 100% precision.

Similarly, original elCol transformed into columnElement. It may be funny, but first seeing elCol I thought I'm reading code in Spanish. :)

Please never never never use the i, j, c, and similar. They are absolutely meaningless. Yes, the other dev "may understand" it, but you don't want anyone to guess what the code does. Spell things out, in most of the modern editors it's a matter of hitting <F2>.

Temporary variables constants

Do not hesitate to introduce reusable temporary constants with descriptive names. They make cryptic conditions if (order[i]) or if (!elRows[i]) relay the intent of the writer.

Avoid branching when possible, or minimize its "scope"

An unnecessary if-then-else for processing array/non-array orders may be generalized, if we normalize the array first.

Was:

if (!Array.isArray(order[i])) {
  moveColumn(elForm, elRows[i], order[i]);
} else {
  for (j = order[i].length - 1; j >= 0; j--) {
    moveColumn(elForm, elRows[i], order[i][j]);
  };
}

Became (longer because of the name, but the branching is almost eliminated by a ternary operator that cleans the input):

const normalizerRowPrescribedOrder =
  Array.isArray(rowPrescribedOrder) ? rowPrescribedOrder : [rowPrescribedOrder];

for (let columnIndex = normalizerRowPrescribedOrder.length - 1; columnIndex >= 0; columnIndex--) {
  findColumnByNameAndMoveToBeginningOfRow(formElement, currentRowElement, normalizerRowPrescribedOrder[columnIndex]);
};

"Newspaper"

Make code read top to bottom aka newspaper style (reorder() is the entry point which invokes createNewRowElementAndInsertIntoForm(), therefore reorder() should go first). Forcing the reader to jump around the code is distracting from the act of active reading, therefore leading to avoidable complications.

Result

const form = (() => {
  const columnClassName = 'formCol';
  const rowClassName = 'formRow';
  const clearClassName = 'clear';

  function reorderForm(formElement, prescribedOrder) {
    const rowElementList = formElement.querySelectorAll(`.${rowClassName}`);
    const maxRowLength = Math.max(rowElementList.length, prescribedOrder.length);

    for (let rowIndex = 0; rowIndex < maxRowLength; rowIndex++) {
      const currentRowElement = rowElementList[rowIndex] || createNewRowElementAndInsertIntoForm(formElement);

      const rowPrescribedOrder = prescribedOrder[rowIndex];
      if (!rowPrescribedOrder) {
        const columnElement = currentRowElement.querySelector(`.${columnClassName}`);
        if (!columnElement) {
          removeRowElement(currentRowElement);
        }
      } else {
        const normalizedRowPrescribedOrder = Array.isArray(rowPrescribedOrder) ? rowPrescribedOrder : [rowPrescribedOrder];
        for (let columnIndex = normalizedRowPrescribedOrder.length - 1; columnIndex >= 0; columnIndex--) {
          findColumnByNameAndMoveToBeginningOfRow(formElement, currentRowElement, normalizedRowPrescribedOrder[columnIndex]);
        };
      }
    }
  }

  function createNewRowElementAndInsertIntoForm(formElement) {
    const rowElement = document.createElement('div');
    rowElement.className = rowClassName;

    const clearElement = document.createElement('div');
    clearElement.className = clearClassName;

    rowElement.appendChild(clearElement);

    formElement.insertAdjacentElement('beforeEnd', rowElement);

    return rowElement;
  }

  function findColumnByNameAndMoveToBeginningOfRow(formElement, rowElement, columnName) {
    const columnElement = formElement.querySelector(`.${columnClassName}[data-id='${columnName}']`);
    rowElement.insertAdjacentElement('afterbegin', columnElement);
  }

  function removeRowElement(rowElement) {
    rowElement.parentNode.removeChild(rowElement);
  }

  return {
    reorderForm,
    // other functions for form
  };
})();

form.reorderForm(document.querySelector('.form'), [
  ['Last', 'City'],
  'First',
  'Country',
  'Phone',
]);

P.S.

It's really nice to see how one uses native API instead of jQuery!


A better implementation of the `execvp` call: the code implements `execvp`

The implementation is non-conformant.

No handling of undefined PATH. Quoting man execp:

search path is the path specified in the environment by
``PATH'' variable.  If this variable is not specified, the default path
is set according to the _PATH_DEFPATH definition in <paths.h>

Once confstr returns 0, check errno, and act accordingly.

Calling abort on execv failure is plain wrong. At least return what execv returns.

Calling access is also incorrect. If the file exists, but doesn't have correct permissions, execvp shall continue searching.

As a side note, access is very rarely useful. Consider calling execvp blindly, and testing errno upon return.

Final errno = ENOENT; is also non-compliant. execvp sets ENOENT if the file does not exist in any path. If it was found at least once, and fails to execute, the errno shall be EACCES.

execvp is not supposed to fprintf anything.


A simple program using branching to guess the answer

I think in general this is fine. The only things I'd point out are stylistic really.

In Ruby, many people would prefer double-quoted strings, which allow you to: Got it; your number is #{number}, right?. Note that this also relies on an implicit #to_s on number. It also allows single quotes to be used without escaping.
Look out for variable naming. Naming things correctly is notoriously hard, even after years of experience, and number is a bit generic.
I would definitely put the if conditional on the same line as the if. If the expression is too long or a bit difficult to instinctively understand, assign its value to a variable with a meaningful name (e.g. correctly_added_six = number_plus_6.to_i == number.to_i * 2 + 6) so your condition is more easily understood (e.g. if correctly_added_six)

Good start, though!


Checking whether a number is a power of 10

Recursing seems pretty heavy for this. You can use much the same logic but with a simple loop:
while (input >= 10 && input % 10 == 0)
  input /= 10;
return input == 1;

This checks to make sure the input is at least 10 (since any integers below that, including zero and negative values, can't be powers of 10) and also a multiple of 10 (as all powers of 10 greater than 1 obviously are). It does the simpler comparison first as a small micro-optimization; the short-circuit evaluation will avoid performing an unnecessary division to compute an unneeded modulus.
If both conditions are met it does an integer division by 10 and repeats the process. For any power of 10, this will terminate with the value 1; if 1 itself is passed in, it will do so without ever executing the body of the while loop.


Separating logic and presentation in wordpress

Actually, there is something better, and that is using templates. Yes, it might be "radical" especially when you see no other developer near you use it. And yes, even my college instructors and friends don't know what templates are and still stuff logic with the presentation so I know how it feels as well.

I suggest you take a look at Mustache for starters. Basically, your templates will be logicless. The template will only contain a bit of custom markup. What your logic will only need to do is load the data, load the template, use the render function and it returns rendered markup, complete with the data.


General Hints

Naming

Your code does not respect Java Naming Conventions. The constants (static final members) names should be ALL_UPPER_CASE.

Singelton Pattern

Do not use the Singelton pattern. It makes it hard to reuse the code using this one in general and to test (in UnitTests) in particular.

BTW: you did it wrong.

Comments

Comments should explain why the code is like it is.

Your comments simply lie.

Following your comments the first method in JsonHttpResponseHandler should throw the exception, not the second.

This problem is quite common in code under development. Someone changes the behavior of the code but does not adjust the comments, turning them into lies.

So just delete the comments.

Supporting DRY

Often you don't have pure duplicated code. In most cases you have similar looking code which you usually quite easily can change to equal code by simple refactorings and/or by applying design patterns.

This goes basically in 3 steps.

identify similar code
make similar code the same
remove the duplication

Since this process is expected not to change the behavior of your application you should better have UnitTest that fix the desired behavior so that you get immediate response when you broke something.

Identify similar code

The biggest block of duplication is the anonymous inner class of type JsonHttpResponseHandler which is created twice with the almost same content.

The only difference is the check for the user being null.

Make similar code the same

In this step you convert individual similar parts of your code to look exactly the same.
Avoid typing as much as possible and rely on your IDEs refactorings like extract to local variable, rename in file and alike.

If the execution context of the first JsonHttpResponseHandler implementation guarantees that user never references null then you could simply copy the null check to it to make the same as the second.

Skip the rest of the section if that applies.

If not you should refactor out the difference. You could do so  by introducing a new interface:

public class Caller {
  private interface ActivityCaller{
     void handle(ShareActivity activity,JSONObject user);
  }

Then you implement the interface with the respective behavior before creating the instance of JsonHttpResponseHandler:

// first version
RequestParams params = new RequestParams(map);
ActivityCaller activityCaller = (a,user)-> a.handleUser(user); // java8 Lambda Style, lambda parameter name 'a' must differ from the methods parameter name
get(registerUrl, params, new JsonHttpResponseHandler() {
  @Override
  public void onSuccess(int statusCode, Header[] headers, JSONObject user) {
     activityCaller.handleUser(activity,user);
  }
  // .. no changes after here

// second versionRequestParams params = new RequestParams(map);
ActivityCaller activityCaller = new ActivityCaller(){ // traditional annonymous inner class
 @Override
  public void handle(ShareActivity activity,JSONObject user){
    if(user!=null){
        activity.handleUser(user);
    }else {
        activity.registerUser();
    }
  }
}
get(registerUrl, params, new JsonHttpResponseHandler() {
  @Override
  public void onSuccess(int statusCode, Header[] headers, JSONObject user) {
     activityCaller.handleUser(activity,user);
  }
  // .. no changes after here

Remove the duplication

Now both anonymous inner class implementations of JsonHttpResponseHandler are exactly the same. Use your IDEs convert anonymous to inner class refactoring to replace both occurrences.

This creates a new inner class:

// assumed you copied the `null` check
public class Caller {
  private static class JsonHttpResponseHandlerImpl{
    private final ShareActivity activity; // if you copied the null check
    JsonHttpResponseHandlerImpl(ShareActivity activity){
      this.activity = activity;
    }
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject user) {
        if(user!=null){
            activity.handleUser(user);
        }else {
            activity.registerUser();
        }
    }
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONArray array) {
        throw new RuntimeException("array in stead of object");
    }
  }

and both of your methods change to:

   RequestParams params = new RequestParams(map);
   get(registerUrl, params, new JsonHttpResponseHandlerImpl(activity));

As a result you have even more common code in both methods which you could easily move to the common get method.

What's left in your getUser() methods it the creation of the map with different content and the implementations of the new ActivityCaller interface if you decided for this way.


Python program to find the factorial of a number using recursion

Looking over your code, this is what I have for you:

Your function can be turned into a one-liner
You should use if __name__ == '__main__' to ensure you're not running this program externally.

Refactored Code:

def recur_factorial(x):
  return 1 if x == 1 else (x * recur_factorial(x - 1))

def main():
  num = int(input("Enter number: "))
  print("The factorial of", num, "is", recur_factorial(num))

if __name__ == '__main__':
  main()

You can read this StackOverflow question for more information about the advantages and disadvantages of recursion


At first glance, I thought, WOW, Nice library!
Decent variable and function names, decent indentation. Some application of
good software engineering principle such as the Single Responsibility Principle and the KISS principle.

On further inspection I found a few issues:

Error handling Versus Error Reporting
The code does handle errors and return a status of the function, but there
is no error reporting. Standard C library functions such as access(),
fopen() and stat() return the actual error code in the global
variable errno. By including errno.h you have access to the error
codes and can report what is causing the error to the user/programmer
using the entropy library using perror() or stderror(). There is also
a discussion of this on stackoverflow.com. I know that if I was using
this library I would like to know whether a file is not found, or I
don't have read permission on the file.

A common practice when returning status of a function
such as entropy(), get_times() or calc_frequencies()
is to include stdlib.h and return either EXIT_SUCCESS or EXIT_FAILURE
instead of using OK or EREAD.

Direct Addressing Versus Indirect Addressing
One fairly common optimization in C is to use pointers (Direct Addressing)
instead of indexes (Indirect Addressing) when accessing the contents
of arrays. Direct Addressing is faster than Indirect Addressing. In some
cases using the highest level of optimization when compiling will convert
indirect addressing to direct addressing.

In most of the for loops in the library the code is using indirect
addressing:

    for (iter = INIT; iter < ASCII; iter++)
    {
      if (table_of_chars[iter] != INIT)
      table_of_chars[iter] = (double)(table_of_chars[iter] / file_size);
    }

Performance may be improved by:

    double *toc_p = &table_of_chars[0];
    for (iter = INIT; iter < ASCII; iter++, toc_p++)
    {
      if (*toc_p != INIT)
      *toc_p = (double)(*toc_p / file_size);
    }

An enhanced optimization would be:

static int calc_frequencies(double table_of_chars[ASCII], const char * file)
{
  unsigned long long int file_size = wc(file);
  if (file_size != (unsigned)EREAD)
  {
    register int iter;
    register double *toc_p = &table_of_chars[0];
    for (iter = INIT; iter < ASCII; iter++, toc_p++)
    {
      if (*toc_p != INIT)
      *toc_p = (double)(*toc_p / file_size);
    }

   return OK;
  }

  return EREAD;
}

Improve Type Safety
The library as written may insert floating point errors in the following
code:

    while ((getch = getc(fget)) != EOF)
    {
      table_of_chars[getch]++;
    }

It is somewhat rare to see the increment a float or double value in C.

I would suggest that table_of_chars be a table of integers rather than
doubles. A second array of doubles could be returned by calc_frequencies().

Variable and Function Names
In some languages, such as Pascal the name of the function is
assigned the return value. This is not the case in C, I would
differentiate between a local variable name and the function
name such as using entropy_val as the return value for the
entropy() function. Some C compilers may have problems with
the current implementation.

The function get_times() might be better named as
count_all_character_instances()

On the Unix and Linux operating systems, wc stands for word count, and
returns the file size in lines, words and characters, a more appropriate
name for the function wc() might be get_file_size_in_bytes().

Variable and Function Names
In some languages, such as Pascal the name of the function is
assigned the return value. This is not the case in C, I would
differentiate between a local variable name and the function
name such as using entropy_val as the return value for the
entropy() function. Some C compilers may have problems with
the current implementation.

The function get_times() might be better named as
count_all_character_instances()

On the Unix and Linux operating systems, wc stands for word count, and
returns the file size in lines, words and characters, a more appropriate
name for the function wc() might be get_file_size_in_bytes().

DRY Code, or the Don't Repeat Yourself Principle
Another software engineering principle is the Don't Repeat Yourself Principle.
Most times when you have repetitive code create you should create a function
that contains just that code so that the code is reusable.

Two functions in the code get_times() and wc() contain

  if (access(file, F_OK) != EREAD)
  {
  }

this is repetitive code.

In addition to repeating, system calls such as
access(), fopen(), stat() and fclose() are expensive time wise,
quite often programs or libraries will be swapped out during these
calls. In the execution of this library it is unlikely that the status of
access() will change between calls. For this library it would be
advisable to call these functions only once.

Portability
Back in the old days ASCII was the primary character set on Unix and Linux.
Today the ASCII character set does not support some languages such as Chinese
and Japanese which require wider characters. This library will work for most
western cultures, but it will not support all languages. Some languages
require two bytes per character, rather than one. This is something to
think about for later.

Function Complexity
Both the function get_times() and calc_frequencies() are too
complex, because the second parameter is the file name rather than
a file pointer. File access really only needs to be checked once,
and the file only needs to be opened once. The function entropy()
should call the function wc() directly. The input file should only
be opened and read after stat has been performed.


Sequentially remove members "repelled" by previous members

In all, there's not much to complain about, but I did find a few things that might be improved. All of my comments and testing are about C++11 mode, since that's what I have conveniently available.

Use const references for the predicate

Right now, the lambda in your predicate has values a and b passed by value, which is fine for primitive types such as int but could be relatively costly for classes such as std::complex<double> due to all of the overhead of construction and destruction of temporary objects.  With that said, it's only a minor change since std::abs creates a temporary itself, and this is a quibble with your example use of the the template rather than the template itself.  This is what I used for testing:

typedef std::complex<double> mytype;
auto pred = [](const mytype &a,const mytype &b)->bool{
    return abs(a-b) < 2;
};

Fix the C++11 version of the code

As has been mentioned in comments, the syntax isn't quite right for the C++ version of the lambda in the template.  It should be:

 [p, target](decltype(*target) i)->bool{return p(i, *target); }

Consider encapsulating the erase

It's a bit odd to have to use x.erase() outside of the templated function.  Putting it inside would make usage a little simpler.

Check for empty container in remove_copy_repelled

I tried to exercise the remove_copy_repelled code.  The first thing I tried was this:

std::vector<mytype>x = {1,3,2,8,5,6,7};
std::vector<mytype>x2;
x2.erase(remove_copy_repelled(
    x.cbegin(), x.cend(), x2.begin(), pred), x2.end());

I was rewarded with a core dump.  It doesn't seem to like an empty destination container.

std::vector<mytype>x2;
x2.reserve(x.size());

This worked, but isn't particularly general, so you could do a template specialization, but there may be a better way.  In particular, you might consider constructing the destination container, perhaps using a passed parameter that is a placeholder for push_back or whatever the caller wishes to use to add another object to the container.


I would probably use iter for this:

def get_chunks(l, chunk_lengths):
    it = iter(l)
    for chunk_length in chunk_lengths:
        yield [next(it) for _ in range(chunk_length)]

Usage:

>>> get_chunks(range(100), [1,2,5])
<generator object get_chunks at 0x7f2744f68910>

>>> list(get_chunks(range(100), [1,2,5]))
[[0], [1, 2], [3, 4, 5, 6, 7]]

Review:

I would make your code at least a function that yeilds the slices and give it a nice name, like I did in the function above.

Note that it is frowned upon in python to iterate over the indices of a list, if all you need are the elements. So prefer this:

for item in l:
    print(item)

over

for i in range(len(l)):
    print(l[i])

Also note that using "%s" % var style formatting is the old way of doing it. It is recommended to use str.format, which offers a lot more possibilities (none of which you need here, though).

print("Slice: [{},{}]".format(start, end,))


Prefered Style Container for the Components in the DataTemplate

You can merge the two style in the DataTemplate.Resources so that it can be applied in all the Borders inside the DataTemplate. Refer the below code.

<DataTemplate DataType="{x:Type m:myFoo}">
        <DataTemplate.Resources>
            <!-- 1) Style Applied to the Border -->
            <Style TargetType="Border">
                <Setter Property="Margin" Value="1"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Active}">
                        <Setter Property="Background" Value="OrangeRed"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataTemplate.Resources>
        <Border>
            <Grid>
                <Border>
                    <!-- Guts -->
                 </Border>
            </Grid>
        </Border>
    </DataTemplate>


Merge sort and selection sort comparison taking too long

The first reason that your code is slow is because you are implementing a selection sort which will be slow in any implementation. It has to scan through a large list looking for the values for each iteration. That's gonna be slow.

The second problem is that you freely create new lists. For example:

j = maxIndex(L[0:i+1])

The slice creates a new list and copies the elements in L into it. That works fine when you are dealing with small lists, but in the lists you are playing with here, thats gonna be a significant speed drain. For the most efficiency in cases like this you need to avoid creating new lists altogether and just move stuff between elements in the same list.

All in all, it isn't really much slower then I'd expect the algorithm you are implementing to be in Python. Nothing you are doing should produce pathologically bad performance. However, there is a reason why we use a sort implementation in C. If you are just interested in implementing algorithms for the learning experience, I suggest you use smaller lists. Thats a lot of data to sort with a bad algorithm.


A Cipher with 2 methods for encryption/decryption

forString

As discussed already in comments, your forString method is not needed because map is available to Scala Strings.  But if you do need to construct such a method, your design is not best practice.  Specifically, you create a local var, append to it repeatedly from within a for block and return that.

This block

    var newStr = ""
    for(c <- str) { newStr += f(c) }
    newStr

can be written simply as

    for (c <- str) yield f(c)

Updating an external var from within a for block is a stateful, potentially error-prone, very non-FP practice which you should use with care.  It is not needed here.  Leave the compiler to construct and return the string - it will be more efficient and your code is cleaner as a result.

(It will be more efficient because in the for-yield block, the compiler knows it is creating a sequence one item at a time and begins each step with a ready pointer to the end of the collection.  In contrast, when your code explicitly appends to the end of a sequence each time, it has to traverse the entire sequence each time.  No handy reference to the end of the string is cached. Appending to strings is expensive.)

wrap

Both the original version and the modulo alternative in your answer use if... else if... then chains.  These are a bad smell.  All three of your options depend upon the value of the input parameter, but nothing about an if-elseif-then chain forces you to cite that parameter in each successive condition.  Pattern matching would at least ensure that the same object is being assessed for each action.  That would look something like this:

n match {
    case _ if (n > cHARMAX) => (cHARMIN + (n - cHARMAX) % cRANGE)
    case _ if (n < cHARMIN) => (cHARMAX - (cHARMIN - n) % cRANGE)
    case _ => n
}

However, although I am still not sure why you have this function in there, I think this is what you are trying to do:

n match {
    case _ if (n > cHARMAX) => cHARMIN + ((n - cHARMIN) % cRANGE)
    case _ if (n < cHARMIN) => cHARMAX - ((cHARMIN - n) % cRANGE)
    case _ => n
}

Key length

Repeating the key until it is as long as the message is a waste of resources (more so, the longer the message becomes).  Just leave the key in its original size.  There are several ways to iterate through the message and (effectively or literally) use modulo arithmetic to fetch the corresponding character from the key.

Create an endlessly repeating Stream from the key (fast and efficient).  Then you can just iterate through both in step (for example, using zipped)
for (i <- message.indices) yield myFunction(message(i), key(i % key.length)) (reasonably fast and efficient)
Use zipWithIndex and map to turn the message into a list of tuples (each character bundled with its index) and then iterate through that, using modulo arithmetic on the index to fetch the right key character (less efficient, slower).

Option 1 is best

Cipher class design

The most curious thing about your Cipher class is that its Apply method takes a message as a parameter.  This is not good OO design and it also inverts the meaning of the word (OK, cipher can mean an encrypted text but more commonly it means one particular encryption method with one particular key choice).  It would make more sense for a cipher object to have the key (and possibly some other parameters like, for example, the range of valid characters) as a field.  So you could create a cipher instance containing the key "MyAmazingSecretCode" and then use that object to encrypt or decrypt as many messages as you want.  As things stand, Cipher is mostly a java-like utility class containing static methods, offering no way to maintain any state.

Having the two different encryption options in one class is also less good.  Are you going to rewrite this class every time you add another variant on the encryption method?

Consider, instead, a basic Cipher class or trait or even interface, which describes the key interface methods (setting the secret, encrypting, decrypting).  If it is a class or trait, you could also design an "encryption strategy" trait from which specific encryption methods (your simple offset and your substitution key, as two examples) could be derived.  You could then mix the appropriate strategy trait into the Cipher class to provide a working cipher.  If you choose to make Cipher an interface, then your two strategies could be separate classes which each incorporate that interface.  Which to choose depends on larger design considerations.


Ensuring that events raised by system.diagnostics process class happen in the parent thread

If you want a pretty solution, you would have to separate your data source (process in your case) from data processor (your while loop), hide implementations behind interfaces and then wire those interfaces together via events or aggregation. This is actually a pretty common problem called "Producer-Consumer", you should be able to find multiple decent implementations on the net.

If you want a simple solution though, yours is probably fine. A few things you might want to improve:

Reduce nesting in your while loop to avoid arrow code. This can be done by using break/continue/return statements or by extracting logic to separate method or entity.
Depending on how often you receive messages and on how much time XXXtakes, you might want to release lock before calling XXX.
You might want to wait for process to exit before returning form your method. This will ensure, that everything went smoothly, and there is no process left hanging somewhere due to some error in your code.
If XXX signature is not set in stone, you should probably replace strings with complex object:

class Message
{
   //use enum instead of hardcoded strings, such as "STDERR"
   public MessageType Type { get; set; }
   //actual data from process
   public string Data { get; set; }
}

You should remove hardcoded "magic" strings either way.


Automating easy-rsa cert creation with Bash script

This

myself=auto_rsa_gen.sh # tells the script who it is

is better done like this:

myself="$0"

or, if you want just filename, then

myself="$(basename "$0")"

because it will give you the actual name of the script, instead of being hard-coded. This also opens a nice renaming possibilities if you use symlinks.

This part:

echo "These \n$(ls /dev | grep sd) \nare the drives available. Please tell me which one you want to mount \n(hint: its usually the one having just the  one additional entry. Like sdc1):"

# read user input (blkdev is the variable that will hold the user inuput for further processing)
read blkdev

##
# I. Mount
# check if de given device exists
if [ -b /dev/"$blkdev" ]
        then # if it exists mount it to /media
            sudo mount /dev/$blkdev /media
            echo "\nDevice $blkdev has been mounted!"
        else # if it doesn't exist
            echo "Device doesn't appear to exist! Restarting"
            sh "$myself" # restart the script
        fi

I think is better put in a while loop, instead of restarting a script, like this:

while true; do
  echo "Pick device, blah, blah,... Press Ctrl+C to abort."
  read blkdev
  if [ ! -b /dev/"$blkdev" ]; then
    echo "The device doesn't appear to exist!"
    continue;
  fi
  sudo mount /dev/"$blkdev" /media
  echo "\nDevice '$blkdev' has been mounted!"
done

You might also want to check if the mount command succeeded.

Also, /media is a standard directory for dynamic mounts. That means that your script will hide mountpoints of mounted CDs, DVDs, USB keys,... while it is running, which may be very inconvenient in some situations (for example, if you have some copying done in the background).

Btw, echo 'Line 1\nLine 2' outputs Line 1\nLine 2 instead of two lines (GNU bash, version 4.2.45, Fedora 19). The correct way for this is

echo -e 'Line 1\nLine 2'

I assume you have -e aliased, or on your distribution it is on by default, or something like that. However, it is not portable, so I suggest you add -e where needed.

I also have a bit of a problem with

cd $easy_rsa

These are my concerns:

It has a relative path to the subdirectory. This will hardly produce satisfactory results if your script is invoked from a directory other than you intended it to be invoked from. Maybe this value should either be prompted (with read), or picked up from the command line?
You're not checking that the directory exists. You could force the directory creation (mkdir -p "$easy_rsa"), and - on top of that - check that $0 is true (i.e., equal to 0) afterwards.

In the last line

echo "\nUmounted $blkdev at /media. Exiting! Bye!"ere

This ere in the end seems to be here by an error.

I also have one general remark. Instead of writing echo $something, cd $dir, and similar commands, I suggest you use echo "$something", cd "$dir", etc. There is no point in thinking if one of these may contain space and, when editing your script later on, thinking about fixing this if you do include a space. It's much easier and safer to always behave as if a variable can contain a space and just include the quotation marks.

Also, without the quotation marks, you're in trouble with all the variables that get their values from the user. The example for this is your $blkdev variable which you sometimes enclose in the quotation marks, but sometimes you do not (I added them in the mount command in my loop example above).


JavaScript to fire event every second until 10s then gradually increase

Your code looks decent, but I think you might have overthought the problem and the need for so many variables to be globally declared. What you want is a nice function that does everything you want in one single call, and I think it looks something like this:

function heartbeat(delay, interval, duration, callback){
 var now = Date.now();
 var end = now + delay + duration;
 var inc = function(v){ return v; };
 function beat(){
  var now = Date.now();
  if(now < end){
   callback(now, interval);
   interval = inc(interval);
   timeout = setTimeout(beat, interval);
  }
 }
 var timeout = setTimeout(beat, interval);
 var delayTimeout = setTimeout(function(){
  inc = function(v){ return Math.pow(v, 1.15); }
 }, delay);
 return function(){
  clearTimeout(timeout);
  clearTimeout(delayTimeout);
 }
}

You can call it like this:

heartbeat(10000, 1000, 10000000, function(now, interval){
    console.log('beat', interval / 1000);
});

Now for a bit of reasoning why I did this, starting with the variable declarations you have made. The problem with it is that you need about four variables to do this, but setting them as globals means you can have exactly one timer, and calling a new one requires a lot of setup. On top of that, you code is very attached to its execution - you want to separate the implementation from the actual code that uses it as much as possible.

First improvement here is using closures. Since you pass a couple of variables and define the actual bulk of the code inside the function, everything has access to these variables inside the function, but not outside. So your _config and _lastheartbeat variables are not shared by anyone else, and they reference themselves internally so they don't clash. Want to start another heartbeat? No problem, it's variables are contained.

As a last touch, your function needed a return value, something useful, so I decided to return a function that will cancel the timeouts, again thanks to the magic of closures.


Tiny Lua library to get char pointer from string

I'm no Lua expert, but I can at least give you a pointer (no pun intended) about your C code.

Your get_pointer function looks like it works fine, but it could be made even more concise! Lua provides a luaL_checkstring function that combines luaL_checktype and luaL_tostring. Therefore, you could just do this:

int get_pointer(lua_State *L)
{
    lua_pushlightuserdata(L, (void *) luaL_checkstring(L, 1));
    return 1;
}


C++ Beginner. Project Euler 14: Longest Collatz sequence under one million

I will try and tackle correctness, style and performance in that order

Corectness

My initial guess, for wrong results would be you are overflowing an int for long sequences. making x0 an unsigned long I get the longest sequence as 524, for 837799, which matches the results at https://www.dcode.fr/collatz-conjecture . Indeed that sequence contains 2974984576 which will overflow a signed int.

Style

Your code is very c-like and has not really used any c++ features other than cout. Some things I would change:

avoid using namespace std, see https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice This is generally considered bad practise as it you can get unexpected name collisions. It probably won't cause any real issues on a small project like this, but is a bad habit to get into.
Prefer stl containers to raw arrays. Stl containers have many advantages over raw arrays. In your case I would make k a std::array, i.e. std::array< std::size_t,  n-2 > k; std::arrays are fixed size containers very similar to raw arrays, but don't decay to pointers, provide iterators and to allow easily looping over the elements ( and interacting with the rest of the stl ), among other features.
Your update of x0 is not very clear/easy to read. I would break this into the two cases with and if/else, and probably make it a separate function. i.e.

if( x0%2 )
{
    x0 = 3*x0 + 1;
}
else
{
    x0 = x0/2;
}

Use stl functions rather than writing your own. Another advantage of using stl containers is there are many standard functions that use the containers, which can save you having to write your own. e.g. std::max_element this could simplify your calculation of max value and index.

auto maxIt = std::max_element(k.begin(), k.end());
int maxSeq = std::distance(k.begin(), maxIt) + 2;
unsigned long maxValue = k[maxSeq - 2];

Make values unsigned if they cannot be < 0. None of your values should be <0, for clarity it is good practise to make them in this case. The normal way to do this for ints is to use std::size_t. This helps clarify the intent of your code.

Performance

Your code seems to have pretty good performance and has no trivial performance improvements that I can see. Possibly the updating of x0 can be written more efficiently, but I would change it for clarity reasons, as mentioned above, and profile any possible performance changes from there.

I will note that the sequence does not depend on previous values, so if you reach a value already calculated k for you do not need to calculate the rest of the sequence, but can just add that value. Again you would need to profile whether the cost of doing the extra checks gives an actual improvement.


jQuery script to toggle an element and handle a Close button

function findNextContent(target){
    var nextContent = target.parent().parent().parent().find(toggleContent);
    return nextContent;
}

You could possibly use the jQuery closest function here.
Or you could remove the variable and just do return target.parent().parent().parent().find(toggleContent);

toggleClose.click(function(){
    var clicked     = $(this);
    var nextContent = findNextContent(clicked);
    closeToggle(nextContent);
    return false;
});

There is no need for the clicked variable. You can just write findNextContent($(this));

You might also want to look into the aria-expanded attribute.


public Transform[] obstaclePrefab;

That's wrong. Prefabs are of type GameObject, not Transform.

private float minSpawnTime;
private float maxSpawnTime;

Why did you make these private? They should have been public with default values - just as all the others.

private float boxPositionY;
private float boxPositionX;
// Distances
private float playerDistance;
private float boxDistance;
private float ySpread;

These shouldn't even been private, but local to the Update() method, as their values are never reused.

// Select box color
int boxColor = Random.Range(0, 4);

This is very likely to break. Better read the array length instead of hard coding it:

// Select box color
int boxColor = Random.Range(0, obstaclePrefab.Length - 1);

Or just get rid of boxColor all together:

// Select box
GameObject box = obstaclePrefab[Random.Range(0, obstaclePrefab.Length - 1)];

// Count the random spawn time
timeCounter += Time.deltaTime;
if(timeCounter >= spawnTime)
{
    // Make new random spawn time
    spawnTime = Random.Range (minSpawnTime, maxSpawnTime);
    timeCounter = 0;
}

That's one way to do it. The cleaner method would have been to handle this in a Coroutine and then use WaitForSeconds. Right now, your code runs every single frame, without actually doing anything useful.

Debug.Log ("Spawn Time: " + spawnTime + " spawnCount: " + timeCounter);

Be careful when you log. Logging when something spawns? OK. But spamming a log entry every single frame? Waste of resources.

boxPositionX = (boxPositionX-1)*2.0f;

What is this line supposed to do? That should have been directly computed into minXDistance and maxXDistance, so this line is obsolete.

If this is actually supposed to be C#, the whole script you posted should actually have wrapped in a regular C# class:

using UnityEngine;
using System.Collections;

public class ScriptName : MonoBehaviour {
    // <---- Your stuff goes here
}

Did you just omit this when posting your code here, or did you actually write your scripts without it?


One thing I'd suggest is to allow a word to be inserted inside __init__, rather than force the user to always call .insert(word). You can still allow for creating an empty TrieTree. Just make word an optional parameter, and ignore it if it's empty:

def __init__(self, word=''):
    self.root = TrieNode()
    if word:
        self.insert(word)

now you could create your tree in one line:

index = TrieTree(word)


Optimizing Java Anagram checker (compare 2 strings)

Start with a simple, easy to understand version. Try to reuse API functions.

import java.util.Arrays;
...

public boolean areAnagrams(String s1, String s2) {
    char[] ch1 = s1.toCharArray();
    char[] ch2 = s2.toCharArray();
    Arrays.sort(ch1);
    Arrays.sort(ch2);
    return Arrays.equals(ch1,ch2);
}

Of course this is not the fastest way, but in 99% it is "good enough", and you can see what's going on. I would not even consider to juggle with things like deleted chars in StringBuilder if there were no serious performance problem.


Not if I understand what you're doing correctly.

So essentially each image has itself, and then some other element that should be before it as a buddy? Assuming they are all siblings, you should utilize some of jQuery's functions that support working with siblings.

Here's an example, though I'm sure it could still be better:

var arrangeLayers = function (e, direction) {
    var $target = $(e);
    var $targetBuddy = $target.prev();
    if (direction === 'down') {
        if($targetBuddy.index() > 1) {
            $target.insertBefore($targetBuddy.prev().prev());
        }
    } else {
        if ($target.index() !=$target.siblings().length) {
            $target.insertAfter($target.next().next());
        }
    }
    $targetBuddy.insertBefore($target);
}

Or if you don't care about index error checking (which in actual practice appears to not matter):

var arrangeLayers = function (e, direction) {
    var $target = $(e);
    var $targetBuddy = $target.prev();
    if (direction === 'down') {
        $target.insertBefore($targetBuddy.prev().prev());
    } else {
        $target.insertAfter($target.next().next());
    }
    $targetBuddy.insertBefore($target);
}

Here's a jsfiddle without the checking:


If you want to learn how to use classes, the best approach is to use them while building a small program. I suggest you do create a Person class and that you stop using dataset. This will be a great learnign experience.

Using numbers instead of const or strings can create a mantenance problem. At a glance, it's not easy to know what 15 mean.

ds.Tables(0).Rows(0).Item(15)

Remove all the database query from the UI. It'll also make the code more readable and you'll be able to reuse the functions if needed. You should have the connection string at one place.

Public Class EmployeeUpdateFrm

    Private Sub Load(sender As Object, e As EventArgs) Handles MyBase.Load

        LoadDropDown()

        ' ...

    End Sub

    Sub LoadDropDown()

        Dim companies As List(Of Company)

        companies = DAL.GetCompanies()

        With CompanyCbx
            'what the user sees
            .DisplayMember = "Name"
            'value behind each display member
            .ValueMember = "Id"
            .DataSource = companies
            .SelectedIndex = 0
        End With

    End Sub

End Class

Public Class DAL

    Private Shared _connectionString As String = "Data Source=SQLTEST_HR,4000\SQLEXPRESS;Integrated Security=True"

    Public Shared Function GetCompanies() As List(Of Company)
       ' ...
    End Function

End Class

Public Class Company

    Public Property Id As Integer
    Public Property Name As String

End Class


An algorithm to calculate the check digit for 18-digit SSCC GS1 codes

First, you iterate through the input string twice: the first time when converting string to int[] SSCCArray and the second time when iterating through array.

Next, you don't need to know the position itself in the array (or string), you just need to know if the position is odd or even. This can be reached via bool variable.

Next, what is the input string has some invalid chars? It makes sense to handle this case.

My proposal:

private static int getCheckDigit(string sscc)
{
    int oddPisitonsSum = 0;
    int evenPositionsSum = 0;

    bool evenPosition = false;

    foreach (char c in sscc)
    {
        int i = (int)char.GetNumericValue(c);
        if (i < 0)
        {
            // Invalid char detected
            continue; // or throw an exception
        }

        if (evenPosition)
        {
            evenPositionsSum += i;
        }
        else
        {
            oddPisitonsSum += i;
        }
        evenPosition = !evenPosition; // Toggle the flag
    }
    int totalSum = oddPisitonsSum * 3 + evenPositionsSum;
    int mod10Remainder = totalSum % 10;

    return mod10Remainder == 0 ? mod10Remainder : 10 - mod10Remainder;
}


Index Match with multiple columns using input boxes

VBE -> Menu Bar -> Tools -> Options

I recommend turning off [ ] Auto Syntax Check and turning on [x] Require Variable Declaration

Turning off Auto Syntax Check will stop those annoying messages from popping up when you are writing code.  The VB Editor highlights syntax errors in red anyway.  The messages do nothing but break the workflow and slow you down.

Require Variable Declaration inserts Option Explicit at the top of newly created code modules.  Option Explicit requires that all variables be declared. Ideally, all variable should be declared and strongly typed.

Declaring Variables

These variables were not declared:

Dim LastSourceID As Long, LastTargetID As Long, LastValue As Long, MyColumn As Long, NextColumn As Long, TargetIDcolumn As Long, ValuesColumn As Long, SourceIDcolumn As Long

I prefer grouping my variables (at the top of the procedure), roughly 1 Dim statement per datatype. I do not like having to scroll to see what the code is doing.

The first thing that stands out is that the Title and Prompt variables are constant values and should be declared as Constants.

'set prompts
Const Prompt1 As String = "Select values to pull (1 or more columns)"
Const Prompt2 As String = "Select unique IDs on target sheet (1 column only)"
Const Prompt3 As String = "Select unique IDs on source sheet (1 column only)"
Const Prompt4 As String = "Select any range on target sheet"

'set titles
Const Title1 As String = "Source Sheet"
Const Title2 As String = "Target Sheet"
Const Title3 As String = "Source Sheet"
Const Title4 As String = "Target Sheet"

Constants can also be grouped but I usually don't because it can make them difficult to reference and modify.

'set prompts
Const Prompt1 As String = "Select values to pull (1 or more columns)",Prompt2 As String = "Select unique IDs on target sheet (1 column only)", Prompt3 As String = "Select unique IDs on source sheet (1 column only)",Prompt4 As String = "Select any range on target sheet"

'set titles
Const Title1 As String = "Source Sheet", Title2 As String = "Target Sheet", Title3 As String = "Source Sheet",Title4 As String = "Target Sheet"

Helper Variables

"Helper Variables" are great when they are helpful.  Many times they are just extra clutter that you have to work through.

Prompt1 is helpful because of the length of the string and these is something that you will probably consider modifying in the future.

Const Prompt1 As String = "Select values to pull (1 or more columns)"

Title1 is pretty short and easily modified where it is used.  I would not have bothered with it.

Set ValuesToPull = Application.InputBox(Prompt1, "Source Sheet", Type:=8)

I personally would save the space and use one of the following:

Set ValuesToPull = Application.InputBox("Select values to pull (1 or more columns)", "Source Sheet", Type:=8)

Set ValuesToPull = Application.InputBox( _
                   "Select values to pull (1 or more columns)", _
                   "Source Sheet" _
                   , Type:=8)

Set ValuesToPull = Application.InputBox( _
                   Prompt:="Select values to pull (1 or more columns)", _
                   Title:="Source Sheet" _
                   , Type:=8)

Are Source1, Target1, SourceIDcolumn, and LastSourceID really needed?

I like to use the Optometrist Analogy when reviewing code.

Which is clearer, Code 1 or Code 2?

Code 1:

With Source1
    Set SourceIDs = .Range(.Cells(1, SourceIDcolumn), .Cells(LastSourceID, SourceIDcolumn))
End With

Code 2:

With SourceIDs.Worksheet
    Set SourceIDs = .Range(.Cells(1, SourceIDcolumn), .Cells(LastSourceID, SourceIDcolumn))
End With

Which is clearer, Code 2 or Code 3?

Code 3:

Set ValuesToPull = Intersect(SourceIDs.EntireRow, ValuesToPull.EntireColumn)

For me Code 3 is clearer.  But not everyone sees code the same way.  You should use the one that is easiest for you to read.  Note:  If you didn't choose Code 3, you might want to consider Lasik.

Repeated Code Patterns

Repeated code patterns in a subroutine is a sign that potions of the code can and probably should be extracted into a separate subroutine.  This will make both the main and extracted code easier to read, debug, and modify.

Public Function getInputRange(Prompt As String, Title As String, Optional AllowMultipleColumns As Boolean) As Range
    Dim Target As Range
    Set Target = Application.InputBox(Prompt, Title, Type:=8)

    If Target Is Nothing Then Exit Function
    If Target.Columns.Count > 1 And Not AllowMultipleColumns Then Exit Function

    With Target.EntireColumn
        Set Target = Range(.Cells(1, 1), .Cells(.Rows.Count).End(xlUp))
    End With

    Set getInputRange = Target
End Function

Other Considerations

Are there Column Headers?
    hasColumnHeader = MsgBox("Do the Ranges Contain Column Headers?", vbYesNo, "Column Header")

Rows.Count should be qualified to the same worksheet the Target1.

Target1.Cells(Rows.Count

Performance

Turning off Application.Application.ScreenUpdating and setting Calculation = xlCalculationManual will greatly improve the performance of code that modify the formats and values of worksheets.

Public Sub SpeedBoost(TurnOn As Boolean)
    With Application
        .Calculation = IIf(TurnOn, xlCalculationManual, xlCalculationAutomatic)
        .ScreenUpdating = Not TurnOn
    End With
End Sub

Reading values from an array is a little faster than reading values from a range.  Writing multiple values from an array to a range in 1 operating is much faster than multiple writes.

Dictionaries are much faster than Application.Match. Reference:Analyst Cave: EXCEL VLOOKUP VS INDEX MATCH VS SQL VS VBA


Exception handling

Throwing Exception is not recommended because it's too generic.
It doesn't give a clue to the caller as to what went wrong.
It's recommended to use specific exceptions.

When implementing a collection abstract data type, it's good to take a look at a similar interface in the standard library, for example Deque:

How do they handle when an element cannot be added due to capacity restrictions? They throw IllegalArgumentException.
How do they handle when an element is requested but the collection is empty? They throw NoSuchElementException.

As you see, suitable specific exceptions already exist.
Also notice that these exceptions are unchecked.
It means that callers of these methods don't have to catch them.
And that seems an appropriate decision,
since the situations in which these exceptions can be thrown are quite unexpected, and should not happen under normal circumstances.

Redundant capacity variable

The member variable capacity is redundant.
The same information already exists in elements.length.

Make members final when possible

Since elements is never reassigned, it would be good to make it final,
so that you cannot reassign by mistake.

Overriding toString

Keep in mind that toString is not intended for "pretty-printing".

And for printing the content of the heap,
this implementation doesn't look useful to me.
With the null values removed,
the structure of the heap is not visible,
and without the structure, the ordering of the elements is meaningless,
which can be misleading.

For printing the content of the heap I would suggest adding a dedicated method,
keep the nulls, and print values of the first size elements.


Django Unified Method for Deleting Instances of Any Model

The use of eval() here is less than ideal as it allows you to call the URL delete/User/3/, for instance, and it will work against all odds. Worse, you can call the URL delete/delete/9 where eval will resolve delete to this view function and lead to all kind of weird behavior.

So the first step is to restrict which symbols can be found from there. The easiest way is to retrieve the attribute directly from your models:

from . import models

...

def delete(request, type_name, object_id):
    try:
        cls = getattr(models, type_name)
    except AttributeError:
        raise Http404
    get_object_or_404(cls, id=object_id).delete()
    redirect(dashboard)

But this is still too large as anything that you imported in models can still be retrieved. So you're better off using a base class in your models.py that only your deletable models will inherit from:

class Deletable:
    def can_delete(self, user):
        return user.is_active and user.is_staff

class OneOfYourCustomModel(Deletable, models.Model):
    # whatever

And check in your view that whatever you get is Deletable:

def delete(request, type_name, object_id):
    try:
        cls = getattr(models, type_name)
    except AttributeError:
        raise Http404
    if inspect.isclass(cls) and issubclass(cls, models.Deletable):
        get_object_or_404(cls, id=object_id).delete()
    else:
        raise Http404
    redirect(dashboard)

You'll also note that it also lead to easy customization of which user can delete what: you just need to override one method and add proper logic (eg raising 403 forbidden) in your view. This can be more useful than the @staff_member_required in case your models can be associated to (owned by) a particular user:

class MyOwnedModel(Deletable, models.Model):
    owner = models.ForeignKey(django.contrib.auth.models.User, …)

    def can_delete(self, user):
        return user == self.owner or super().can_delete(user)

But of course, if only the staff can delete things, the decorator is plenty sufficient.

Lastly, it would be good to separate the "retrieve the actual model" logic from the "delete the particular instance of that model" one. The latter being the responsibility of the view, but the former would better fit as a custom URL converter.

The main advantage being that you don't need to handle the 404s for unknown models in your view, django will take care of that itself if your converter ever raises a ValueError. Going this route, you can have a converters.py:

from inspect import isclass

from django.urls.converters import StringConverter

from . import models

class DeletableConverter(StringConverter):
    def to_python(self, value):
        try:
            cls = getattr(models, value)
        except AttributeError:
            raise ValueError
        if not isclass(cls) or not issubclass(cls, models.Deletable):
            raise ValueError
        return cls

    def to_url(self, value):
        return value.__name__

Usage in your urls.py:

from django.urls import path, register_converter

from . converters import DeletableConverter

register_converter(DeletableConverter, 'deletable')

urlpatterns = [
    …,
    path('delete/<deletable:model>/<int:object_id>', views.delete),
    …,
]

And in your view:

def delete(request, model, object_id):
    instance = get_object_or_404(model, id=object_id)
    if instance.can_delete(request.user):
        # or a simple @staff_member_required decorator
        instance.delete()
    redirect(dashboard)


Percentage of questions that are unanswered or answered

Comments
Your comments are mostly clutter, and I mean that because your naming is good enough to where the comments are mostly irrelevant. Also, if you do need to make multi-line comment, you can use the same syntax in SQL as in pretty much everything else.
Look at this, the comments and the code read almost identically:

/**
 * The percentage of un-answered questions. Calculated
 * using this:
 * (Unanswered Questions / Total Site Questions) * 100
 */
SELECT
  (@UnansweredQuestions / @TotalQuestions) * 100.0 AS [Percentage Of Unanswered Questions];

There is an elegant way of assigning an alias in an expression that would make it even easier to read:
SELECT
  [Percentage Of Unanswered Questions] = (@UnansweredQuestions / @TotalQuestions) * 100.0

Does exactly the same thing, but reads more like typical code, where you name a thing before assigning it something, rather than after.

Dead code
Your first SELECT query is never displayed. There are two ways you could fix that, either by making them two different columns, or two different rows (according to your needs).
Columns:
SELECT
  [Percentage Of Unanswered Questions] = (@UnansweredQuestions / @TotalQuestions) * 100.0
, [Perentage Of Answered Questions] = 100 - ((@UnansweredQuestions / @TotalQuestions) * 100.0);

Rows:
SELECT
  [Type of value] = 'Percentage Of Unanswered Questions'
  , [Value] = (@UnansweredQuestions / @TotalQuestions) * 100.0
UNION
SELECT
  'Percentage Of Answered Questions'
  , 100 - ((@UnansweredQuestions / @TotalQuestions) * 100.0);


First Code, But I Feel It Is So Ugly, Can You Explain Why?

it is a bit hard to compare it with "standard code" if you only worked through first two chapters ;)

You should consider three principles in the following order:

The code should work
The code should be readable
The code should be extendable

Only the 1st is proofable. But maybe not that easy as one might think. Consider edge cases and errors. It takes some experience to know them. But usually something like

Boundary values - e.g. 0 for a lower boundary
Wrong format of parameter e.g. 0,5 instead of 0.5 (for english local)
Input is out of allowed boundary

There are a lot of ways to handle them, like to ask for a new value or to simply abort.

If your code is readable is matter of taste. I prefer short code blocks in methods that are named. Also repeated code should be avoided.
That said here is my first concrete suggestion for you: There are common code blocks where you ask the user for a value (System.out.print(...)) and then read the value (sc.nextDouble()). You could combine them to a method, like

private static double askForDouble(String label, Scanner scanner){
    System.out.print(label);
    return scanner.nextDouble();
}

which you can use then instead of every occurance:

System.out.print("Days: ");
double day = sc.nextDouble();

becomes

double day = askForDouble("Days: ", sc);

I would also put every calculation in separate functions although that would not give any benefit at the moment. But later you could write unit tests.

There are more possible improvements, but you should go on with the tutorials to learn about them.


Memory cache implementation with a static class inside a normal class

The MemoryCache is thread safe, all those locks and semaphore are useless.

Also, the Memory Cache by itself makes some serializations so at every update you are deserializing the whole collection of given type, add the item and re-serialize the whole collection.

If you can really use a Dictionary use it, a ConcurrentDictionary < Type,List < T >> will resolve all your problem


Code to initialize, set, or get node properties

For one, I'm wondering about strict vs sawGetSet, and why it's an if...else if structure (instead of just using one of the two variables, and an if...else). But without knowing the rest of the code, I won't get into that.

Anyway, I see no need for switch statements. I don't know if I'd call it "bad practice", but it is certainly strange practice to use a switch when it's not really called for.

I also doubt you gain any appreciable performance by splitting the code into two blocks. At least, I'd advice you to thoroughly benchmark it before duplicating code; premature optimization is the root of all evil, and all that.

As for the logic, it seems you're only interested in 'get', 'set' and 'init' values (I'll call these "the three magic values" in the following), and you call raise() for certain combinations of those. Anything else passes through.

So first, I would move the checking of kind outside the loop, since you can skip everything in your code, if kind isn't one of the three magic values.

Now, if the idea is that kind is guaranteed to always be one of the three magic values, then you can obviously skip that check. But then there's no reason to check its value; you only have to check the other.kind value. So either way, you can skip a bunch of code.

Your code is written to check for kind/otherKind-combinations that'll call raise(), but since that's most combinations, it'd be simpler to turn it inside out, and focus on the combinations that won't call raise().

As far as I can tell, the only configurations that won't call raise() (besides a key.name mismatch) are:

if kind is not any of the three magic values
if other.kind is not any of the three magic values
if

sawGetSet is true, and
kind is 'init', and
other.kind is also 'init'

Everything else will call raise().

So those 3 configurations are the only ones we need to check, and if any of them come up true, we can just skip everything else. If none come up true, call raise().

So from what I can gather, this should have the same result

var i, l,
    kindIsInit, kindIsMagic,
    other, otherIsInit, otherIsMagic;

// we'll be using this more than once
kindIsInit = (kind == 'init');

// Check for configuration #1
kindIsMagic = kindIsInit || (kind === 'get') || (kind === 'set');
if(!kindIsMagic) {
  // I imagine a `continue`, `break` or `return` could go here;
  // I've just put `return` as an example.
  return;
}

for(i = 0, l = node.properties.length; i < l; ++i) {
  other = node.properties[i];
  if(other.key.name !== prop.key.name) {
    continue;
  }

  // we might be using this more than once, too
  otherIsInit = (other.kind === 'init');

  // Check for configuration #3
  // (I'm checking this before #2 because it's probably infinitesimally
  // faster, but, really, the order of 2 & 3 really doesn't matter)
  if(sawGetSet && kindIsInit && otherIsInit) {
    continue;
  }

  // Check for configuration #2
  otherIsMagic = otherIsInit || (other.kind === 'get') || (other.kind === 'set');
  if(!otherIsMagic) {
    continue;
  }

  // If we're here, both kind and other.kind are one of the three "magic"
  // values, and any remaining combination of them should call raise()
  raise(prop.key.start, "Redefinition of property");
}

That should be both faster and simpler than what you have. "Simpler" is of course relative, and you should still copiously document all this, since it'll be tricky to read regardless.

For fun, here's a probably slower (haven't tried it), but more readable (I think) version

// helper function
function parseKind(kind) {
  var isInit = (kind == 'init');
  return {
    init: isInit,
    magic: isInit || (kind === 'get') || (kind === 'set')
  };
}

var i, l, other, kind = parseKind(prop.kind); // I'm guessing `kind` in your code is a shortcut for `prop.kind`.

// Config #1
if(!kind.magic) { return; }

for( i = 0, l = node.properties.length ; i < l ; i++ ) {
  if(node.properties[i].key.name !== prop.key.name) { continue; }

  other = parseKind(node.properties[i].kind);

  // Config #2
  if(!other.magic) { continue; }

  // Config #3
  if(sawGetSet && kind.init && other.init) { continue; }

  raise(prop.key.start, "Redefinition of property");
}


First user login function: Security and efficency opinions

Hashing

Let's start with the correct solution for hashing passwords: use bcrypt; PHP offers it with password_hash.

It's secure, and it's really easy to use (it's just a simple function call, and it manages salts etc for you).

What is wrong with your approach:

simple sha512 is way too fast; it's still better than plaintext, but it's really not the correct approach.
you don't have a per-user salt.
you don't even have a per-site salt. pass_salt doesn't serve any purpose, the check will always match as you are using it wrong and are thus still open to rainbow attacks etc (it should be something like $password = hash('SHA512', $password . $salt);, but again, site-salts are not enough).

Misc

your comment talks about encryption, but you are never encrypting, only hashing.
putting spaces around -> is unusual and leads to harder to read code.
don't die in functions, it makes it impossible for the calling code to recover. Just throw an exception.
pass the connection to the function instead of including it to make your function easier to reuse and test.

Apart from these minor issues and the very weak hashing, your code looks good to me.


Query messages and 'bold' part of a message. Show one query at a time but get the next query in advance for better user experience

note: this took me longer then I expected and there may be some syntax errors, but contains the general idea
Once your component starts having complex logic, it's a good indication to start breaking it up.
Here I propose putting your logic in some different files:

constants.js
helpers.js
hooks.js
MessageBox.js

Notably, in hooks.js I would create a few custom hooks to handle your logic.

useQueryFullMessage - handles fetching a message + a bold and returning the result
useFullMessage - uses useQueryFullMessage twice to get two full messages and handles the logic on preloading the next full message.

This is a possible abstraction (among many) you can use.
I also don't believe that useMemo is required in this situation... unless you're going to be loading many messages. React by default is already pretty optmized.
//constants.js
const API_MESSAGE_URL = 'https://myapi.com/message';
const API_BOLD_URL = 'https://myapi.com/bold';

//helpers.js
import { API_MESSAGE_URL, API_BOLD_URL } from './constants';

const getMessage = async () => {
  const res = await fetch(API_MESSAGE_URL);
  const {data} = await res.json() ?? {};
  return data?.message;
}

const getBold = async (message) => {

  const res = await fetch(API_BOLD_URL, {
    method: "POST",
    headers: { "Content-type": "application/json" },
    body: JSON.stringify({ content: message }),
  });
  const {data} = await res.json() ?? {};
  return data?.bold;
}

export const getFullMessage = async () => {
  const message = await getMessage();
  if(!message) {
    // handle error
    return {};
  }
  const bold = await getBold(message);
  if(!bold) {
    // handle error
  }
  return {
    message,
    bold
  };
}

//hooks.js
import { getFullMessage } from './helpers';

const useQueryFullMessage = () => {
  const [fullMessaage, setFullMessage] = useState();
  const [loading, setLoading] = useState(true);
  const [preloadNextValue, togglePreloadNext] = useState(0);
  useEffect(async () => {
    if(!loading) {
      setLoading(true);
    }
    const fullMessage = await getFullMessage();
    // handle if bold not set
    setFullMessage(fullMessage);
    setLoading(false);
  }, [preloadNextValue]);

  return {
    fullMessage,
    loading,
    preloadNext: () => togglePreloadNext(preloadNextValue + 1),
    setFullMessage,
  }
}

export const useFullMessage = () => {
  const {
    fullMessage: currentFullMessage,
    loading: loadingCurrentFullMessage,
    setFullMessage: setCurrentFullMessage
  } = useQueryFullMessage();
  const {
    fullMessage: nextFullMessage,
    loading: loadingNextFullMessage,
    preloadNext
  } = useQueryFullMessage();

  const requestNextMessage = () => {
    if(loadingCurrentFullMessage || loadingNextFullMessage) {
      return;
    }
    setCurrentFullMessage(nextFullMessage);
    preloadNext();
  }

  return {
    currentFullMessage,
    loadingCurrentFullMessage,
    nextFullMessage,
    loadingNextFullMessage,
    requestNextMessage
  };
}

// MessageBox.js
import { useFullMesage } from './hooks';
const MessageBox = () => {
  const {
    currentFullMessage,
    loadingCurrentFullMessage,
    nextFullMessage,
    loadingNextFullMessage,
    requestNextMessage
  } = useFullMessage();

  const { message, bold } = fullMessage;
  // TODO: check if message and bold are set.

  const formatMessageAndBold = () => {
    if (message && bold) {
      return

        {message.substring(0, bold.start)}
        {message.substring(bold.start, bold.end)}
        {message.substring(bold.end)}

;
    } else if (message && !bold) {
      return {message};
    }
  };

  return (

      {loadingCurrentFullMessage ? "Loading..." : formatMessageAndBold()}
      <button isLoading={loadingNextFullMessage} onClick={requestNextMessage}>
        {!loadingNextFullMessage ? "Next Message" : "Loading..."}
      </button>

  );
}
```


Counting votes for candidates in a category and region

can get this done much more efficiently.

Yes, I agree.

If C candidates each receive an average of V votes (total of C * V votes cast), then your complexity is quadratic in number of candidates: O(C * C * V).

There's nothing so bad about making a pair of linear passes, to accumulate candidates and then votes.

But there's no need, you can make a single pass to do both. Create a HashMap, iterate over all votes, probe the map to see if you should add a zero entry for a new candidate, and then increment the entry so you'll have vote totals at the end.


Displaying an overlay when hovering over photos

Instead of

 $(this).parent().children(".search").show();

you can use

$(this).siblings(".search").show();


Scale object based on distance between 2 vertices

I’ll start with some general comments on Python style:

Line should be no more than 79 characters long. (PEP 8: Maximum Line Length)
When you’re specifying a list of keyword arguments to a function, there shouldn’t be a space around the equals sign. (PEP 8: Other Recommendations)

So for example, line 9 becomes:

vtxCoordList = mc.xform(selPoints, q=True, translation=True, ws=True)

When you have lots of keyword arguments, you can put them on newlines (aligned with the opening parens) to make them easier to read. For example, line 63 becomes:

currentLength = mc.textFieldButtonGrp("currentLength",
                                      ed=False,
                                      tx="{0}".format(d),
                                      buttonLabel="Refresh",
                                      bc=getDist)

Python variable naming convention for variables and functions is lowercase_with_underscores rather than dromedaryCase.
Functions are documented with docstrings, which are triple-quoted strings that are the first item within the function body. So in getDist(), you want to move the d= to after your docstring, and you should move the comment above scaleDist() to within the function as a docstring.
I don’t understand any of the calls to maya.cmds, because I’m familiar with neither Maya nor this library. If somebody who knows this library could easily follow these calls, and why you’re making them, then this is probably fine. If not, some extra comments might not go amiss.
I would recommend using slightly longer variable names, particularly for d in defineParameters() and b in scaleDist(). Characters are cheap.

And a few more specific comments:

defineParameters():

I think the name of this function is unclear. It actually returns a distance between two points in 3D space, not parameters. I think it might be better to return the two tuples A, B, and move the distance calculation elsewhere.
Rather than using (…)**0.5, you can use the sqrt() function from the math module. I believe it’s equivalent to what you’ve written, but it makes the float() unnecessary and your intent clearer:

import math

d = math.sqrt( (Ax - Bx)**2 + (Ay - By)**2 + (Az - Cz)**2 )

If you want to be really fancy, you can use numpy.linalg.norm:

import numpy

A = vtxCoordList[:-3]
B = vtxCoordList[3:]
d = numpy.linalg.norm(A - B)

but if you don’t already have numpy installed, then setting it up for this small task is probably overkill.

getDist():

This is the function where you should have your code for computing the distance.

refreshScaleFactor():

I would get rid of the userInput variable, and just use the sf variable directly.
You don’t need the float() around the return value; you can just return scaleFactor directly. As the quotient of two float values, this is automatically a float.

scaleDist():

I think this function is going to throw a NameError when you try to get the value of objName. This variable was only ever defined in the local scope of defineParameters(), but it disappears as soon as that function was done.

I see two possibilities:

Either set up objName as a global variable in defineParameters() (but you should try to avoid global variables where possible); or
Have defineParameters() return a dictionary of parameters: objName, A and B, and then access values as appropriate.

In the mc.scale(float(b), …) line, the float()s around b are unnecessary: again, it’s the quotient of two floats.
I don’t know Maya, so I don’t know what the variables in the two freeze transformation lines mean (t, r, s, …). If it’s obvious to somebody who knows Maya and/or the maya.cmds module, then perhaps you don’t need to explain it; but if not, perhaps a comment would be useful.

Finally, there’s some code that isn’t part of any function at the bottom of the script:

Rather than having this code in global scope, put it in a main() function and then have this at the end of the script:

if __name__ == '__main__':
    main()

This means you can run the file as a script, but you can also import it in another script without it kicking off the main code.


Find nearest k points from the central point

Don't sqrt the distance.

It is a common mistake when filtering distances to use the complete distance calculation.

Given 2 values a and b, if a < b then it is also true that sqrt(a) < sqrt(b). Hence you don't need the expensive sqrt calculation to know the if a point is closer than another.

To find the closest the following does not use the sqrt of the distance.

function closestPoint(points, point, dist){
    var x, y, found, min = dist * dist; // sqr distance
    for(const p of points) {
        x = p[0] - point[0];
        y = p[1] - point[1];
        x *= x;
        y *= y;
        if(x + y < min){
            min = x + y;
            if (min === 0) { return p } // early exit
            found = p;
        }
    }
    return found;

}

Not in the sort!!!

You are doing the distance calculation in the sort DON'T!!!, that means you repeat the same calculations over and over.

To improve you throughput the following will reduce the over all time. The improvement is linear and does not change the complexity.

Note that in JS a ** 2 is slightly slower than a * a

A more efficient version of your solution

function findNearestPoints({list, center, k}) {
    const res = [];
    const cx = center[0], cy = center[1]; // alias and reduce indexing overhead
    const distSqr = (x, y) => (x -= cx) * x + (y -= cy) * y;
    const sort = (a, b) => a[1] - b[1];

    for (const p of list) { res.push([p, distSqr(p[0], p[1])]) }
    res.sort(sort).length = k;
    return res.map(p => p[0]);
}

The ** operator for roots

Note that JS has the ** operator. That you can use it to get roots by making the right side the inverse, 1 over the power. Thus the sqrt is **(1/2) the cube root is **(1/3)

eg

if 2 ** 2 === 4 then 4 ** (1/2) === 2
if 2 ** 3 === 8 then 8 ** (1/3) === 2  Don't approximate 8 ** 0.33 !== 2
if 2 ** 4 === 16 then 16 ** (1/4) === 2

Better sort

The sort is the bottle neck in this problem.

You can use a binary tree sort as it is the least complex for real numbers (every coder should learn how to implement a binary tree sort)

Do you need the sort?

However I think (think means might be, I am going by instinct) that there is a faster solution that does not involve a sort and that is at most \$O(n)\$

Remember that the order of the points is not important, that you need only separate the points in two. It may take a few passes to do, but as long as the number of passes is not related to the number of points or 'k' you will have a \$O(n)\$ solution.

I am not going to give you the solution this time (if there is one) as there is no problem solving experienced gained coping code.


Proper way to work with stored procedures in Entity Framework Core

The biggest thing I would change is to return the connection to the state you found it.

bool isOpen = cmd.Connection.State == ConnectionState.Open;
if (!isOpen)
{
    cmd.Connection.Open();
}

await cmd.ExecuteNonQueryAsync();

if (!isOpen)
{
    cmd.Connection.Close();
}

Then, from there, I would create a helper method to build the SqlParameter objets for you:

private SqlParameter BuildParamter(string name, SqlDbType type, object value, ParameterDirection? direction)
{
    var parameter = new SqlParameter(name, type);

    if (value != null)
    {
        parameter.Value = value;
    }

    if (direction.HasValue)
    {
        parameter.Direction = direction.Value;
    }

    return parameter;
}

Then your parameters go from:

cmd.Parameters.Add(new SqlParameter("@phoneNumber", SqlDbType.NVarChar) { Value = phoneNumber });
cmd.Parameters.Add(new SqlParameter("@dateOfBirth", SqlDbType.Date) { Value = dateOfBirth });

cmd.Parameters.Add(new SqlParameter("@registered", SqlDbType.Bit) { Direction = ParameterDirection.Output });

To:

cmd.Parameters.Add(BuildParameter("@phoneNumber", SqlDbType.NVarChar, phoneNumber));
cmd.Parameters.Add(BuildParameter("@dateOfBirth", SqlDbType.Date, dateOfBirth));

cmd.Parameters.Add(BuildParameter("@registered", SqlDbType.Bit, null, ParameterDirection.Output));

It's less verbose, but if you build a lot of SqlParameter objects it might be handy to have one method you can use for all of them. (You can optionally add a int? size parameter to the method as well.)

Then, extract a SetStoredProcedure method which would take the input SqlCommand and string, set the type and command text to "dbo." + name, then you add the parameters, then ExecuteStoredProcedure would do the connection checking and then you can return your cmd.Parameters["@registered"].Value as you are. In the end something like:

SetStoredProcedure("CheckIfUserRegistered", cmd):

cmd.Parameters.Add(BuildParameter("@phoneNumber", SqlDbType.NVarChar, phoneNumber));
cmd.Parameters.Add(BuildParameter("@dateOfBirth", SqlDbType.Date, dateOfBirth));

cmd.Parameters.Add(BuildParameter("@registered", SqlDbType.Bit, null, ParameterDirection.Output));

ExecuteStoredProcedure(cmd);

return (bool)cmd.Parameters["@registered"].Value;

Optionally with your async/await pattern.

This way, if you create more stored procedures it's less work to make them operate.


Know the limits of an image after rotation

xmaxOrigine

So this looks like you are mixing a French word with English.  Be careful of that.  A native English reader will be mildly confused by this, as it looks similar to original which would make sense in that context.  But the real problem is with someone for whom origine does not look like a word.  For example, take native Mandarin speakers.  Presumably they know how to look up English words that they don't understand in the English code.  They won't however know that this is not an English word.  So they won't find it in an English directory and won't know that they should look in a French dictionary.

Perhaps your context will have you overwhelmingly sharing this code with people who speak enough French to know what you mean.  But if you do need to share with someone who doesn't speak French, that person may be confused by things like this.

    xmin_f = xmin_f < p1X ? xmin_f : p1X;
    xmax_f = xmax_f < p1X ? p1X : xmax_f;
    ymin_f = ymin_f < p1Y ? ymin_f : p1Y;
    ymax_f = ymax_f < p1Y ? p1Y : ymax_f;

This would be easier to read if you used the natural language constructs for this.

    xmin_f = Math.min(xmin_f, p1X);
    xmax_f = Math.max(p1X, xmax_f);
    ymin_f = Math.min(ymin_f, p1Y);
    ymax_f = Math.max(p1Y, ymax_f);

You also do this repeatedly.  If these are object fields, you can make a method to do this for you.

private void expandBoundaries(int x, int y) {
    xmin_f = Math.min(xmin_f, x);
    xmax_f = Math.min(xmax_f, x);
    ymin_f = Math.min(ymin_f, y);
    ymax_f = Math.min(ymax_f, y);
}

If they are not object fields, you can make objects to track them.  Then you'd use them like

    xRange.include(p1X);
    yRange.include(p1Y);

and at the end

    widthFinal = xRange.getMax() - xRange.getMin();
    heightFinal = yRange.getMax() - yRange.getMin();

or even

    widthFinal = xRange.getDifference();
    heightFinal = yRange.getDifference();

with include defined as

public void include(T value) {
    min = Math.min(min, value);
    max = Math.max(max, value);
}

You can also save some multiplications by storing the values for later use:

    float rotatedX2X = xmaxOrigine * cos;
    float rotatedY2X = ymaxOrigine * sin;
    float rotatedX2Y = xmaxOrigine * sin;
    float rotatedY2Y = ymaxOrigine * cos;

Then you could rewrite this code as

    BufferedImage myImage = ImageIO.read( new File( "D:\\Users...jpg" ) );
    xmaxOrigine = myImage.getWidth() - 1;
    ymaxOrigine = myImage.getHeight() - 1;

    angle = 12;
    angleRadian = Math.toRadians( angle );
    cos = Math.cos( angleRadian );
    sin = Math.sin( angleRadian );

    float rotatedX2X = xmaxOrigine * cos;
    float rotatedY2X = ymaxOrigine * sin;
    float rotatedX2Y = xmaxOrigine * sin;
    float rotatedY2Y = ymaxOrigine * cos;

    xRange.include((int) (rotatedX2X - rotatedY2X));
    yRange.include((int) (rotatedX2Y + rotatedY2Y));
    xRange.include((int)-rotatedY2X);
    yRange.include((int)rotatedY2Y);
    xRange.include((int)rotatedX2X);
    yRange.include((int)rotatedX2Y);
    xRange.include(0);
    yRange.include(0);

    widthFinal = xRange.getDifference();
    heightFinal = yRange.getDifference();

Note that this gets rid of p1X, p1Y, etc.  They weren't used in the original code snippet.  It's possible that they were used elsewhere.  If so, you'd have to put them back.

Then your Range class:

public class Range<T extends Number> {
    private T max;
    private T min;

    public Range(T min, T max) {
        this.min = min;
        this.max = max;
    }

    public void include(T value) {
        min = Math.min(min, value);
        max = Math.max(max, value);
    }

    public T getMin() {
        return min;
    }

    public T getMax() {
        return max;
    }

    public T getDifference() {
        return max - min;
    }
}

Note that you have to initialize the Range before using it.  You don't show the initialization in the original code snippet, so I didn't show it here.  It would look something like

    Range xRange = new Range(small, large);


As @Zeta said, only your examiner can tell you why he wasn't satisfied.
But here are a couple of suggestions anyway:

Variable names are important and myArray doesn't mean much. You can try inputArray for example.
Changing the index of a for loop is usually not a good idea, because it makes the code a bit more difficult to understand (not by a lot, but why make it harder?).

This is another go at the same algorithm, which I think is more readable:

function bubbleSort(inputArray)
{
  var index;
  var done = false;
  var temp;

  while ( !done )
  {
    done = true;
    for(var index = 0; index < inputArray.length; index++)
    {
      if ( inputArray[index] > inputArray[index+1] )
      {
        temp = inputArray[ index ];
        inputArray[ index ] = inputArray[ index+1 ];
        inputArray[ index+1 ] = temp;
        done = false;
      }
    }
  }

  return inputArray;
}


Better to follow a common stack API

The common API for a stack:

push(item): add an item on the top of the stack and then return the item
pop(): remove the top item from the stack and return it

My objection is against what your methods return.
push returns a message, pop returns an (item, message) tuple.
If you think about it, the message is useless.
Users of this class would have to check the output of each call,
and evaluate success or failure using string comparison.
This is very weak.

Instead of using the return value to indicate success and failure,
it would be better to follow the common API,
and raise exceptions in case of failures.
For example like this:

class EmptyStackError(Exception):
    def __init__(self):
        super().__init__("Stack is empty: cannot pop an empty stack")

class StackFullError(Exception):
    def __init__(self):
        super().__init__("Stack is full")

class stack():
    # ...

    def push(self, data):
        if self.isFull():
            raise StackFullError()
        self.data.append(data)
        return data

    def pop(self):
        if self.isEmpty():
            raise EmptyStackError()
        item = self.data[len(self.data) -1]
        del self.data[len(self.data) -1]
        return item

Python conventions

Follow PEP8, the official coding style guide of Python. For example:

The convention for class names is PascalCase, so stack should be Stack
The convention for method names is snake_case, so isFull should be is_full


Yes. Try to automate converting a URL to a name, instead of hardcoding the mapping. With only two URLs, your approach is doable, but as soon as you have to handle lots of different URLs, it will quickly become very painful.
Also, avoid first copying a column and then replacing every item in it. Rather, construct the column with the right contents directly. Here is an example:
df['Name'] = [url.split('.')[-2].upper() for url in df['URL']]

This will fail for proper URLs like https://www.pandas.org/index.html. If you want to handle that automatically, you'll have to properly parse them, for example using urllib.parse.


How can I enhance my jigsaw puzzle solver function?

First - some minor comments regarding your code:

you are saying that all pieces of equal size, then it doesn't make sense to do rows,cols=candidate.dim() in a loop
I never worked with Matrix class, but I assume that [0:rows,0:1] is the same as [:-1, :1], so you don't have to carry rows and cols everywhere
instead of "./im"+str(i+1)+".bitmap" - you can do "./im{0}.bitmap".format(i + 1). IMO it is more readable
add more spaces to the code to make it more readable, at least around all operators. For example: n = n1+n2+sep => n = n1 + n2 + sep
instead of checking is this line throws an exception Matrix.load("./im1.bitmap"), you can just check if file exists with os.path.isfile
please don't do from images import * from modules, because now I don't know what came from images. Please consider from images import Matrix or something else.

Second, I feel like it would be possible to solve this problem with object graph rather than with indexes and temporary lists. E.g wrap a bitmap piece into an object an have it reference it's neighbours (left, right, top, bottom), once you have a complete graph - just draw it.

This is my version of the code. Please don't consider it to be a solution(I may swapped cols/rows accidentally etc), this is just an overall idea. I didn't even run this code , but I believe it is possible to use something like this.

Also this piece of code assumes that puzzle is ideal - so there is always exactly one solution and all pieces should be used.

import os.path
import itertools

# helpers to construct file names
def bitmap_file_name(index):
    return "./im{0}.bitmap".format(i + 1)

def puzzle_file_name(index):
    return "./puzzle/im{0}.bmp".format(i + 1)

# helpers to cut a piece of bitmap
def left_stripe(bitmap):
    return bitmap[:1, 0:-1]

def right_stripe(bitmap):
    return bitmap[-1:, 0:-1]

def bottom_stripe(bitmap):
    return bitmap[:-1, -1:]

def top_stripe(bitmap):
    return bitmap[:-1, :1]

class Piece(object):
    """
    Wrapper around bitmap piece, has references to it's neighbours
    """
    def __init__(self, bitmap):
        self.left = None
        self.right = None
        self.top = None
        self.bottom = None
        self.bitmap = bitmap

def reconstruct_image(m):
   images_range = range(m**2)

   # check if we already converted bmps to bitmaps
   if not os.path.isfile(bitmap_file_name(0)):
        for i in images_range:
            image2bitmap(puzzle_file_name(i))

    bitmaps_gen = (Matrix.load(bitmap_name(i)) for i in images_range)
    # list of `Piece` elements, all neighbours are `Nones`
    pieces = [Piece(x) for x in bitmaps_gen]

    # try all pairs of these pieces (it will twice over each pair A, B and B, A)
    for piece1, piece2 in itertools.permutations(pieces, 2):
        # compare edges of elements, but only if these edges are not taken
        if not piece1.left and not piece2.right and left_stripe(piece1.bitmap) == right_stripe(piece2.bitmap):
            piece1.left = piece2
            piece2.right = piece1
        elif not piece1.top and not piece2.bottom and top_stripe(piece1.bitmap) == bottom_stripe(piece2.bitmap):
            piece1.top = piece2
            piece2.bottom = piece1

    # assuming that our puzzle is always solvable
    # so now we have full graph, and there is one element that doesn't have top and left neighbours
    top_left = next(p for p in pieces if not p.left and not p.top)

    piece_width, piece_height = top_left.dim()

    # init result matrix
    result_matrix = Matrix(piece_width * m, piece_height * m)

    first_line_elem = top_left
    current_elem = first_line_elem
    # let's fill new matrix line by line, we could choose BFS or something else. but line by line seem to be more logical
    for row in xrange(m):
        for column in xrange(m):
            left_x = column * piece_width
            left_y = row * piece_height
            result_matrix[left_x : left_y, left_x + piece_width : left_y + piece_height] = current_elem.bitmap

            # choose next piece
            if current_elem.right:
                current_elem = current_elem.right
            elif first_line_elem.bottom:
                current_elem = first_line_elem.bottom
                first_line_elem = current_elem

    return result_matrix