If you want to write tests for this helper class only - they would be integration tests since they touch the file system.

In order to make the code unit testable you need to make it independent from hardware and physical interaction with network or disk.

If you want to unit test the business logic that uses this FileHelper, then you should introduce Inversion of Control to separate business logic from file activities. You'll have to create an interface that describes all operations you can do with files, transform this static helper class into class implementing that interface, and reference file operations from business logic via interface only. Example of file helper:

public interface IFileOperations
{
    void ExtractZipFile(Stream zipStream, string location);
    void CreatePageFolderIfNotExist(string directory);
}

public class FileOperations : IFileOperations
{
    public void ExtractZipFile(Stream zipStream, string location)
    {
        ..................................
    }

    public void CreatePageFolderIfNotExist(string directory)
    {
        .................................................
    }
}

Then, in order to properly cover you code with tests, you would need to write unit tests for business logic and add integration tests for the implementation of FileOperations.


Running a master query and a query of queries

You could use a UNION to run one master query

<cfquery datasource = "XX.XX.X.XX" name="master1">
SELECT DATE(Timedetail) as FIRSTCONN, COUNT(Timedetail) as FIRSTOccurances, EVENTS
FROM  MyDatabase
WHERE EVENTS = "FIRST"
GROUP BY FIRSTCONN
UNION
SELECT DATE(Timedetail) as SECONDCONN, COUNT(Timedetail) as SECONDOccurances, EVENTS
FROM  MyDatabase
WHERE EVENTS = "SECOND"
GROUP BY SECONDCONN;
</cfquery>

and then in your QoQ reference the correct column name

<cfquery dbtype="query" name="detail1">
SELECT  *
FROM master1
WHERE FIRSTCONN  >= <cfqueryparam value="#form.startdate#" cfsqltype="cf_sql_varchar">
AND FIRSTCONN  <  <cfqueryparam value="#dateAdd('d', 1,form.enddate)#"     cfsqltype="cf_sql_varchar">
AND EVENTS = 'FIRST';

<cfquery dbtype="query" name="detail2">
SELECT  *
FROM   master1
WHERE  SECONDCONN  >= <cfqueryparam value="#form.startdate#"     cfsqltype="cf_sql_varchar">
AND    SECONDCONN  <  <cfqueryparam value="#dateAdd('d', 1,form.enddate)#" cfsqltype="cf_sql_varchar">
AND EVENTS = 'SECOND';
</cfquery>


Printing the characters at the even and odd indexes sounds like two similar tasks. So the code for these tasks should look very similar. You can either extract that code to a separate method, or, since it is very simple, just write the code twice.

public static void printEvenOddIndexes(String[] strings) {
    for (String word : strings) {

        for (int i = 0; i < word.length(); i += 2) {
            System.out.print(word.charAt(i));
        }

        System.out.print(" ");

        for (int i = 1; i < word.length(); i += 2) {
            System.out.print(word.charAt(i));
        }

        System.out.println();
    }
 }

The two loops only differ by the starting index. Note the += 2 at the end of the for loop.


Converting fixed-width text file to CSV in C

Consider const char *

const char *source allows the function to be used with const strings, better conveys code's functionality and more readily allows for optimizations.

// int trimcpy(char *destination, char *source, size_t len) {
int trimcpy(char *destination, const char *source, size_t len) {

Undefined behavior

trimcpy() begins by examining later elements of source[] even though they are not known to have been assigned.  The string may not be as long as len.

int trimcpy_alt(char *destination, char *source, size_t len) {
   // Suggest memchr() here rather than strlen() to not look too far.
   char *null_character_pos = memchr(source, '\0', len);
   if (null_character_pos) len = null_character_pos - source;
   ...

Undefined behavior 2

In a selective case of an empty file, the first call to fgets() returns NULL and then the following fputs(out, wfp); is UB as out contents are not initialized.  Add initialization or assignment.

char out[BUFFER_SIZE];
out[0] = '\0'; // add

Not trimming end spaces before \n

trimcpy() does not trim spaces just before '\n'.  I suspect this in not in line with OP's goals.

Avoid redundant information

Redundant information takes more work to maintain.   Consider dropping the 3

// #define COLS 3
size_t RANGES[][2] = {{0, 6}, {6, 20}, {29, 3}};
#define COLS (sizeof RANGES/sizeof RANGES[0])

Minor things:

Mixing types

Little reason to mix size_t and int types here for array indexing and sizing.  Recommend to  use just one: size_t (my preference) or 2) int, but not  both.

// From
int trimcpy(char *destination, char *source, size_t len) {
  ...
  int i = 0;
  while (i<len && *source != '\0') {

// To
size_t trimcpy(char *destination, char *source, size_t len) {
  ...
  size_t i = 0;
  while (i<len && *source != '\0') {

main()

  // int p = 0;
  size_t p = 0;

Subtraction with unsigned types

If above size_t employed, consider the 2 below:  Which works well should a later version of code surprisingly  define  #define BUFFER_SIZE 19?

if (p > BUFFER_SIZE - 20) {
if (p + 20 > BUFFER_SIZE) {

   The first is the same as if (p > SIZE_MAX) { or if (0) {


You should call rlist() consistently, and write

elif k == 1:
    return rlist(curr, empty_rlist)

… for reasons that will become apparent.  Also be sure to use four spaces per level of indentation, as prescribed by PEP 8.

Are your tuple, range, and string the same as each other?  No, comparing them using == will obviously return False.  What they all have in common, though, is that they are all iterables.  Being iterable means that you can use them in for e in iterable expressions — either in a loop or a generator.

That means that if you want to be able to write things like print([e for e in fib_sequence(5)]), you'll need to make your rlist type iterable.  Here's one way you could accomplish that.

class rlist(tuple):
    def __new__(cls, first, rest):
        return super(rlist, cls).__new__(cls, (first, rest))

    def __iter__(self):
        seq = self
        while seq is not None:
            yield first(seq)
            seq = rest(seq)

This works as long as you have applied the rlist() fix to fib_sequence() as mentioned above.


Write an anonymous function validating email address

As I already noted in your other question, trying to validate email addresses correctly is an almost impossible task; there are a lot more characters allowed that you are assuming. Check out this correct regex to validate addresses, which is quite unpractical.

This means that we can either be too strict or too lenient with our regex. For front-end validation, being too strict is not the right choice as people with valid email addresses will not be able to use your service.

Personally, I would check if there is an @ in the string, and be done with it. It will catch common typos, there isn't much more you can do.

Later on, you could write two functions: requiredEmailValidation and optionalEmailValidation. The first just looks for an @, and doesn't allow a form to be submitted, the second checks for common typos (eg .con instead of .com, gmai.com instead of gmail.com, etc) and shows a warning.

Misc

js variable names generally can't contain -. I'm surprised it's even working for you, it didn't for me with firefox or chrome.
regpat isn't that great of a variable name; it's hard to read (regexPattern would be better), and contains few information (I can already see that it's a regex pattern). Something like emailPattern would be better (for such a short function, it's not that important, but if you write larger functions later on, naming becomes very important).


Searching string for character not in array

First we'll clean this up a bit, then we'll look at performance.
There is absolutely zero reason to be using an anonymous function. This is useful functionality that you will eventually want to call from somewhere else. As such, it deserves to be extracted into a proper method of it's own.
Private Function IsValidString() As Integer
    'Dim Input As String = "Hello World" 'This is Invalid
    'Dim Input As String = "13.4i+4" 'This is Invalid
    Dim Input As String = "13.4i" 'This is valid
    If IsValidString(Input) Then
        Return -1
    Else
        'Do some other stuff
        Return 1 '
    End If
End Function

Function IsValidString(Input As String) As Boolean
    Dim IsValid As Boolean = True
    For Each Character In Input
        If Not {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "i"}.Contains(Character) Then
            IsValid = False
        End If
    Next

    Return IsValid
End Function

Next, let's forget entirely about the other IsValidString() method for a second and focus on the code we want to focus on. Watch your casing. It's terribly confusing to make local variables PascalCased just like your classes & methods. Local variables should be camelCased.
Public Sub Main()
    Console.WriteLine(IsValidString("Hello World"))
    Console.WriteLine(IsValidString("13.4i+4"))
    Console.WriteLine(IsValidString("13.4i"))
End Sub

Function IsValidString(input As String) As Boolean
    Dim isValid As Boolean = True
    For Each character In input
        If Not {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "i"}.Contains(character) Then
            isValid = False
        End If
    Next

    Return isValid
End Function

We could go one step farther and Linq-ifiy it a bit into some very readable code.
Function IsValidString(input As String) As Boolean

    Dim validChars = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "i"}

    Return input.All(Function(c) validChars.Contains(c))

End Function

But does it perform? Well, actually, yes it does. I wrote some benchmarking code and it turns out that the Linq version out performs yours by quite a bit. I was kind of surprised by this, but here are the results.

Sample Size: 100
Original; Mostly Invalid: 10ms
Linq; MostlyInvalid: 0ms
Original; Mostly Valid: 0ms
Linq; Mostly Valid: 0ms

Sample Size: 1000
Original; Mostly Invalid: 2ms
Linq; MostlyInvalid: 1ms
Original; Mostly Valid: 2ms
Linq; Mostly Valid: 1ms

Sample Size: 10000
Original; Mostly Invalid: 25ms
Linq; MostlyInvalid: 4ms
Original; Mostly Valid: 25ms
Linq; Mostly Valid: 23ms

Sample Size: 100000
Original; Mostly Invalid: 235ms
Linq; MostlyInvalid: 41ms
Original; Mostly Valid: 231ms
Linq; Mostly Valid: 255ms

Sample Size: 1000000
Original; Mostly Invalid: 2408ms
Linq; MostlyInvalid: 587ms
Original; Mostly Valid: 2347ms
Linq; Mostly Valid: 2083ms

Press any key to continue . . .

As you can see, the Linq version nearly always outperforms your method on mostly invalid input. However, on mostly valid input, it performs roughly the same; it's sometimes better, sometimes worse. I suspect this is because the Linq version bails out of the check earlier on invalid input.
Here's the final version of the benchmarking code. It exceed's .NetFiddle's memory limits, so you'll need to paste it into a C# console program to see the results of the higher sample sizes.
If you're either uncomfortable with Linq, or really looking to just push the performance to the absolute best it can be, then we can just modify your original algorithm to return early when we know that the answer is false.
Function IsValidString(input As String) As Boolean
    For Each character In input
        If Not {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "i"}.Contains(character) Then
            Return False
        End If
    Next

    Return True
End Function

This outperforms the both version above in every case, mostly valid or mostly invalid and it does it consistently each time I run the updated benchmarks.

Sample Size: 1000
Original; Mostly Invalid: 2ms
Linq; MostlyInvalid: 0ms
Improved; Mostly Invalid: 0ms
Original; Mostly Valid: 2ms
Linq; Mostly Valid: 2ms
Improved; Mostly Valid: 1ms

Sample Size: 10000
Original; Mostly Invalid: 25ms
Linq; MostlyInvalid: 4ms
Improved; Mostly Invalid: 3ms
Original; Mostly Valid: 22ms
Linq; Mostly Valid: 20ms
Improved; Mostly Valid: 17ms

Sample Size: 100000
Original; Mostly Invalid: 242ms
Linq; MostlyInvalid: 43ms
Improved; Mostly Invalid: 33ms
Original; Mostly Valid: 235ms
Linq; Mostly Valid: 238ms
Improved; Mostly Valid: 186ms

Sample Size: 1000000
Original; Mostly Invalid: 2479ms
Linq; MostlyInvalid: 609ms
Improved; Mostly Invalid: 336ms
Original; Mostly Valid: 2358ms
Linq; Mostly Valid: 2059ms
Improved; Mostly Valid: 1704ms

BUT........
Correctness
Is 0323.233.12.i a valid string? Both your and my method says it is. Your regex also suffers from the same problem.


This can be significantly cleaned up and simplified using Java 8. Let's start with a quick review, though before rewriting it all :)

public static void main(String[] args) {
    try (Scanner input = new Scanner(new File(args[0]))) {

You perform no validation whatsoever here. When this is called without an argument, you'll get a ArrayIndexOutOfBoundsException... not nice. Validate your inputs (even when the assignment says you'll get a path)

Also you should consider using JSR-203 (aka. java.nio) API. It's cleaner and more informative wrt. Exceptions and general handling of problematic inputs.
Also it integrates very nicely with Streams :D

But you're using try-with-resources, which is a good start.

        while(input.hasNextLine()) {
            System.out.println(sanitize(input.nextLine()));
        }

This is a small indication your main-method is doing too much. You do:

Open file
read that file
call sanitize
print
error handling

Following the Single Responsibility Principle by the letter would mean every single one of these should be a separate method. I personally find that overkill, but I'd at least shift the responsibilities a little by separating result retrieval (aka. sanitize()) from printing.

Which gets me to sanitization or rather how you do it:

    for (String s : input.split("[^a-zA-Z]+")) {

What you're doing here is interesting and basically a cool trick, but.. you're cheating around what you actually want.

You want to extract words consisting of [a-z] (case insensitive). What you do is split you String on everything else and then reassemble it.

So there's a few things you could've done instead. First possibility would've been to extract the words with a Pattern and then assembling them, which might've been more obvious:

Pattern words = Pattern.compile("([a-z]+)", Pattern.CASE_INSENSITIVE);
Matcher m = words.matcher(s);
StringBuilder sb = new StringBuilder();
while (m.find()) {
   sb.append(m.group()).append(' ');
}

This basically accomplishes the same as your code, but is more explicit as to what you want to match. But this is a lot of code for something dead simple. It boils down to what your split does in combination with the loop.

What you do is replace everything, that's not a latin letter with a space. Why not write that?

s.replaceAll("[^a-zA-Z]+", " ");

this eliminates the for-loop you have and .. basically does the same :D

Now that we got this out of the way, let's look at how it looks with JSR203 and Streams :)

public static void main(String[] args) {
    try (Stream<String> lines = Files.lines(Paths.get(args[0]))) {
        final String output = lines.map(CleanWords::sanitize)
             .collect(Collectors.joining(System.lineSeparator()));
        System.out.println(output);
    } catch (IOException ex) {
        System.out.println("Could not read File");
    }
}

private static String sanitize(String input) {
     return input.replaceAll("[^A-Za-z]+", " ").toLowerCase().trim();
}


Thanks to an answer to a similar question on StackOverflow (thanks @200_success), I improved the implementation of operator(). Using _memory.count is pretty inefficient compared to _memory.find since the latter will stop once the first corresponding key is found:

auto operator()(Args... args)
    -> Ret
{
    const auto t_args = std::make_tuple(args...);
    auto it = _memory.find(t_args);
    if (it == _memory.cend())
    {
        using val_t = typename std::unordered_map<std::tuple<Args...>, Ret>::value_type;
        it = _memory.insert(val_t(t_args, _func(args...))).first;
    }
    return it->second;
}

While the solution above is indeed better than what I had, I managed to improve it even more: the results of _func should be directly constructed into _memory thanks to the piecewise construction of std::pair:

template<typename Ret, typename... Args>
auto MemoizedFunction<Ret, Args...>::operator()(Args... args)
    -> Ret
{
    const auto t_args = std::make_tuple(args...);
    auto it = _memory.find(t_args);
    if (it == _memory.cend())
    {
        it = _memory.emplace(std::piecewise_construct,
                             std::forward_as_tuple(t_args),
                             std::forward_as_tuple(_func(args...))
                        ).first;
    }
    return it->second;
}

Now, operator() is far better than it originally was. I don't know whether it is still possible to improve it or not though.


POST variable analysis contains JSON format string PHP

I think you're are definitely on the right track here. I spent a good deal of time trying to refactor, here's what I came up with

#Validate Function for Json
function jsonDecodeAndValidate($var, $assoc = false) {
    if(!is_string($var))
        return false;
    if(!$decoded = json_decode($var, $assoc))
        return false;
    if(!is_object($decoded) && !is_array($decoded))
        return false;
    return $decoded;
}
#Parse Function
function buildVirtualData($data) {
    if (is_array($data) || is_object($data)) {
        foreach ($data as $key1 => $val1) {

            if(is_array($val1)){
                foreach ($val1 as $key2 => $val2) {
                    $result[$key1][$key2] = buildVirtualData($val2);
                }
            }
            else if($decoded = jsonDecodeAndValidate($val1)){
                $result[$key1] = buildVirtualData($decoded);
            } else {
                if(in_array($val1, ['true', 'false']))
                    $val1 = filter_var($val1, FILTER_VALIDATE_BOOLEAN);
                $result[$key1] = $val1;
            }
        }
        return $result;
    } else {
        if ($decoded = jsonDecodeAndValidate($data, true)) {
            return buildVirtualData($decoded);
        } else {
            return $data;
        }
    }
}

At the very least this will save you some calls to json_decode as the decoding is done once per iteration.

EDIT: I took another stab at it. I think you can boil it down to this.

#decodeand validate
function jsonDecodeAndValidate($var) {
    if(!is_string($var))
        return $var;
    if(!$decoded = json_decode($var, true))
        return $var;
    if(!is_array($decoded))
        return $var;
    return $decoded;
}
#Parse Function
function buildVirtualData($data, &$build) {
    $data = jsonDecodeAndValidate($data);
    if(is_array($data) || is_object($data)){
        foreach($data as $key => $value){
            buildVirtualData($value, $build[$key]);
        }
    } else {
        if ($data === 'true')
          $data = true;
        if ($data === 'false')
          $data = false;
        $build = $data;
    }
}
# call to Function:
$build = [];
buildVirtualData($_POST, $build);
echo '<pre>';
echo json_encode($build, JSON_PRETTY_PRINT);
echo '</pre>';

You just have to declare your array outside of the function.


Datagrid not refreshing correctly with Async Ping VB .Net

I have a similar problem (but I have to use PSLoggedOn.Exe which times out in 10-15 seconds).

To mitigate the problem I use WMI to Ping.

I will then do PSLoggedOn only if the result was a valid IPnumber.

WmiPingStatus is perhaps a little less reliable because it is faster.
But if You don't get an answer you will get an answer the next loop.

    Friend Function WmiPingStatus(computer As String) As String
    Dim searcher As New ManagementObjectSearcher("SELECT ProtocolAddress FROM Win32_Pingstatus WHERE Address = '" & computer & "'")
    For Each wmiObj As ManagementObject In searcher.Get()
        For Each prop As PropertyData In wmiObj.Properties
            If prop.Name.Equals("ProtocolAddress", StringComparison.InvariantCultureIgnoreCase) Then Return wmiObj(prop.Name.ToString).ToString
        Next
    Next
    Return ""
End Function

Your function PingHost is not async but You can do it async if You use :

Await preply = SendAsync(host, Object)

But that is only part of the problem becasue You still have to wait for the answer.
Async is allways good because it will use less resources when Waiting.
And while You wait you could perhaps do for example 5 Task in "Parallell".
But then You still have to wait for the longest query to end.
So perhaps WmiPingStatus could be useful also for You


Thread, handler and activity structure for a bouncing ball animation

I don't have time to do a full review, but here are some pointers.

Don't use raw access to members (view.x), but always use getters/setters instead.  It has been a Java convention for about 15 years.  Also, you should declare all your members as private.
Don't do many assignements on a single line (int x = view.x,y = view.y, ...).  Again, it does work, but the Java convention is to have one assignment per line.
Don't have Ball being a member of MyActivity and MyActivity being a member of Ball.  That is spaghetti code.
Avoid using Thread in Android, or Java.  There are cleaner and less dangerous patterns for working with concurrent code. For Android, you should look into AsyncTask; for example this.  You can probably find a more appropriate pattern if you look harder.
I haven't touch Android for a while, but I don't think onWindowFocusChanged is the usual callback where everything is started.


A couple of small things:

If you're specifically looking for executable files, you might use which instead of whereis command. From this answer, you can see the difference between the two using whatis:

$  whatis which
which                (1)  - shows the full path of (shell) commands

$  whatis whereis
whereis              (1)  - locate the binary, source, and manual page files for a command

Be consistent. You've used two different formatting styles:

"where {}".format(app)

and

"Application ,",app,", not forund.",err  # you also have a spelling mistake here (forund -> found)

I'd recommend you use the former one
You should have at least two spaces before an inline comment
You should put a space after the comma in almost every situation. (e.g: print("Application,",app,", not found.",err) -> print("Application,", app, ", not found.", err))


A few notes about your code:

Both the inner and outer method are fairly small, and the name of the outer method is already aptly descriptive, so I see no need for a named inner method here. An anonymous method would suffice.
List<T>.ForEach is a bit of an odd duck, in my opinion. It looks like functional programming (similar to Linq), but it's actually used to produce side-effects. Combining the two is giving off conflicting signals. A for or foreach loop, on the other hand, is clearly not functional-style, so side-effects would not be surprising.
I agree with keeping anonymous method parameter names short, but x isn't very descriptive. line is a little longer but much more descriptive.

Also, I find it more readable to put chained Linq calls on a line of their own:

var unnamed = finalCode
    .Where(x => x.Label != null && x.Label.Name == null)
    .ToList();

Having that said, I would go for a plain old foreach loop. It may not be as fancy, but it's simple and to the point, which should make it easier to understand:

int count = 0;
foreach (var line in finalCode)
{
    if (line.Label != null && line.Label.Name == null)
    {
        line.Label.Name = $"dyn_label{++count}";
    }
}


IPC The sleeping barber problem in C feedback

readline

buf is a pointer. sizeof(buf) is either 8 or 4, depending on the architecture. bzero(buf,sizeof(buf)); only clears 8 (or 4) bytes of the buffer.

Similarly, sizeof(strlen(fd.BUF)) is equal to sizeof(int), and 256 - sizeof(strlen(fd.BUF) always evaluates to 252, regardless of the fd.BUF contents. Doesn't look right, and may lead to a buffer overrun.

Looking for '\n' in fd.BUF may degrade the performance. Looking for it in temp would be faster (because temp is smaller).

I don't see why do you need temp at all. It only introduces an extra copy. You may read directly to fd.BUF.

strcpy(fd.BUF,fd.BUF+mv) is very dangerous, and technically introduces an undefined behaviour: strcpy is declared as
  cher * stpcpy(char * dst, const char * src);

The const states a contract, that the source string is not modified. You invocation violates the contract.


Keep track of possible values
A comment in your code says:

#backtracking depth-first search with constraint propagation

...but you're not actually propagating constraints. You can reduce the number of move validations by keeping track of the possible moves, i.e. the values a cell can  actually have. Each inserted value (correct or not) constrains the possible values of cells in the same row, column and box, thus reducing the number of values you have to consider in subsequent recursive calls.
Choose empty cells with least number of possible values
You're choosing the first empty cell. If that happens to have very little constraints, you're unnecessarily exploring a lot of possibilities that may have been invalidated if you had chosen a different cell first. Choosing the empty cell with the least number of possible values drastically reduces the breadth of your depth-first search tree.
Example implementation
I tried to stay close to your original code and this code should only demonstrate how you can implement the mentioned concepts. There are still things that could be improved, but since you specifically asked about time complexity I concentrated purely on that.
import numpy as np
from skimage.util import view_as_blocks  # pip install scikit-image

# input: 9x9 numpy array, empty cell = 0
# output: 9x9 numpy array: if not solution all array entries should be -1
# backtracking depth-first search with constraint propagation

# Returns (row, col) of an empty cell with the least number of possible values.
# Returns False if no empty cell exists.
def get_emtpy_cell_with_least_possible_values(sudoku, possible_values):
    min_possible_values = 10
    min_row = -1
    min_col = -1
    for i in range(len(sudoku)):
        for j in range(len(sudoku[0])):
            if sudoku[i][j] == 0:
                num_possible_numbers = sum(possible_values[i][j])
                if num_possible_numbers < min_possible_values:
                    min_possible_values = num_possible_numbers
                    min_row = i
                    min_col = j
    if min_possible_values < 10:
        return (min_row, min_col)
    else:
        # No empty cell found
        return False

def remove_possible_values(possible_values, row, col, value):
    """ Remove 'value' from the possible values in row, col, and the box containing
    cell [row][col]. Returns a list of tuples (row, col) for each cell that has been changed.
    """
    cells_changed = []
    for c_index, c in enumerate(possible_values[row]):
        if c[value - 1] == 1:
            cells_changed.append((row, c_index))
            c[value - 1] = 0

    for r in range(9):
        if possible_values[r][col][value - 1] == 1:
            cells_changed.append((r, col))
            possible_values[r][col][value - 1] = 0

    # Check box
    box_x = col // 3
    box_y = row // 3

    # y-axis/columns
    for i in range(box_y*3, box_y*3 + 3):
        # x-axis/rows
        for j in range(box_x * 3, box_x*3 + 3):
            if possible_values[i][j][value - 1] == 1:
                cells_changed.append((i,j))
                possible_values[i][j][value - 1] = 0
    return cells_changed

def restore_possible_values(possible_values, value, changed_cells):
    """ Restore 'value' as possible value for each cell (row, col) in 'changed_cells'.
    """
    for row, col in changed_cells:
        possible_values[row][col][value - 1] = 1

def solver(sudoku, possible_values):
    next_cell = get_emtpy_cell_with_least_possible_values(sudoku, possible_values)
    if not next_cell:
        return True
    else:
        row, col = next_cell

    # check insertion values 1-9
    for guessed_value in range(1, 10):
        if possible_values[row][col][guessed_value - 1] != 1:
            continue
        # update possible values and sudoku board for recursive call
        changed_cells = remove_possible_values(possible_values, row, col, guessed_value)
        sudoku[row][col] = guessed_value

        if solver(sudoku, possible_values):
            return True
        # restore possible values and sudoku board for next iteration
        restore_possible_values(possible_values, guessed_value, changed_cells)
        sudoku[row][col] = 0

    return False

def initial_invalid(sudoku):

    # Check row
    for i in range(9):
        dup_lst = []
        for j in range(9):
            if sudoku[j][i] != 0:
                if sudoku[j][i] in dup_lst:
                    return True

                else:
                    dup_lst.append(sudoku[j][i])

    # check column
    for i in range(9):
        dup_lst = []
        for j in range(9):
            if sudoku[i][j] != 0:
                if sudoku[i][j] in dup_lst:
                    return True

                else:
                    dup_lst.append(sudoku[i][j])

def sudoku_solver(sudoku):

    if initial_invalid(sudoku):
        return np.full((9, 9), -1)

    possible_values = np.ones((9,9,9), dtype=int)
    # initialize possible values based on already existing values
    for row in range(9):
        for col in range(9):
            value = sudoku[row][col]
            if value != 0:
                remove_possible_values(possible_values, row, col, value)

    if solver(sudoku, possible_values):
        return sudoku
    else:
        return np.full((9, 9), -1)

Some measurements on my computer using your examples:

original code
improved code

Sudoku 1
21.836s
1.449s

Sudoku 2
2.753s
0.639s

Sudoku 3
50.993s
0.479s


if n < 2
    1
else
    n * factorial_r(n - 1)
end

This is exactly equivalent to the following, which is called a ternary statement:

n < 2 ? 1 : n * factorial_r(n - 1)

Your factorial_r and factorial_r_recursion functions call each other, but this makes you call your validate function over and over. You should rewrite it so that factorial_r_recursion only ever calls itself, because you can ensure that everything it produces is valid already. (Same with the tr functions)

if n < 0 or not n.kind_of? Integer

This would be much better worded as:

unless n.is_a? Integer && n >= 0

No one uses kind_of?, and you need to check if the number is an Integer before you compare it to 0.

Although it doesn't appear to be in the scope of your project, ideally you would not call validate at the beginning of each factorial method. You would call it once, when you actually get n, and THEN pass it in to the factorial function.

Some last points; I recognize that this is a learning step for you, but do not use for loops in ruby. They have bad side effects and you do not need them, there are plenty of ways to iterate over collections. Also the while loop looks rather ugly but that's because it's the wrong tool for the job, so it's to be expected.

All in all, it's pretty decent ruby! Good job on using reduce / inject, a lot of beginners don't use/comprehend what they do., however reduce is an alias of inject so to have them both is kind of silly :P


What you did right is solve the problem.
What you did "wrong" really depends on a number of factors, so I'll respond with what you can do to improve it, with an example that implements those improvements.  Note, many improvements will make the code longer.
Improvements

Use the shebang #!/usr/bin/env ruby.  It allows the environment to have ruby in a different directory than /usr/bin/ruby.
Use $stderr.puts "Usage: #{$0} <a> <b> <c>".  $stderr is a global variable and can be changed.  It allows standard error to be redirected, say to a file or a logger.  It would be restored by $stderr = STDERR.
Ruby indentation standard is 2 spaces and no hard tabs.
Use disc_str to indicate it is a String version of disc.
Use disc_sqrt_str to indicate it is a String version of disc_sqrt.
Use a variable to reduce wasted calculations; sqrt is not a simple calculation.
Nested ? operators can be hard to read and can lead to mistakes.
Use numerator and denominator to convey intention, instead of s and d.
Allow for the case when discriminant is zero.
Use parentheses for arguments when method calls are arguments.  Thus instead of f g h x do f g(h(x)) or even better f(g(h(x))).
Use discriminant because it is a Mathematics domain term.  A non-mathematics literate developer will be blocked from maintaining it because Googling "disc" won't help them.
Eliminate common factors.
Eliminate fraction if denominator is 1.
Define methods for greater flexibility.
Include some tests to test each pathway.
Use appropriate comments and self-commenting code by using good names.
Use Rubocop to provide similar automated improvements.
Use the colorize gem in an optional way, since it is not actually necessary.
Check if it is available by using ''.respond_to?(:underline), which will mean that it is more flexible because another method could be added to String which might do a similar thing or even something rather different; CSS, LaTeX, ASCII, ... .
Use Unicode codes instead of the characters directly.  Some editors may not display Unicode characters properly and could change the characters to something unexpected.

#!/usr/bin/env ruby
#
#   quadratic   - Output quadratic solutions as a fraction
#
#     Luis Esteban    9 August 2020
#       review of code of Dmitry Kudriavtsev

# Output rational solutions to the quadratic equation
#   For a.x^2 + b.x + c = 0
#
#   x = (-b ± √d) / 2a
#   d = b^2 - 4.a.c       (discriminant)
#

begin
  require 'colorize'
rescue LoadError
end

ALLOW_IMAGINARY = true

def solve_quadratic(a, b, c)
  discriminant = b**2 - 4*a*c
  denominator  = 2 * a

  if discriminant > 0
    discriminant_sqrt = Math.sqrt(discriminant)
    if discriminant_sqrt % 1 == 0
      b, discriminant, denominator = simplify(b, discriminant_sqrt.to_i, denominator)
      numerator = [-b, " \u00b1 ", discriminant]
    else
      b, discriminant, denominator = simplify_with_sqrt(b, discriminant, denominator)
      numerator = [-b, " \u00b1 \u221a", discriminant]
    end
  elsif discriminant == 0
    solution    = Rational(-b, denominator)
    numerator   = [solution.numerator]
    denominator = solution.denominator
  else
    if ALLOW_IMAGINARY
      discriminant_sqrt = Math.sqrt(-discriminant)
      discriminant_sqrt = discriminant_sqrt.to_i if discriminant_sqrt % 1 == 0
      if discriminant_sqrt % 1 == 0
        b, discriminant, denominator = simplify(b, discriminant_sqrt.to_i, denominator)
        numerator = [-b, " \u00b1 i \u2a2f ", discriminant]
      else
        b, discriminant, denominator = simplify_with_sqrt(b, discriminant, denominator)
        numerator = [-b, " \u00b1 i \u2a2f \u221a", -discriminant]
      end
    else
      numerator = []
    end
  end

  [numerator, denominator]
end

def simplify(b, discriminant, denominator)
  gcd = [b, discriminant, denominator].inject(&:gcd)
  gcd = -gcd unless denominator.positive?

  [b, discriminant, denominator].map{|n| n / gcd }
end

def simplify_with_sqrt(b, discriminant, denominator)
  gcd = [b**2, discriminant, denominator**2].inject(&:gcd)
  gcd_sqrt = Math.sqrt(gcd).round
  if denominator.negative?
    gcd      = -gcd
    gcd_sqrt = -gcd_sqrt
  end

  [
    b            / gcd_sqrt,
    discriminant / gcd,
    denominator  / gcd_sqrt
  ]
end

def display_fraction(numerator, denominator)
  size        = numerator.size
  numerator   = numerator.join
  denominator = denominator.to_s
  width       = [numerator, denominator].map(&:length).max + 2

  if size > 0
    if denominator != "1"
      if ''.respond_to?(:underline)
        puts "#{numerator}".center(width).underline
        puts denominator.center(width)
      else
        puts numerator.center(width)
        puts "─" * width
        puts denominator.center(width)
      end
    else
      puts numerator
    end
  else
    puts "No solutions"
  end
end

if ARGV.length != 3
  $stderr.puts "Usage: #{$0} <a> <b> <c>"
  exit 1
else
  a, b, c = ARGV.map(&:to_i)
  puts "solution(s) to #{a}x\u00b2 + #{b}x + #{c} = 0"

  display_fraction(*solve_quadratic(a,b,c))
end

# Testing
#  [
#    [1, 1, -12],    # Integer discriminant
#    [-1, 1, 12],    # Make denominator positive
#    [1, 2, 0],      # Don't show denominator if 1
#    [4, 4, 1],      # Don't show discriminant if 0
#    [1, 2, -17],    # Don't show denominator if 1 with surd
#    [2, 4, 2],      # Don't show denominator if 1 and  discriminant if 0
#    [1, 1, -13],    # Show surd
#    [1, 2, 17],     # Imaginary solution with integer discriminant no denominator
#    [1, 2, 16],     # Imaginary solution with correct cancellation of surd
#    [2, 0, 2],      # Imaginary solution with surd, hide denominator
#    [2, 8, 16],     # Imaginary solution with integer discriminant
#  ].each do |a,b,c|
#    puts "For: a = #{a.inspect}, b = #{b.inspect}, c = #{c.inspect}"
#    puts
#    display_fraction(*solve_quadratic(a,b,c))
#    puts
#  end


Converting image size from Maybe (Int, Int) to (Float, Float)

I do not understand what benefit you get from the conversion to float
I would advise you to not mix - IO with the mostly pure calculation you have

so let us look at your code (minus the IO)

getImageSize :: DynamicImage -> Maybe (Int, Int)
getImageSize (ImageRGB8  (Image w h _)) = Just (w, h)
getImageSize (ImageRGBA8 (Image w h _)) = Just (w, h)
getImageSize _ = Nothing

but readImage already has a more useful return type than Maybe it has an Either String which is giving you error messages instead of Nothing so we can adjust.

getImageSize :: DynamicImage -> Either String (Int, Int)
getImageSize (ImageRGB8  (Image w h _)) = Right (w, h)
getImageSize (ImageRGBA8 (Image w h _)) = Right (w, h)
getImageSize _ = Left "Image type neither ImageRGB8 or ImageRGBA8"

this section could be improved a bit - also working on pure data

sizeToVec :: (Int,Int) -> Vec2D
sizeToVec (x,y) = Vec2D (fromIntegral x) (fromIntegral y)

you can then use those with the many mechanisms haskell provides you:

 readImage path :: IO (Either String DynamicImage)
 getImageSize :: DynamicImage -> Either String (Int, Int)
 sizeToVec :: (Int,Int) -> Vec2D

the last two you can combine à la

fmap sizeToVec (getImageSize img) -- or fmap sizeToVec . getImageSize

and the first two

doStuff = do eitherImg <- readImg mypathtoimg
             return $ do size <- getImageSize
                         sizeToVec size

or

doStuff = do eitherImg <- readImg mypathtoimg
             return (getImageSize eitherImg >>= sizeToVec)

or even shorter

doStuff = readImg mypathtoimg >>= (getImageSize >>= sizeToVec)

doStuff = readImg path >>= fmap sizeToVec . getImageSize

if I am not mistaken (I have no haskell env on this machine, therefore this code is untested - sorry)


Java has good support for OOP techniques - Using these will allow you to create a more elegant solution. Your code could be refactored with the correct use of these techniques to produce something of the form:

PegMachine sampleTest = PegMachine(500,100);
sampleTest.histogram;

This approach hides the complexities of the program and allows you to conduct tests by simply creating a PegMachine specifying the number of pegs and balls for each sample.

I noticed Aron_dc pointed out the slotIndex variable in your simulateDrop method is never used - This can be removed as it does not contribute anything to your program.

Out of curiosity I conducted a larger sample using your code to see if it produced the correct normal-distribution curve. The results were as expected; confirming your codes correctness.

Besides suggesting the use of object orientation your code seems well written and correct.


A few notes:

Firstly, I would add some docstrings to each function to document what the expected behaviour is.

In select when you're not doing any mutations (i.e. under the * case), it seems you could just return self. Is there any reason to make a new copy?

In select, where, astype instead of creating a temporary dict, you could use a dict comprehension instead, example:

def where(self, cond):
    return type(self)({key: value for key, value in self.json.items() if cond(key, value)})

In astype you're using JSONSelector, however everywhere else you're using type(self) this should be consistent whichever one you go for.

print seems like an unnecessary function, but if you keep it the return lines have no effect.

Hope that's helpful.


I suggest you read more about rules on simple rules for HTTP caching, and simple rules for AJAX caching. These should give you a heads up on gotchas, especially in IE as well as the right headers to send for HTTP caching.

A more proper way to do this is to send the right headers. This would mean some server-side action and using the Expires header.

Anyways, let's do cache busting instead. This is the method you are trying to do, which is to append a variable value into a query string. This assumes that your resources are "forever cached" and needs busting to bring in a new version.

Here's a few gotchas in your code:

It doesn't persist during page load.

Since you don't have any persistence layer in your code, each page load will generate a new time stamp for the resource, and will reload them from the server instead of the cache.
What happens when it expires?

I don't seem to see code that tells if the resource has already expired, unless you have other code that does that for you.

If without it, you should build a collection that records the urls and their times. Then you refer to that collection to get the url of the resource. If the resource has not expired, then return the previously generated url. If it has expired, then generate a new url with a new time stamp and hand it for use.

Here's code that should get you on the right track. This assumes that the resources never expire, so that you need the cache-buster mechanism going.

(function(ns){

  //Read from local storage, if any, or use an empty object
  var collection = /*read from local storage*/ || {};

  ns.generate(url,duration){

    //return a runnable function that generates either an existing url
    //or a newly generated url
    return function(){
      var currentDate = Date.now();

      //if URL isn't in collection or has already expired
      if(!collection.hasOwnProperty(url) || collection[url].expires < currentDate){
        //generate the url and store
        collection[url] = {
          url : url,
          expires : currentDate + duration;
          stampedUrl : url += '?_ts='+ (currentDate + duration)
        }

        /*save in local storage*/

      }

      //return the url
      return collection[url].stampedUrl;
    }
  }
}(this.StampedUrl = this.StampedUrl || {}));

Sample usage:

//Generate and store our URL. This should return a runnable function
//that returns an unexpired URL or a newly generated url
var myScript = StampedUrl.generate('http://example.com/someScript.js',3600);

//Use function to generate the URL.
$.get(myScript(),function(){...});


Building an efficient bubble sort function

Instead of using a regular for loop to loop through array:

for(int i=0; i<array.length; i++)
{
    System.out.print(array[i] + " ");
}

you can use a nicer foreach loop:

for (int i : array)
{
    System.out.print(i + " ");
}


This is exactly* the way you should be using your CursorAdapter. I'm sure you're referring to "recycling" the Views as talked about when overriding the getView() method of a BaseAdapter.

In the case of the CursorAdapter, all of that is taken care of for you so that just implementing newView() and bindView() fully takes advantage of the View recycling you're asking about.

Here is the code for CursorAdapter.getView():

public View getView(int position, View convertView, ViewGroup parent) {
    if (!mDataValid) {
        throw new IllegalStateException("this should only be called when the cursor is valid");
    }
    if (!mCursor.moveToPosition(position)) {
        throw new IllegalStateException("couldn't move cursor to position " + position);
    }
    View v;
    if (convertView == null) {
        v = newView(mContext, mCursor, parent);
    } else {
        v = convertView;
    }
    bindView(v, mContext, mCursor);
    return v;
}

So you see, the method attempts to recycle the View that was passed in by checking convertView == null. If successful, it uses that View and simply calls bindView() to set it up appropriately. If convertView is null, it calls newView() to create the View, followed by bindView() to set it up. This is one of the rare instances on SE that I can say "You're doing it right!"

But to nitpick, there's really no reason to maintain a reference to your Context in mContext - You're not using it anywhere and maintaining references to Contexts can lead to memory leaks, and ultimately the end of the world.


Putting array name in variable and shortening code

Is it possible to put the array name into a variable and iterate by a foreach loop?

YES.

Array ProductItems = Drinks.ToArray();
foreach(Product item in ProductItems)
                    {
                        Console.WriteLine(item.ProductName);
                    }

Now about your second question, (it's unclear what's the significance of the first question)...

If there are many products and user selects one from the combobox1 how to update the product details in listbox1? (is this your question?)

Answer : Make a Dictionary of combobox1 index and ProductList. Iterate over the combobox1 list and map the indexes with the ProductList. This may help.

Dictionary ProductDict = new Dictionary<int, List<Product>>();

Then after SelectedIndexChanged event is fired get the ProductList corresponding with combobox1 index. Then iterate over the list and add the details it in listbox.

General Review

Since productName and price is trivial make them auto-implemented properties

public string ProductName { get; set; }


Answers to Your Questions

Yes, this usage is acceptable if your intention was to have a Set of Observer objects that can be removed by the garbage collector if they are not referenced from elsewhere.
Instead of using the old-school synchronized keyword, I'd recommend to add a ReentrantReadWriteLock field in EventManager and use it in the three methods.
I think that your implementation is already quite simple, readable and usable. Making it better would depend on the goal you are looking for. But there are still a few remarks after these answers.
If you add another method like onEvent(EventType, Class), it will have drawbacks such as pollution of the APIs of the objects that do not need the second method, ambiguities in the choice of the method to use for the caller, etc. If you want to grant your user a possibility to define custom events, the simplest way that I see here is to replace the EventType argument with String: the API will not be coupled with the rigid enum (which needs to be modified in order to introduce a new event type) and the user will be able to define his own event types easily.

Other Remarks

Style: the m_ prefix for the private fields violates standard Java naming conventions.
There is no need to call observerManagers.containsKey() to check if the item is already in the map. For Maps, there is the putIfAbsent method that does exactly the same in one line.
I'm not sure that .filter(Objects::nonNull) and weakReferencedObservers.remove(null) are necessary in ObserverManager.callEvent. How do you expect null values to be present in the collection, if add method checks the object to be not null?


Is there a safer/ more readable way of using this code?

Well, at first glance, i think it should be:

Constructor shouldn't have any logic other than initialization. Any I/O, Threads .... operations would be better to start in custom method. So, in your case i will write:

public TemperaturePresenter(){
    _view = new MainView();
}
delegate in your example very large, my opinion - it should be extracted as a new method
Webrequest in Presenter? It depends, but I think it no so good. May be it would be better if you extract web-request logic as external dependency like ITemperatureProvider. Because now, it pull dependency on webserver file and file working into the presenter - it has some smell.

At first glance that's all.


Opening a CSV file in Python, with error handling

Don't handle the exception in this part of the code, since it will hide errors. Just let it bubble up.


A few things that I noticed, not necessarily in order:

The globally locked and secured total is an unnecessary bottleneck. The aggregation you're performing is really well-suited for subresult aggregation. Instead of updateScore which can only ever be entered by one thread, you should have a running aggregate as you traverse the node hierarchy.
Node should not know about NodeHandler. You're tightly coupling these two together through a static method, which makes your code hard to test. Instead of a static class, use dependency-injection
Your termination condition isn't perfectly secure against premature termination. Also the getTotal is basically busy-waiting. You also only ever have multiples of seconds when running this task, which doesn't bode well for smaller node-structures.
Declaring rawJson as a member-variable is not a good solution. The compiler may or may not notice that it's in fact a local variable and may or may not correctly free the memory you're not using anymore.
Java EE has a JsonParser implementation since Java 1. That implementation crucially allows directly streaming the JSON access, so long as you're using forward access only. This allows you to keep a minimal memory-footprint. Look into Json.createParser(InputStream)
Since you're creating tasks from your initial task, the ForkJoinPool and the use of ForkJoinTasks is the "correct" model to use here. With this knowledge we can rewrite your program to be significantly more idiomatic and probably quite a bit faster :) This also allows you to not need to think about the termination condition of your operation.


final Pattern LETTERS = Pattern.compile("[A-Za-z]");

Every time either getLetters or getNumbers is called, a new regex is created and compiled.

This is not very efficient, considering regex compilation can be fairly slow. I would recommend moving the compiling to the constructor. Then, you can set the new Patterns to be fields of the class.

Now, the regexes will be compiled once and only once.

I don't quite understand your design.

Initialize the class with a string.
Use the class methods to get different parts of the string.

What if I want to check another string? Well, considering the fact that you made inputString public, I'm assuming you want the code to just set inputString to something else:

myPatternMatcher.inputString =

Just to quickly say, the inputString should be private and there should be a setter for it. This is common Java practice.

However, that is not the point of this tip. My main point is that it is weird that I have to change a property of the class and then call another method of that class to work on the string I just passed in a second ago.

With setters, that would look like this:

myPatternMatcher.setInputString("foo");
myPatternMatcher.getLetters();

Isn't that a little weird having to call another method just to use the class?

I think a better approach would be to make the methods static. You could get rid of having to pass the inputString via the constructor, and you can move the pattern compilation to the fields themselves. Then, for each method, you can have it accept the string to check.

Now, your class would look like this:

public class PatternMatcher {
    public static String getLetters(String str) {
        ...
    }
    public static String getNumbers(String str) {
        ...
    }
}

Now, to use this class, it would look something like this:

PatternMatcher.getLetters("Foo");

This design makes more sense.


Linked list where user replace a chosen number in the list with a number chosen by user - how can it be improved?

For a new user of C you really aren't doing too bad, you're not using global variables which is very good. The functions are small and well defined. The program as a whole is well organized so that function prototypes are not required.

This program could have a few more function and that would simplify main():

A function that asks the user for input and performs error checking on the input before returning values, this would also localize the variables for input in the function
There are some basic linked list operations that are not here that might be helpful insert_node(), delete_node() and append_node() find_node(), other functions such as replace() can utilize these basic functions
It might be good to have a function that prints a title and then calls printlist() which would reduce the amount of code in main()
A function to initialize the linked list

Missing Error Checking

There are two places where error checking in this program, first, it is generally a best practice to error check all user input before using the input values. Users can make mistakes when entering data, they may just hit the enter key without entering data, they may enter a string instead of a number, they may enter a number that is not in the list which could cause problems while searching the list.

The second place where error checking is necessary is after any memory allocation in the C programming language, some or most high level languages will throw exceptions if memory allocation fails. In C programming if memory allocation fails the call to malloc(), calloc() or realloc() returns NULL. It is very important to check the value returned to make sure it is not NULL before using the memory, access through a NULL pointer causes unknown behavior. This can cause a number of problems including the crashing of the program or the corruption of data in the program.

node_t *create_new_node(int val) {
    node_t *result = malloc(sizeof(node_t));
    if (result == NULL)
    {
        fprintf(stderr, "malloc failed in create_new_node()\n");
        return result;
    }
    result->val = val;  // Unknown behavior here if malloc() failed
    result->next = NULL;
    return result;
}

Include Files That Are Not Necessary

The code contains #include <string.h> however, no functions defined in this include file are utilized. The `#include  statement copies the contents of the file into the current file, it will increase the compile time and if you are using an editor that also creates a makefile it may add an unnecessary dependency to the makefile. There may also be collisions with functions defined in the code. Basically don't include files you don't need.

Return From Main

The C compiler is smart enough to add return 0; at the end of this program, if the code does contain multiple returns from main() such as program failure when malloc() fails the code will be more readable if return EXIT_FAILURE; or return EXIT_SUCCESS;. These macros are included from stdlib.h which is already included in this program.

Readability

The code would be more readable and easier to maintain if there were spaces between operators and operands for (int i=0; i<25; i++) { versus for (int i = 0; i < 25; i++) {. It would also make the code more readable and maintainable if the 25 in the for loop was a symbolic constant

#define LIST_SIZE 25

...

    for (int i = 0; i < LIST_SIZE; i++) {
        tmp = create_new_node(i);
        if (tmp == NULL)
        {
            return EXIT_FAILURE;
        }
        tmp->next = head;
        head=tmp;
    }


PermMissingElem- find the missing element in a given permutation in C#

It is possible to solve the problem without sorting the array (which is expensive). The input array is actually a simple arithmetic sequence 1, 2, 3, 4 ... N+1, the numbers are just in a jumbled up order and one of them is missing.

The sum of the sequence is easy to calculate as n/2(1+n) (here n = N + 1). The sum of the input array will be the same as this, minus the value of the missing element. So the value of the missing element is the difference between the sum of the entire sequence and the sum of the input array.

    public static int permMissingElement(int[] elements)
    {
        int n = elements.Length + 1;
        int sumOfAllElements = (n * (1 + n)) / 2;
        int missingElement = sumOfAllElements - elements.Sum();
        return missingElement;
    }

Edit:

The maximum value of N is 100,000, which would cause an arithmetic overflow when calculating the sum of the sequence. The straightforward solution is to use longs for the calculations instead:

    public static int permMissingElement(int[] elements)
    {
        long n = elements.Length + 1;
        var sumOfAllElements = (n * (1 + n)) / 2;
        var missingElement = sumOfAllElements - elements.Select(x => (long)x).Sum();
        return (int)missingElement;
    }


You can for sure replace this loop by using Select()

public ActionResult Index()
{
    IEnumerable<MaterialRequestModel> model= DB.MaterialRequest
        .Where(m => m.MaterialStatusId == MatStatus.A9Cancelled || m.MaterialStatusId == MatStatus.A8Complete)
        .Select(r => new MaterialRequestModel(r, DB.Employees.Find(r.ConcernedEmployeeId), DB.Employees.Find(r.OrderedByEmployeeId), DB.Offices.Find(r.OfficeId)));
    return View(query.ToList());
}

or much cleaner by a separate method

public ActionResult Index()
{
    IEnumerable<MaterialRequestModel> model= DB.MaterialRequest
        .Where(m => m.MaterialStatusId == MatStatus.A9Cancelled || m.MaterialStatusId == MatStatus.A8Complete)
        .Select(r => CreateMaterialRequestModel(r));
    return View(query.ToList());
}

private MaterialRequestModel CreateMaterialRequestModel(MaterialRequest materialRequest)
{
    return new MaterialRequestModel(r, DB.Employees.Find(r.ConcernedEmployeeId), DB.Employees.Find(r.OrderedByEmployeeId), DB.Offices.Find(r.OfficeId));
}

which can be improved further by caching the employee and office in a dictionary.

private Dictionary<int, Employee> cachedEmployees = Dictionary<int, Employee>();
private Employee GetEmployeeById(Int id)
{
    Employee employee;
    if cachedEmployees.TryGetValue(id, out employee)
    {
        return employee;
    }
    employee = DB.Employees.Find(id);
    if(employee != null)
    {
        cachedEmployees[id] = employee;
    }
    return employee;
}

in the same way the office cacheing can be done, which results CreateMaterialRequestModel()

private MaterialRequestModel CreateMaterialRequestModel(MaterialRequest materialRequest)
{
    return new MaterialRequestModel(r, GetEmployeeById(r.ConcernedEmployeeId), GetEmployeeById(r.OrderedByEmployeeId), GetOfficeById(r.OfficeId));
}

there is only a small problem. Any changes to an employee or an office won't be reflected in the dictionaries.


Finding the maximum of a given list of data in GNU Assembly x86 (32 bit)

In general I try to stick to the naming conventions of the registers themselves. Although, I have been criticized for it because many programmers think of these conventions as archaic. But I think it helps reading the code.

  General-Purpose Registers (GPR) - 16-bit naming conventions[edit] The    8 GPRs are:

  Accumulator register (AX). Used in arithmetic operations.
  Counter register (CX). Used in shift/rotate instructions and loops.
  Data register (DX). Used in arithmetic operations and I/O operations.
  Base register (BX). Used as a pointer to data (located in segment register    DS, when in segmented mode).
  Stack Pointer register (SP). Pointer to the top of the stack.
  Stack Base Pointer register (BP). Used to point    to the base of the stack.
  Source Index register (SI). Used as a    pointer to a source in stream operations.
  Destination Index register (DI). Used as a pointer to a destination in stream operations.

Cited from: https://en.wikibooks.org/wiki/X86_Assembly/X86_Architecture

.section .data
data_1:
    .long 1, 3, 4, 5, 6, 7, 8, 9, 0
data_2:
    .long 23, 45, 62, 13, 87, 54, 0
data_3:
    .long 1, 3, 7, 6, 5, 8, 1, 1, 0

.section .text
.globl _start
.type maximum, @function
.type exit, @function

_start:
    movl    $data_3, %ebx
    call    maximum

exit:
    movl    %eax, %ebx
    movl    $1, %eax
    int     $0x80

maximum:
    movl    (%ebx), %edx # notice i did not index address here.
    movl    %edx, %eax
    movl    $1, %esi

max_loop:
    cmpl    $0, %edx
    je      exit_loop
    movl    (%ebx, %esi, 4), %edx
    cmpl    %edx, %eax
    cmovng   %edx, %eax
    incl    %esi
    jmp     max_loop

exit_loop:
    ret

Instead of passing the args on the stack, I opted to pass the address in the base register. AMD64 defines way different calling conventions than the original 32bit stuff. If this were a non trivial program we'd definitely want to adhere to the sysv calling conventions which define which registers may be overwritten or must be preserved between calls, stack alignment, etc. In the maximum function we could use a cmov__ instruction if we wanted to conditionally move the data register to the accumulator (current max) if it was greater.

The next book to get if you want to learn a great deal more about assembly AFTER programming from the ground up is Professional Assembly Language.

Linus Torvalds has criticized cmov instructions because of the out of order execution nature of modern processors. Which the Professional Assembly Language book explains in detail.

http://yarchive.net/comp/linux/cmov.html


something along these lines

public static class DTExtensions
{
    public static List<T> ToList<T>(this System.Data.DataTable dt) where T : new()
    {
        var obj = dt.Rows.OfType<System.Data.DataRow>().Select(dr => dr.ToObject<T>()).ToList();
        return obj;
    }
    public static T ToObject<T>(this System.Data.DataRow dataRow) where T : new()
    {
        T item = new T();
        var itemType = item.GetType();
        foreach (System.Data.DataColumn column in dataRow.Table.Columns)
        {
            System.Reflection.PropertyInfo property = itemType.GetProperty(column.ColumnName);

            if (property != null && dataRow[column] != DBNull.Value)
            {
                var result = Convert.ChangeType(dataRow[column], property.PropertyType);
                property.SetValue(item, result, null);
            }
        }

        return item;
    }
}

public class DataHandler
{
    private readonly string _ConnectionInfo = String.Empty;
    public DataHandler(string connectioninfo)
    {
        _ConnectionInfo = connectioninfo;
    }

    public async Task<System.Data.DataTable> DataAsync( string commandSQL, IEnumerable<System.Data.SqlClient.SqlParameter> listParameter=null)
    {
        System.Data.DataTable dt = new System.Data.DataTable("data");

        using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(_ConnectionInfo))
        {
            try
            {
                await connection.OpenAsync().ConfigureAwait(false);
            }
            catch (InvalidOperationException ex)
            {
                return null;
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                return null;
            }
            using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(commandSQL, connection))
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                if (listParameter != null && listParameter.Any())
                {
                    command.Parameters.AddRange(listParameter.Where(p => p != null).ToArray());
                }
                using (var r = await command.ExecuteReaderAsync(System.Data.CommandBehavior.SequentialAccess).ConfigureAwait(false))
                {
                    dt.Load(r);
                }
                command.Parameters.Clear();
            }
            connection.Close();
        }

        return dt;
    }
}

public sealed class Employee
{
    public string EmpID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class EmployeeDBHandler
{
    private readonly DataHandler _DataHandler;
    public EmployeeDBHandler(DataHandler datahandler)
    {
        _DataHandler = datahandler ?? throw new System.ArgumentNullException("datahandler");
    }

    public async Task<List<Employee>> GetEmployees()
    {
        System.Data.DataTable dt = await _DataHandler.DataAsync("GetAllEmployee").ConfigureAwait(false);
        if (dt != null)
        {
            //OR look into using yeild
            //yield return employee
            //OR
            var list = dt.ToList<Employee>();
            return list;
        }
        return null;
    }

    public async Task<List<Employee>> FetchEmployee(int empid)
    {
        List<Employee> empList = new List<Employee>();
        var parameters = new List<System.Data.SqlClient.SqlParameter> { new SqlParameter("@EmpID", empid) };
        System.Data.DataTable dt = await _DataHandler.DataAsync("usp_FetchEmployeeDetails", parameters).ConfigureAwait(false);
        if (dt != null && dt.Rows.Count>0)
        {
            var list = dt.ToList<Employee>();
            return list;
        }
        return null;
    }
}

//  main program:
public class MainProgram
{
    public void DoSomeWork()
    {
        string sqlConnstr = @"Data Source=<...>; Initial Catalog=<...>; User ID=username; Password=password"; //Utils.GetDBConnection();
        var dbHandler = new DataHandler(sqlConnstr);
        var employeeHandler = new EmployeeDBHandler(dbHandler);

        var employees = employeeHandler.GetEmployees();
        if (employees != null)
        {
            //.....
        }
    }
}


The names Worker and run are very general, while what they are doing is actually very specific (crawl a single web site for images matching a pattern). It would be better if the names reflected their content.
The magic numbers and strings in the code should either be parameters or constants. The thread count, for example, would be a good candidate for a parameter (since you might handle threading differently when importing Worker), while the different parts of the URL could be class constants.
Regarding main, it should IMO only contain that which is necessary for running from a shell (as opposed to importing the functionality in another Python program). That is, when importing everything except main there should be no missing pieces to get the same functionality as when running from a shell.


Brute Force N Body Implementation in C++

Here are some observations that may help you improve your code.

Make sure to #include all required headers

This program calls printf and srand but does not include the corresponding headers.  Fix that by adding these lines:

#include <cstdio>
#include <cstdlib>

Use objects

You have a Particle structure and then separate functions that operate on Particle data. With only a slight syntax change, you would have a real object instead of C-style code written in C++.  For example, you have a loop right now that says this:

for (int i = 0; i < N; i++)
{
    particles[i] = Update(particles[i], TIMESTAMP);
}

With objects, and with C++11 or newer, you could instead write this:

for (auto &p : particles)
    p.update(TIMESTAMP);

All that would be required would be to make Update a member function.

Prefer stream I/O to printf

The printf function was a capable workhorse for many years, but the C++ iostream library is better in a number of regards.  Although it's often more typing for the programmer initially, it's better because it has better type checking, less possibility for runtime overhead, and it fits well with the rest of C++.  So I would probably change your PrintParticle to this:

friend ostream& operator<<(ostream& out, const Particle &p) {
    return out <<
        "rx == " << p.rx_ <<
        " ry == " << p.ry_ <<
        " vx == " << p.vx_ <<
        " vy == " << p.vy_ <<
        " mass == " << p.mass_ << '\n';
}

Use const where practical

There are a number of things in your code that look and act like constants, such as numberofiterations in main().  Declare them as const for a program more resistant to error. Also, move the constants, such as N into main rather than having them at file scope.

Create a function rather than repeating code

The functions which create the particle use the same rand()-based function several times.  Instead of repeating it, make it into a function:

double xrand() {
    return 1e18*exp(-1.8)*(.5 - rand());
}

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  It isn't necessarily wrong to use, but be aware of when you absolutely shouldn't do it (such as in header files).

Consider using a better random number generator

If you are using a compiler that supports at least C++11, consider using a better random number generator.  In particular, instead of rand, you might want to look at std::uniform_real_distribution and friends in the <random> header.

Consider altering your algorithm

At the moment, the force on each particle from every other particle is calculated exhaustively, but Newton tells us that the force actually acts equally (but opposite) on both particles, so your loop could be simplified and calculations speeded if you take advantage of that fact to only calculate force vectors once and then apply them to both.

Double check your constant values

It seems to me that 3e4 is a somewhat large value for EPS.  Additionally, in the calculation of the random mass, the math is currently 1.98892e30*rand()*10 + 1e20, but why not simply write 1.98892e31*rand() + 1e20 instead?

Eliminate return 0 at the end of main

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


Code deletes unique entity that reports data later than 4 quarters, runs too slow

This uses an AutoFilter and performs the delete operation once (it should take less than a sec)

Option Explicit

Public Sub Two_Keep3Quarters()
    Const WS_NAME = "Filtered Data"

    Dim ws As Worksheet, tbl As ListObject, tblUR As Range, t As Double

    t = Timer
    Set ws = ThisWorkbook.Worksheets(WS_NAME)
    Set tbl = ws.ListObjects("DataTable")
    Set tblUR = tbl.Range.Offset(2).Resize(tbl.ListRows.Count - 1)

    Application.DisplayAlerts = False
    With tbl.Range
        tblUR.AutoFilter Field:=7, Criteria1:=">4", Operator:=xlAnd
        .Rows("1:2").Hidden = True

        On Error Resume Next    'For empty filter
        tblUR.SpecialCells(xlCellTypeVisible).EntireRow.Delete
        On Error GoTo 0

        .AutoFilter
        .Rows.EntireRow.Hidden = False
        .Cells(1).Activate
    End With
    Application.DisplayAlerts = True
    Debug.Print "Time: " & Format(Timer - t, "0.000") & " sec"
End Sub

Some issues with your code:

Missing Option Explicit
The Sub should be declared Public explicitly
Naming conventions: what's the difference between Lastrow and lRow

All variable names should start with a lower case letter

You turn Calculation to xlCalculationManual but don't change it back at the end
Some ranges are not fully qualified (bellow Range("F1"))

When you know the worksheet used you shouldn't qualify ranges with ActiveSheet

You're performing an extra rng.Rows.Delete which is unneeded

When deleting rows make sure you use EntireRow - it's faster

Tables (ListObjects) are dynamic so there is no need to Unlist and resize them
Inconsistent indentation (at the end)


Looks good.
There is not a whole lot to say that could improve performance. It's a pretty minimal example, so take that for what it is.

Table naming
Your DDL naming convention is hard to follow in your post_tags table:

CREATE TABLE `posts_tags` (
 `post` int(10) unsigned NOT NULL,
 `tag` int(11) NOT NULL,
 PRIMARY KEY (`post`,`tag`),
 KEY `tag` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Would be more logical if you specified it was an Id in the name:
CREATE TABLE `posts_tags` (
 `post_id` int(10) unsigned NOT NULL,
 `tag_id` int(11) NOT NULL,
 PRIMARY KEY (`post`,`tag`),
 KEY `tag` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Foreign keys
It looks like you don't have any FOREIGN KEY constraints, which may be a problem, or at least something you would want to integrate, so as to be able to raise key violations. For example, using the above-referenced table:
CREATE TABLE `posts_tags` (
 `post_id` int(10) unsigned NOT NULL,
 `tag_id` int(11) NOT NULL,
 PRIMARY KEY (`post`,`tag`),
 KEY `tag` (`tag`)
 FOREIGN KEY (post_id) REFERENCES posts(id),
 FOREIGN KEY (tag_id) REFERENCES tags(id),
) ENGINE=InnoDB DEFAULT CHARSET=utf8

One last thing. The back ticks in MySQL are only needed for names that use reserved characters/delimiters, for example names that have a space between words. The way you are naming your tables and columns, none of those would be needed.


Some comments based on my first impression:

Your code is a bit sparse on comments or documentation. Some more of that would be nice, in particular explain what arguments I’m supposed to supply to functions, and how I should interpret the return values.
Don’t skimp on characters for variable names. ary ~> array, elem ~> element. More expressive variable names are better; there's no need not to use full words.
The problem states “determine whether a given integer is in the array”, which sounds like a boolean. As such, I expected your search() function to return True/False.

Instead it returns a number (the index of the element if present) or None. That’s not wrong, but a docstring would have been helpful there.

On to more substantive comments:

You can definitely reduce the amount of code duplication in the two binary search functions.

Right now the binary search functions are responsible for picking the subset of the array that they search. I think that would be better handled by the caller – they should choose which subset of the array to inspect. That allows you to tidy up the search:

def binary_search(array, element):
    """Given an array of elements sorted in ascending order,
    perform a binary search to find this element.
    """
    ...

and then when you want to do a search in descending order, you can reverse the array before passing it in. Alternatively, you could do a check for the direction of the array when it’s passed into this function, and reverse it if necessary.

Then in your search function, take slices of the array and pass it into this function.
You can speed up some cases with a simple bounds check on the two halves of the array. Check that the element is between the first and last elements of the array.

For example: if I have a sorted array of 100 elements [1, ..., 1000], I know that –5 isn’t in that array just by inspecting the first and last numbers, without doing a binary search.

Adding a check that a number could plausibly be in an array will save you some operations.
In the search function, you check both the left and right-hand arrays before returning a result. If you find the element in the left-hand array, the result won’t change based on the right-hand array, so checking it is wasting CPU cycles.

A better approach would be something like:

if bin_search(ary, elem, 0, maximum - 1):  # left-hand array
    return True
elif bin_search_reverse(ary, elem, maximum + 1, len(ary) - 1)  # right-hand
    return True
else:
    return False

This is called short-circuit evaluation. You might be able to fit it onto one line – the or statement does this automatically – but the example above illustrates the principle.


The code here seems a bit over complicated for its intended purpose.

Would there be some issue with just appending a random number or hash to the end of each user name? something like taking all the user provided information and creating a sha-1 hash then just using the first 3 or so characters?

data = [fname,lname,fint,lint,urole]
Digest::SHA1.base64digest(data.join(''))
#=> f1ed8d7c48b27af459240984574c7bcd8b14fe4b

This would give you a very unique string to add to each username.


Truncating integer using string manipulation

If I understood your requirements correctly then it might be like this:

int roundUpto2digit(int cents) {
  if (cents < 100)
    return cents < 10 ? cents * 10 : cents;
  while ((cents + 5) >= 1000)
    cents /= 10;
  return (cents + 5) / 10;
}

The test:

#include <stdio.h>

void
test(int i) {
    printf("%d -> %d\n", i, roundUpto2digit(i));
}

int
main() {
    test(0);
    test(1);
    test(5);
    test(9);
    test(10);
    test(49);
    test(50);
    test(94);
    test(95);
    test(99);
    test(100);
    test(104);
    test(105);
    test(994);
    test(995);
    test(999);
    test(1000);
    test(1040);
    test(1050);
    return 0;
}

The result:

0 -> 0
1 -> 10
5 -> 50
9 -> 90
10 -> 10
49 -> 49
50 -> 50
94 -> 94
95 -> 95
99 -> 99
100 -> 10
104 -> 10
105 -> 11
994 -> 99
995 -> 10
999 -> 10
1000 -> 10
1040 -> 10
1050 -> 11

It is uncertain if [1, 9] range should map into [10, 90] (2 digits) or [1, 9] (1 digit). I could fix it, if the later case is true.


Find minimal number of days to meet all your friends

Making the set out of an interval is an immediate red flag. set is a heavyweight data structure, and making it is a heavyweight operation. It is also much easier to compute an intersection of two intervals, than of two sets.

Making the same set twice is another red flag.

All that said, it seems that you really overthink the problem. It admits a much simpler solution. Consider the friend whose window of opportunity closes the earliest. You want to meet him anyway, so make the most of it: select every friend whose window opens prior to it, schedule a party, and discard all the participants from further consideration; rinse and repeat.

Hint: do not sort the list of intervals. Sort the list of events (interval openings and closings).

Two things I intentionally don't want to spell out:

Prove that this algorithm does produce an optimal solution, and
How to efficiently discard the friends you've already met.


There's no need to repeat yourself by defining DESCRIPTION (and in fact your strings have gotten out of sync).  Just reuse the program's docstring:

def get_arguments():
    """Parse the commandline arguments from the user"""
    parser = argparse.ArgumentParser(description=__doc__)
    …


slice combines some lookups. The index arithmetic can be frontloaded.

eval :: Intcode -> Intcode
eval = go [0,4..] where
  go (index:es) intcode =
    let
      [opcode, v1Pos, v2Pos, savePos] = toList $ slice index 4 intcode
      v1 = intcode ! v1Pos
      v2 = intcode ! v2Pos
    in
      case intToOp opcode of
        Add  -> go es $ intcode // [(savePos, v1 + v2)]
        Mult -> go es $ intcode // [(savePos, v1 * v2)]
        Noop -> intcode

// takes linear time on immutable vectors. Noop should be Halt. This displays the unreliability of adding data types for their suggestive names. Therefore, inline intToOp.

eval :: Intcode -> Intcode
eval = modify $ \intcode ->
  void $ runMaybeT $ for_ [0,4..] $ \index -> do
    [opcode, v1Pos, v2Pos, savePos] <- traverse (read intcode) [index..index+3]
    v1 <- read intcode v1Pos
    v2 <- read intcode v2Pos
    case opcode of
      1 -> lift $ write intcode savePos $ v1 + v2
      2 -> lift $ write intcode savePos $ v1 * v2
      99 -> empty
      _ -> error $ "invalid opCode, should not happen" ++ show opcode

Of course, all of this imperativeness doesn't feel Haskell. However, interpreting an imperative language is pretty much the one time you need not feel bad about that.


Convenience function wrapping C++17's std::sample for distance=1 case

A pointer is an iterator.
template <typename InputIterator, typename URBG>
auto singleRandomSample(InputIterator first, InputIterator last, URBG&& rng)
{
    using value_type = typename std::iterator_traits<InputIterator>::value_type;

    auto result = value_type{};

    std::sample(first, last, &result, 1, std::forward<URBG>(rng));

    return result;
}

Or, with a better, C++20 interface:
template <std::input_iterator I, std::sentinel_for<I> S, typename URBG>
    requires std::uniform_random_bit_generator<std::remove_reference_t<URBG>>
auto singleRandomSample(I first, S last, URBG&& rng)
{
    auto result = std::iter_value_t<I>{};

    std::ranges::sample(first, last, &result, 1, std::forward<URBG>(rng));

    return result;
}

template <std::input_range R, typename URBG>
    requires std::uniform_random_bit_generator<std::remove_reference_t<URBG>>
auto singleRandomSample(R&& r, URBG&& rng)
{
    auto result = std::ranges::range_value_t<R>{};

    std::ranges::sample(r, &result, 1, std::forward<URBG>(rng));

    return result;
}

This requires the value type of the range to be default-constructible, but you were already counting on that with the array solution.
If you want a solution that does not require default construction, you could probably do something like using an optional type—like std::optional, or std::variant with std::monostate—and a custom output iterator that does an emplace into it.


Your application is a nice candidate for the command pattern. With a few changes you can make it easily extendable and maintainable. Here's how it goes:

First you need an interface for such a command. Each command needs at least a descritpiton and it must be able to do something:

interface ICommand
{
    string Description { get; }
    void Execute(BookList books);
}

Next we can start implementing the commands:

class AddBookCommand : ICommand
{
    public string Description => "Add a book.";
    public void Execute(BookList books) { }
}

class DeleteBookCommand : ICommand
{
    public string Description => "Delete book.";
    public void Execute(BookList books) { }
}

class ExitCommand : ICommand
{
    public string Description => "Exit.";
    public void Execute(BookList books) { Environment.Exit(0); }
}

Then in your Main you could create all the commands:

var commands = new ICommand[]
{
    new AddBookCommand(),
    new DeleteBookCommand(),
    new ExitCommand()
};

a list of books:

var books = new BookList();

and the main loop:

while (true)
{
    Console.WriteLine("Welcome to Library.");
    Console.WriteLine("What do you want to do?");

    // This loop creates a list of commands:
    for (int i = 0; i < commands.Length; i++)
    {
        Console.WriteLine("{0}. {1}", i + 1, commands[i].Description);
    }

    // Read until the input is valid.
    var userChoice = string.Empty;
    var commandIndex = -1;
    do
    {
        userChoice = Console.ReadLine();
    }
    while (!int.TryParse(userChoice, out commandIndex) || commandIndex > commands.Length);

    // Execute the command.
    commands[commandIndex - 1].Execute(books);
}

This is just a start. You still need to add console maintenance like .Clear  some more error checking etc.


ExcelVBA loop exports data from spreadsheet to table within Excel

I'm having difficulty in visualising your data here, a screenshot would be really useful.

In the meantime:

Option Explicit

This should be at the top of every code module you ever create in VBA. Go to Tools --> Options --> Require Variable Declaration and it will automatically insert it for you from now on.

This is important because without it, VBA will interpret any new variable names (including mis-spellings) as entirely new variables, instead of what you intended.

It also forces you to declare your variables. So you must explicitly give them a type (Long, String, Variant etc.) and a scope (Procedure Dim var As, Module Private Var As, Project Public Var As).

This will then automatically catch all sorts of unintended situations (such as accidentally setting a number equal to an object) which would not be caught if VBA has to assume that all your variables are Variant because you never explicitly declared them.

Magic Variables

And not the good kind of magic either. A Magic Variable is any value which is hardcoded. Especially if it's hardcoded in multiple places.

  lr = Cells(Rows.Count, 1).End(xlUp).Row

Why 1? How was that number determined?

  "Bac Form", "A1", "Q3" etc.

Why those values in particular? If you can't look at a variable and know what it represents, then it has appeared in your code as if by magic.

If you have to hardcode values, then they should be hardcoded precisely once, into a descriptively named variable.

This:

  FolderPath = "C:\Users\Joe.Dimaggio\Desktop\PDFs"

is the right way to hardcode a value. It's written once, and I can see FolderPath later on in the code and know exactly what it is.

This:

For x = 2 To lr
    Sheets("Bac Form").Range("A2").Value = _
    Sheets("Q3").Cells(1, 1).Value & Sheets("Q3").Cells(x, 1).Value
    Sheets("Bac Form").Range("A3").Value = _
    Sheets("Q3").Cells(1, 2).Value & Sheets("Q3").Cells(x, 2).Value & _
    " (Third Bacterial Quarter)"
    Sheets("Bac Form").Range("A4").Value = _
    Sheets("Q3").Cells(1, 3).Value & Sheets("Q3").Cells(x, 3).Value
    Sheets("Bac Form").Range("B4").Value = _
    Sheets("Q3").Cells(1, 4).Value & Sheets("Q3").Cells(x, 4).Value
    Sheets("Bac Form").Range("A5").Value = _
    Sheets("Q3").Cells(1, 5).Value & Sheets("Q3").Cells(x, 5).Value
    Sheets("Bac Form").Range("A6").Value = _
    Sheets("Q3").Cells(1, 6).Value & Sheets("Q3").Cells(x, 6).Value
    Sheets("Bac Form").Range("A7").Value = _
    Sheets("Q3").Cells(1, 7).Value & Sheets("Q3").Cells(x, 7).Value
    Sheets("Bac Form").Range("A8").Value = _
    Sheets("Q3").Cells(1, 8).Value & Sheets("Q3").Cells(x, 8).Value
    Sheets("Bac Form").Range("A9").Value = _
    Sheets("Q3").Cells(1, 9).Value & Sheets("Q3").Cells(x, 9).Value
    Sheets("Bac Form").Range("A10").Value = _
    Sheets("Q3").Cells(1, 10).Value & Sheets("Q3").Cells(x, 10).Value

is not. What happens if the name of your sheet changes? Or your data table moves because someone inserted/deleted a column/row? You'll have to go and re-code every single value.

Naming

Variable names should be Concise, Descriptive and, above all, Unambiguous.

  FolderPath

is a good name because it's clear exactly what the variable contains/represents.

  lr

is not. If I encounter that line halfway through your code, I'm going to go all the way back through to remind myself what it's meant to be representing. Just call it lastRow and you avoid all that trouble.

VBA Naming Conventions:

Typical VBA Naming conventions go as follows:

camelCase for local variables.

PascalCase for Module/Global Variables.

SHOUTY_SNAKE_CASE for constants.

Get in the habit of following them.

Bringing it all together

Step 1, put your worksheets in variables:

For x = 2 To lr
    wsBacForm.Range("A2").Value = wsQ3.Cells(1, 1).Value & wsQ3.Cells(x, 1).Value
    wsBacForm.Range("A3").Value = wsQ3.Cells(1, 2).Value & wsQ3.Cells(x, 2).Value & " (Third Bacterial Quarter)"
    wsBacForm.Range("A4").Value = wsQ3.Cells(1, 3).Value & wsQ3.Cells(x, 3).Value
    wsBacForm.Range("B4").Value = wsQ3.Cells(1, 4).Value & wsQ3.Cells(x, 4).Value
    wsBacForm.Range("A5").Value = wsQ3.Cells(1, 5).Value & wsQ3.Cells(x, 5).Value
    wsBacForm.Range("A6").Value = wsQ3.Cells(1, 6).Value & wsQ3.Cells(x, 6).Value
    wsBacForm.Range("A7").Value = wsQ3.Cells(1, 7).Value & wsQ3.Cells(x, 7).Value
    wsBacForm.Range("A8").Value = wsQ3.Cells(1, 8).Value & wsQ3.Cells(x, 8).Value
    wsBacForm.Range("A9").Value = wsQ3.Cells(1, 9).Value & wsQ3.Cells(x, 9).Value
    wsBacForm.Range("A10").Value = wsQ3.Cells(1, 10).Value & wsQ3.Cells(x, 10).Value

And suddenly the structure becomes clear.

Then:

Add options to change the row/column position of your tables.
Loop through rows/columns.
Add separate variables for each sheet to deal with (potentially) separate positions.
Add an index counter to track where to insert extra text.
Put the filename creation on a separate line.
Add proper Range objects.

And now, if you need to change something, or your data tables get bigger, or you need to modify a specific aspect of the execution, you can just change one value and the rest is done for you.

Private Sub CommandButton1_Click()

    Dim fileName As String

    Const FOLDER_PATH As String = "C:\Users\Joe.Dimaggio\Desktop\PDFs"

    Dim wsBacForm As Worksheet, wsQ3 As Worksheet
    Set wsBacForm = Sheets("Bac Form")
    Set wsQ3 = Sheets("Q3")

    Dim q3BaseRow As Long, q3BaseCol As Long '/ Location of the Q3 data table
    q3BaseRow = 1
    q3BaseCol = 1

    Dim bacBaseRow As Long, bacBaseCol As Long '/ Location of the bac output table
    bacBaseRow = 1
    bacBaseCol = 1

    Dim lastRow As Long, lastCol As Long
    lastRow = wsQ3.Cells(Rows.Count, q3BaseCol).End(xlUp).row
    lastCol = wsQ3.Cells(q3BaseRow, Columns.Count).End(xlToLeft).Column

    Dim bacRow As Long, bacCol As Long, q3Row As Long, q3Col As Long
    Dim row As Long, col As Long, counter As Long

    Dim bacOutputCell As Range, q3HeaderCell As Range, q3DataCell As Range
    Dim outputString As String

    For row = q3BaseRow To lastRow
        bacRow = row - q3BaseRow + bacBaseRow
        q3Row = row

        counter = 0
        For col = q3BaseCol To lastCol
            counter = counter + 1
            q3Col = col

            Set bacOutputCell = wsBacForm.Cells(bacRow, bacBaseCol)
            Set q3HeaderCell = wsQ3.Cells(q3BaseRow, q3Col)
            Set q3DataCell = wsQ3.Cells(q3Row, q3Col)

            outputString = q3HeaderCell.Value & q3DataCell.Value

            Select Case counter '/ used a counter so that it is (absolute position of column) agnostic

                Case Is = 2
                outputString = outputString & " (Third Bacterial Quarter)"

                Case Is = 14
                outputString = outputString & " colony/100 ml"

                Case Is = 16
                outputString = outputString & " MPN/100 ml"

            End Select

            bacOutputCell.Value = outputString
        Next col

        fileName = FOLDER_PATH & "\" & wsBacForm.Name & "(" & wsQ3.Name & ")" & (row - 1)
        wsBacForm.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fileName, openafterpublish:=False
    Next row

End Sub


There is much to say about this piece of code. I'll just focus on some parts of it.

One long method

There is one long main method. It makes it hard to get an overview of what is happening. Consider breaking the main method into several methods that each does its piece. Something like.

public static void main(String...args){
    int[] randomNumbers = generateNumbers();
    String result = format(randomNumbers);
    result += formatNumberOfOccurences(randomNumbers);
    result += formatGraph(randomNumber);
    System.out.println(result);
}

// 4 methods omitted....

In this way you will get smaller chunks that is easier to understand. Each of these methods except the number generator is also easy to unit test since the outcome is the same for each argument. The code you have now is hard to unit test.

Printing with System.out

This is handy in many ways. But this is the main reason you need two loops for the code you have highlighted. Since you want to print the occurrence count first and then the graph you ned to do it in separate loops. If you instead store the intermediate result in a local variable then you can do it in one loop. Something like:

String occurrencesReport = "";
String graph = "";

for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
{
    occurrencesReport += "The number " + (countOfNumbers + 1) +
        " occurs " + countOfArray[countOfNumbers] + " times.";

    if (countOfNumbers != 9)
        graph += (countOfNumbers + 1) + "   ";
    else
        graph += (countOfNumbers + 1) + "  ";

    for (int a = 0; a < countOfArray[countOfNumbers]; a++)
    {
        graph += "*";
    }
    graph += "\n";
}

System.out.println(occurrencesReport);
System.out.println(graph);

Readability example

This little piece:

if (countOfNumbers != 9)
    graph += (countOfNumbers + 1) + "   ";
else
    graph += (countOfNumbers + 1) + "  ";

can be simplified like so:

graph += (countOfNumbers + 1) + "  ";
if (countOfNumbers != 9) graph += " ";

this makes it easier to understand what is going on. (On a side note - most people dislike the absence of curly braces in this code snippet. If you add a statement yo your if-block it will actually be outside if curly braces are omitted. I tend to do ifs on one line when they are short. But people don't like that either....) This example can be applied to at least one more piece of the code where there is unnecessary repetition.

Better stop now - just some bits and pieces I hope you can use to improve!


Indentation and whitespace
The Ruby convention is 2 spaces of indentation, and blank lines between methods. I'd also recommend spaces between arguments and operators, e.g. @hour = hour.
Naming
Don't use underscores in class names. It's clear that Regular_ParkingSpace is a kind of ParkingSpace because it inherit directly from that parent class. A name like RegularSpace would be more straightforward and less of a mouthful.
attr_accessor
You're adding a number of synthesized accessor methods with attr_accessor but you never use those methods. Instead you access instance variables directly. My advice is to always use accessor methods when you can. However, attr_accessor generates both readers and writers, and they're public. Which means that external code can just say parking_lot.size = 9999, which doesn't make sense. Of course, you never actually use the size attribute for anything, which brings me to my next point:
Junk code
It sounds harsh, but I just mean "code that doesn't actually do anything". For example the @size variable in ParkingLot which is never used. Or Regular_ParkingSpace having a payment method that just calls super - something that'd happen automatically if the method wasn't there.
Dangerous assumptions
Speaking of the parking lot's size, your way of determining the number of handicap spaces is not vary robust. You just assume it's going to be one tenth of the spaces. Well, what if the parking lot has 8 spaces in total? Then you have 0.8 of a handicap space, and 7.2 regular ones. Or what if it has 213 spaces? Then you have 21.3 handicap spaces. Neither situation makes any sense. For that matter who says there are any handicap spaces at all? There's no reason - that I know if - to assume there's any proportional relationship between the two numbers.
Outright bugs
Following from the above: The way you check for remaining spaces assumes integers. If the remaining number of spaces is anything above zero, you assume that that means there's a whole parking space there. So, in turn, you assume that whatever size was originally passed to ParkingLot.new is cleanly divisible by 10. But that's not given.
End result is that if I make a parking lot with 8 spaces, I can fit 9 vehicles: 1 handicap vehicle (in the 0.8 of a space), and 8 regular ones (the first 7 get a space each, and the last one has to fit in 0.2 of a space).
Oh, and I can just park a car for zero hours, and I'll pay zero rupees.
Pointless classes
You parking lot classes don't really serve any purpose being classes. You instantiate one of them, only to call payment and then discard the instance. In the end, you classes could be replaced with methods, or even just an expression: a * b.
Informal exceptions
Don't just raise a string; create an exception class that inherits from StandardError and raise it instead.

In other words, there's a lot going on here. Making it "more object-oriented" is a secondary concern. And with no concept of time passing, hourly rates don't really make much difference. It's a little weird that the cost gets calculated immediately when parking, and "paid" when the car's retrieved. A real parking lot would do one or the other: Pre-pay for x amount of time (with the possibility of an extra fee if you overstay), or pay for time used when leaving. This is neither of those.


I don't know Dart, but I haven't had any problems with Javascript regular expression speed, so I don't see why it would be a problem with Dart.

If you format strings are long -- which is probably unlikely -- then scanning the whole string once for each substitution string is not ideal. It's also buggy. Consider the calls:

formatStringListRegExp(['{0} {1}', '{1}', 'foo'])
formatStringListRegExp(['{0} {1}', 'foo', '{0}'])

So what I'd do is this (all error checking removed for brevity):

String formatStringListRegExp(List<String> args)
{
  return args[0].replaceAllMapped(new RegExp(r'{(\d+)}'),
                                  (Match m) => args[int.parse(m[1])+1])
}


Sieve of Eratosthenes solution for CodeEval

Your if statement can be moved out of the loop, if you do you need to change the range to start at 2.

A[0] = 0
A[1] = 0
for i in xrange(2, int(math.sqrt(n))):

For your other loop, we can think of the algorithm slightly differently.
You start at i ** 2, you take a step of i, and it ends on len(A) (shown by the try-except).
Or:

for j in xrange(i ** 2, n + 1, i):

As for filter you can change it to use bool or None instead of the lambda.
Alternately you can change it to a list comprehension:

return [i for i in A if i != 0]

This makes the code simple:

def factorfinder(n):
    A = range(n + 1)
    A[0] = 0
    A[1] = 0
    for i in xrange(2, int(math.sqrt(n))):
        for j in xrange(i ** 2, n + 1, i):
            A[j] = 0
    return filter(bool, A)


I discovered an (arguably) better way of doing this in F# using Seq.unfold and tuples. I'll post the solution below.

open System

(1,1) |> Seq.unfold (fun (a, b) -> Some(a + b, (b, a + b)))
|> Seq.takeWhile (fun x -> x <= 4000000)
|> Seq.sumBy (fun x -> if x % 2 = 0 then x else 0)
|> printf "The sum of Fibonacci terms up until 4,000,000 is: %d"
Console.ReadKey () |> ignore