Search through fortran source for a string ignoring comments

Shebang
#!/usr/bin/python is not portable, #!/usr/bin/env python is preferred.
White Space
There should be a blank line between your imports and your function declarations.
Efficiency
You are constantly converting your cond to lowercase.  You don't need to repeatedly do this; just do it once, before the loop.
Right Leaning Code
As you've mention, the code is way-too right leaning.
You could fix this with continue type statements ...
def fgrep(file_name, cond):
    first_valid_chars=tuple(range(0,10 )) + (' ',)

    # Fortran is case insensitive so comparing lower to lower
    cond = cond.lower()
    with open(file_name, 'r') as f:
        for line in f:
            if line[0] not in first_valid_chars:
                continue

            line1 = line.strip()
            if not line1:    # ignore empty lines
                continue

            if line1[0] == '!':
                continue

            if cond in line1.lower():
                print(line1)

RegEx
You could use a Regular Expression to identify comment lines.

\s*! would find an exclamation mark after any number of spaces.
[^\d\s] would match anything but a digit or a white-space character.

Combined these with the | or-operator, and use .match() to search from the start of the string, and you get an easy comment-line predicate:
def fgrep(file_name, cond):
    # A comment line starts with an exclamation mark as the first non-blank character,
    # or any non-blank character other than a digit as the first character.
    comment = re.compile(r'\s*!|[^\d\s]')

    # Fortran is case insensitive so comparing lower to lower
    cond = cond.lower()

    with open(file_name, 'r') as f:
        for line in f:
            if not comment.match(line) and cond in line.lower():
               print(line)

Line numbers
You might want to print out the line number of the matching line, to make it easier to find the lines in the file.  enumerate would help:
def fgrep(file_name, cond):
    # A comment line starts with an exclamation mark as the first non-blank character,
    # or any non-blank character other than a digit as the first character.
    comment = re.compile(r'\s*!|[^\d\s]')

    # Fortran is case insensitive so comparing lower to lower
    cond = cond.lower()

    with open(file_name, 'r') as f:
        for line_no, line in enumerate(f, 1):
            if not comment.match(line) and cond in line.lower():
               print(line_no, line, sep=": ")


Feeding stateful and stateful-effectful computations into each other

What I'd like to improve on this code is two things:

Reduce the lens piping. I could, of course, get rid of _1, _2 and _3 by using a bespoke record type, but then that introduces its own noise -- sim is the only function that uses this particular combination of I, S and O.

Is this really a problem? I don't understand what could be improved about that part.

The write-back to inp' could easily be accidentally omitted, resulting in not-obviously-wrong-looking, well-typed code that
wouldn't work correctly.

You can move the state-passing of I into a separate function for which that's the only job:
withInput :: ALens' s i -> (i -> StateT s i) -> StateT s ()
withInput l go = do
  i <- use (cloneLens l)
  i' <- go i
  cloneLens l := i'

...
sim = do
  withInput _1 $ \inp ->
    inp' <- ...
    pure inp'
  ...

The result type () of withInput makes it difficult to forget to update the state: the function would fail to typecheck if you forget the last clause.


This is an improvement on the answer by @coderodde. Just like they said, you can do this in \$\mathcal{O}(n)\$ time by counting how often each digit appears and then using a fixed output format. However, I would use collections.Counter from the standard library and string multiplication to achieve this goal:

from collections import Counter

def largest_number(string: str) -> str:
    counters = Counter(map(int, string))
    return "".join(str(d) * counters[d] for d in range(9, -1, -1))

Compared to sorting, as presented in the answer by @bullseye, and the original answer, this compares OK. It has a slight overhead for small strings due to the Counter object, but in the end it is faster than hardcoding character values and on the same level as sorting, but not better.

However, all three are vastly better than your \$\mathcal{O}(n^2)\$ algorithm (note the vastly different x limits):

As soon as you have three or more testcases, it might make sense to not repeat the testing code. Just put the input and expected output into a data structure (a list of tuples would do here), and iterate over it:

if __name__ == '__main__':
    test_cases = [("12345", "54321"), ("4689123", "9864321"), ("9", "9"), ("", "")]
    for string, expected in test_cases:
        output = largest_number(string)
        if output != expected:
            raise AssertionError(f"{string!r} gave back {output!r}"
                                 f" instead of {expected!r}")

For more complicated programs you might want to look at a testing framework like unittest.


Different class name based on condition in React

if you're just trying to decide between number--high number--medium or '' based on the condition variable, then just make a helper function that does that

then do return
{number}


BFS for creating a queue without repetitions and with loops in the graph

As far as I can tell, this code seems pretty easy to follow, especially with the comments.  Here are several things that stood out to me:

Since you haven't provided your own queue implementation, I assume you're using std::queue.  If so, remove using namespace std and use std:: where necessary.
This entire method should be const.  You're modifying three local containers and returning one, while not modifying any class members.  By making this const, data members will stay immutable (modifications will cause compiler errors) and the reader will be aware of this.

queue<string> CEngineInternal::GetFiltersListToRun() const

filtersBFS is not a very descriptive name; we know this program is about BFS.  It's also not the local queue that is returned, so it is unclear what this is used for within the function.
Your functions start with a capital letter, which is not proper naming in C++.  Only user-defined types should be named this way.  Your variables (except for FilterName) are named correctly, however.  Both variables and functions should start with a lowercase letter.
For this line:

for(BaseFilterMap::const_iterator it = m_Filters.begin(); it != m_Filters.end(); it++)

It may be more readable to declare the iterator type before the loop.

In addition, it may be better to use pre-increment since you're not dealing with basic types.  This could also potentially avoid an extra copy.

BaseFilterMap::const_iterator it;

for (it = m_Filters.begin(); it != m_Filters.end(); ++it) {}

However, if you're using C++11, consider auto instead of your current iterator.  The compiler will determine the correct type, and it's more readable.  You may also keep it inside the loop statement.

for (auto it = m_Filters.begin(); it != m_Filters.end(); ++it) {}

Better yet, if you're using C++11, consider a range-based for-loop:

for (auto& it : m_Filters) {}

This:

if (outPinConnections.size() != 0)

should instead use !empty():

if (!outPinConnections.empty())

For here:

for (size_t i = 0; i < outPinConnections.size(); ++i) {}

If this is the size type returned by size(), make it std::size_t since this is C++.  Otherwise, make sure you're using the correct size type to avoid potential loss-of-data warnings.
These:

(*it).first;
(*it).second;

should use the more readable -> operator:

it->first;
it->second;

You say:

  If I have a loop, I only want to count the end of the loop once.

But I don't see that anywhere in the code, plus there are multiple loops used here.  If you're still receiving the correct output and no errors associated with them, then they should be okay.


Swift: arrayToTree() where array contains int and nil

Simplifying func arrayToTree()

This

   var nodes = [TreeNode?]()
   for num in 0..<self.count{
       if let num = self[num]{
           nodes.append(TreeNode(num))
       }
       else{
           nodes.append(nil)
       }
   }

creates a new array by mapping each element in self (an optional Int) to a new element (an optional TreeNode). That can be simplified to

let nodes = self.map { $0.map { TreeNode($0) } }

where the outer Array.map maps the given array to a new array, and the inner Optional.map maps an optional Int to an optional TreeNode.

The

   var i = 0
   repeat {
       // ...
       i += 1
   } while i < (self.count) / 2

loop can be simplified to

for i in 0..<self.count/2 {
    // ...
}

The forced unwrapping

   return nodes.first!

cannot crash – the nodes array cannot be empty at this point. I would still suggest to avoid it since later code changes might break the logic. It also makes it easier for future maintainers of the code to verify its correctness.

Actually the preceding code just results in an empty nodes array if the given list is empty. Therefore we can remove the initial guard and replace it by

guard let first = nodes.first else {
    return nil
}
return first

at the end of the method. This can be further shortened to

return nodes.first.flatMap { $0 }

Putting it together, the function would look like this:

func arrayToTree() -> TreeNode? {

    let nodes = self.map { $0.map { TreeNode($0) } }
    for i in 0..<self.count/2 {
        nodes[i]?.left = nodes[2 * i + 1]
        if self.count > 2 * i + 2 {
            nodes[i]?.right = nodes[2 * i + 2]
        }
    }

    return nodes.first.flatMap { $0 }
}

An alternative implementation

What you have is a way to create a TreeNode, and that is what initializers methods are for. Therefore I would put the code in a

public convenience init?(values: [Int?])

of the TreeNode class instead of an Array extension method. The usage would be

let list = [3, 9, 20, nil, nil, 15, 7]
if let tree = TreeNode(values: list) {
    // ...
}

And the task calls for a recursive implementation:

public convenience init?(values: [Int?], offset: Int = 0) {
    guard offset < values.count, let value = values[offset] else {
        return nil
    }
    self.init(value)
    self.left = TreeNode(values: values, offset: 2 * offset + 1)
    self.right = TreeNode(values: values, offset: 2 * offset + 2)
}

Making it generic

With the above changes it is now easy to replace Int by an arbitrary value type:

public class TreeNode<T> {
    public var val: T
    public var left: TreeNode?
    public var right: TreeNode?
    public init(_ val: T) {
        self.val = val
        self.left = nil
        self.right = nil
    }

    public convenience init?(values: [T?], offset: Int = 0) {
        guard offset < values.count, let value = values[offset] else {
            return nil
        }
        self.init(value)
        self.left = TreeNode(values: values, offset: 2 * offset + 1)
        self.right = TreeNode(values: values, offset: 2 * offset + 2)
    }
}


Bundling JavaScript resources for an MVC app

The best practice moved from using dotNet code for bundling, to use tools for this.

The most popular and best practised tools are:

gulp
grunt

Both are tools that work on top of nodejs, an easy to install app.

Use either of these tools to minify and bundle your js and css and reference to result file.

You can make the tooling run on build events of your project to always have it bundled

But, best practise here is to use development files in development (to  keep yourdev cycle a short as possible). And in production use the bundled and minified version.


Checking if a git repository needs to be updated

Your function has the side-effect of switching the directory to the file's path.  To be side-effect-free, you should let l:current_path = getcwd() instead.  Better yet, use the --git-dir and --work-tree options to git(1) to avoid having to cd at all.

You always query the remote named origin, but pull from `git remote`.  That inconsistent looks like a bug.

I don't see any reason to use --abbrev-ref when the result is not intended for human consumption.  Just use the full commit id.


C program to read a file containing numbers, and then print ones divisible by 3 to another file

The easiest way to make this more compact is to write a function to handle opening a file and just pass in the name and mode you want. Something like this:

FILE* open_file_or_exit(const char* filename, const char* mode)
{
    FILE* fileHandle = NULL;
    if((fileHandle = fopen(filename, mode)) == NULL){
        perror(filename);
        exit(EXIT_FAILURE);
    }
    return fileHandle;
}

Your main() then becomes:

int main(void){
    FILE *in_file = open_file_or_exit("total", "r");
    FILE *out_file_divis = open_file_or_exit("divis", "w');
    FILE *out_file_remain = open_file_or_exit("remain", "w");
    // ... rest of main ...
}

Any time you find yourself repeating the same few lines of code, that's a good sign that it should go into a function.


single responsibility
your class does all things together

reading user input
printing dialogs
handle game logic

by this you violate the openClosed principle. If you want to change your code (eg. play a one of four game) you have to make a lot of changes. If you want to add handling for InputExceptions (see Scanner.nextInt()  you would find the proper place. Make Classes for each responsibility!
minor issues

magic numbers: (3)+1
hardcoded Strings (put them in a language file) - that also helps to separate concerns between dialogs and logic
redundancy (use a formatter for the text from the language files)


Don't use the obsolete syntax `...`

Use the modern syntax $(...):

today=$(date "+%Y-%m-%d")

Simplify file deletion

Instead of deleting files with -exec rm {} \;, a simpler way is using -delete:

find "$BACKUP_DIR" -type f -mtime +30 -delete

Don't use the obsolete syntax head -N

head -1 is obsolete syntax. Use head -n 1 instead.

Don't repeat yourself

On these lines, $(ls -t "$BACKUP_DIR" | head -1) is repeated:

last_backup=$(ls -t "$BACKUP_DIR" | head -1)
if [ -n "$last_backup" ] && diff "$BACKUP_FILE" "$BACKUP_DIR/$(ls -t "$BACKUP_DIR" | head -1)" >/dev/null

The second use should be replaced with $last_backup.

Compare files using cmp

Instead of diff, it's more efficient to compare files using cmp:

if [ -n "$last_backup" ] && cmp -s "$BACKUP_FILE" "$BACKUP_DIR/$last_backup"

Avoid empty statements

Instead of the empty then clause of the final condition,
it's better to invert it (using DeMorgan's law):

if [ ! "$last_backup" ] || ! cmp -s "$BACKUP_FILE" "$BACKUP_DIR/$last_backup"
then
        cp "$BACKUP_FILE" "$BACKUP_DIR/$today.sqlite3"
fi

Delay operations until really needed

The today variable is only used once at the end,
when certain conditions are fulfilled.
It would be better to create it right before it's needed.


Testing
When @200_success asked if you had tested the code you seemed puzzled and pointed out that you had included two tests.  Unfortunately, writing things out to the screen and sight checking the results would not be considered good unit testing and for a reviewer they are not very useful as all we can tell is that some output was displayed. There is nothing to indicate what the expected results were or if they were achieved.

Also, two unit tests which pass is a limited subset to say that it is working.

What happens with an empty input?
What happens if they are all negative?
What happens if we have two sub-arrays which both have the same maximum value?

to a degree this is a gap in the requirements, the original Kadane only cares about the max value not the start and end.

Should we return start = 0 and end = 0 if there are no elements in the input or if all are negative. The result (0) is correct but it seems to indicate an array of length starting at 0, ending at 0.

Bottom line: Testing a function like this is a great place to use an automated unit testing framework. It may seem like doubling the code to be written but by the time one has run the code, read and checked the answers and repeated umpteen times for each tweak to the code to deal with the next thing we hadn't thought of, it does save time and gives a nice warm fuzzy feeling that we can see that it works and if any changes break it.

API
We do not use the List functionality anywhere in the function but insist that the user passes in a List.  I would push for changing the interface to IEnumerable<int>.


Your code is mostly all right, especially given it's your first code attempt.

I would say there is only on critical flaw. A post or a category is not a database connection. Hence it should be never extended from it. It would be like if you extend a human from a car simply because a human is going to ride a car. A car is a service used by a human, that needs to be injected into a human object.

Besides, the way your code is written, it will create a new connection to the database in the  every class instance. Which will result in the "Too many connections"  error.

To sum it up:

a database connection has to be made only once. and then passed as a parameter to all your classes that need it.
your dbh class is rather useless. it does't add anything to original PDO. so you can get rid of it and simply create a plain PHP file with connection code and include it in your scripts
then you have to rewrite your data classes adding a constructor, providing either vanilla PDO or your own database connection class' instance as a parameter

something like this

class categoriesData {
    protected $conn;
    public function __construct($conn) {
        $this->conn = $conn;
    }
    ...

and then use it like this

require_once 'pdo.php';
$post = new PostsData($pdo);
$posts = $post->getPosts();

foreach ($posts as $post) {
    echo $post->post_title . '<br>';
}


This can be done by hand in constant time using a bit of math. Just break the board up into two regions to place the first queen in:

The queen is in a corner/edge. For each corner, this eliminates the n-1 squares on the same row, column, and one or two diagonals, plus one for the one the queen is on. There are 4*(n-1) edge pieces, so there are 4*(n-1)*(n^2-(3(n-1)+1)) possibilities.
The queen is in the middle, not on an edge. Each of the (n-2)^2 positions that the queen can be in eliminates 4*(n-1)+1 squares (row, column, two diagonals, and the one square for the queen), for a total of (n-2)^2*(n^2-4*(n-1)+1).

Add these two and you should have your answer (assuming I didn't make any math mistakes).


One problem I see is that returning None from your modified get() method conflicts with the normal case of a valueless option (from the bottom of the module docs for ConfigParser):

>>> import ConfigParser
>>> import io

>>> sample_config = """
... [mysqld]
... user = mysql
... pid-file = /var/run/mysqld/mysqld.pid
... skip-external-locking
... old_passwords = 1
... skip-bdb
... skip-innodb
... """
>>> config = ConfigParser.RawConfigParser(allow_no_value=True)
>>> config.readfp(io.BytesIO(sample_config))

>>> # Settings with values are treated as before:
>>> config.get("mysqld", "user")
'mysql'

>>> # Settings without values provide None:
>>> config.get("mysqld", "skip-bdb")

>>> # Settings which aren't specified still raise an error:
>>> config.get("mysqld", "does-not-exist")
Traceback (most recent call last):
  ...
ConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'

Note the second-to-last example commented as "Settings without values provide None:"  Of course this isn't an issue if you intend to exclude this sort of option.  Other than that, I like the auto-section feature.

Though, I'd lean towards adding to the interface rather than masking and changing the behavior, so instead of replacing get/set, add safe_ versions:

def safe_set(self, section, option, value):
    if self.has_section(section):
        self.set(section, option, str(value))
    else:
        self.add_section(section)
        self.set(section, option, str(value))

def safe_get(self, section, option):
    if self.has_option(section, option):
        return self.get(section, option)
    else:
        return None

This would make it more flexible as code would still have access to ConfigParser's normal interface and the option of using the "safe" calls which don't throw exceptions.


I would use set to do the checks, and you can build the columns using some zip magic:

def check_sudoku(sudlist) :
    numbers = set(range(1, len(sudlist) + 1))
    if (any(set(row) != numbers for row in sudlist) or
        any(set(col) != numbers for col in zip(*sudlist))) :
        return False
    return True

I have tested it with the following samples:

a = [[1, 2, 3, 4, 5],
     [2, 3, 5, 1, 4],
     [3, 5, 4, 2, 1],
     [4, 1, 2, 5, 3],
     [5, 4, 1, 3, 2]] # latin square

b = [[1, 2, 3, 4, 5],
     [2, 3, 5, 1, 4],
     [3, 5, 4, 2, 1],
     [4, 1, 2, 5, 3],
     [3, 4, 1, 5, 2]] # 1st and 4th elements of last row interchanged

c = [[1, 2, 3, 4, 5],
     [2, 4, 5, 1, 4],
     [3, 5, 4, 2, 1],
     [4, 1, 2, 5, 3],
     [5, 3, 1, 3, 2]] #1st and 5th elements of second column intechanged

>>> check_sudoku(a)
True
>>> check_sudoku(b)
False
>>> check_sudoku(c)
False


How to avoid mounting SQL by concatenating strings?

Yeah, that does feel kinda wrong. But OR queries in Rails are tricky.

There are two things here: One is creating the query, the other is parsing the params.

I'd probably start1 by preparing/parsing the params so building the query is cleaner. I'd add a method - or several - to the controller, rather than the model, to do this. Both model and controller are involved in this, but I'd rather not pass params to the model. Things like checking the string value of the telecommute param seems like a job for the controller, whereas the model's search method should only have to deal with a boolean. For instance, you might want to call Job.search from code, where it'd be silly to use string values.

There's some cleanup you can do here too. For instance, I'd strongly consider adding constants or methods for the work_types array and the location keys.

I'd also be more consistent; in one place you use %w(...) to make an array of (string) keys, and in another you use [...] to make an array of (symbol) keys.

Here's an example, if you were to just use one method:

def search_params
  search_terms = {}

  # put the "AND" terms in the hash
  search_terms[:telecommute] = params['telecommute'] == 'true'

  Job.LOCATION_KEYS.each_with_object(search_terms) do |key, memo|
    memo[key] = params[key] if key.present?
  end

  # put the "OR" terms in a nested hash
  Job.WORK_TYPES.each_with_object(search_terms) do |key, memo|
    if params[key].present?
      memo[:work_types] ||= {}
      memo[:work_types][key] = true
    end
  end

  search_terms
end

It ain't pretty, but at least it's all in one place.

As for the searching itself, you can use regular ActiveRecord's query interface without descending to Arel:

def self.search(hash = {})
  # we'll be modifying the hash, so work on a dup
  # (you'll first want to check if it's empty, though!)
  terms = hash.dup

  # grab the work types
  work_types = terms.delete(:work_types)

  # add the AND clauses
  query = self.where(terms)

  # add the OR clauses (if any)
  if work_types
    subquery = self.where(work_types).where_values.inject(:or) # magic!
    query = query.where(subquery)
  end

  query
end

I get this:

Job.search(telecommute: true, country: "US", work_types: { full_time: true, freelance: true }).to_sql
# => "SELECT "jobs".* FROM "jobs"  WHERE "jobs"."telecommute" = 't' AND "jobs"."country" = 'us' AND (("jobs"."full_time" = 't' OR "jobs"."freelance" = 't'))"

1 Edit: Actually, that's not where I'd start if I were writing this from scratch. It is however where I started my rewrite, but that's because it was already there. Otherwise, I'd start by defining the search method as I'd want it to look and work - without worrying about the params -, and then worry about how to make the params fit.


Compare hostnames and leases between CSV and DHCP info

Piping the DHCP calls through foreach-object instead and then comparing at the end, cut the time down from 3min to 1min. Everything I have read made it seem like foreach was faster. Having DHCP being processed down the pipe with foreach-object instead of several iterations with foreach makes foreach-objects more efficient.
$servers = Get-DHCPServerInDC
$hashtable = @{}

# scopes into the leases to go into the PsCustomObject to be matched later
$leases = $servers | ForEach-Object {
    $server = $_.dnsname
    Get-DHCPServerv4Scope -computerName $server  #get scopes on DHCP serves

    } | ForEach-Object {
    $scope = $_
    $_ | Get-DHCPServerV4Lease -ComputerName $server | #get leases in all the scopes

     ForEach-Object {
        [pscustomobject]@{ # Make object to match later
        ScopeName = $scope.name #want name of scope only
        HostName  = $_.hostname #want hostname of leases
        }
    }
}

$assets = (Import-CSV c:\script\Asset_List.csv).asset #pull asset list

$assets | ForEach-Object { $asset = $_ #Go through hostnames finding matching lease

    $leases | Where-Object { #check leases
        $_.HostName -like "${asset}*" #find hostname
    } | ForEach-Object {
        $hashtable[$asset] = $_.ScopeName #store matches
    }
}
```


Surely this is a trick question? The formulas only apply once the system has been running long enough that its behaviour approximates the stationary distribution. But the question explicitly says that A has "recently opened" and that B has "launched" its service. This suggests that the restaurants may not have been running long enough to approximate the stationary distribution, and so we may not be able to deduce anything about the probability of particular states.

Alternatively, the question is poorly phrased. Nonetheless, I would expect a solution to mention the assumption that the system has been running long enough for the formulas to be (approximately) valid.
Moving on, there's a second problem with the interpretation of the question. When it asks about "the queue", are we to include the customers currently being served (if any), or not?

In the docstring you write "n: amount of customers in the queue" which suggests that your interpretation is that the customers being served are in the queue.

But then you compute the answer to "what is the probability that the queue will be empty?" by adding \$P_0 + P_1 + P_2\$, which suggests that your interpretation is  that the customers being served are not in the queue.

I would expect you to make this decision one way and stick to it.
In the formulas, \$λ\$ must be the arrival rate, not (as claimed in the post) the arrival time.

This is clear from a simple dimensional analysis — if \$λ\$ were the arrival time then it would have dimensions of time, and so could not be added to the service rate \$μ\$ which has dimensions of time\$^{-1}\$.

Hence, in the code, the variable should be named arrival_rate, not arrival_time.
The docstring says, "mean arrival time per hour", but this is meaningless.
In fact, writing "per hour" at all is superfluous since the computation doesn't depend on the units. It would work just as well if the rates were "per minute", or "per day", or whatever, so long as they were consistent.
The interface to n_state_probability has a special case: "To calculate the probability that the queue is empty, let n = 2." The trouble with this is that now you can't use the function to compute \$P_2\$.

The Zen of Python says, "Special cases aren't special enough to break the rules". So I would remove the special case and let the caller compute \$P_0 + P_1 + P_2\$ by calling the function three times and adding the results.
The computation of \$P_n\$ involves exponentiating twice:

(1 / 2 ** (n - 1)) * ((arrival_time / service_rate) ** n) * idle

A small transformation to the equation means that you would only have to exponentiate once:

2 * ((arrival_time / (2 * service_rate)) ** n) * idle

For ease of checking the code against the formulas, I would suggest using the same names.

Revised code:

# -*- coding: utf-8 -*-

def n_state_probability(arrival_rate, service_rate, n):
    """Return the probability that an M/M/2 queue is in state n, assuming
    that the system has been running long enough that it is in the
    stationary distribution.

    Arguments:
        arrival_rate: mean arrival rate
        service_rate: mean service rate
        n: number of customers in the system

    """
    λ, μ = arrival_rate, service_rate
    assert 0 <= λ < 2 * μ # otherwise there is no stationary distribution
    P0 = (2 * μ - λ) / (2 * μ + λ)
    if n == 0:
        return P0
    else:
        return P0 * 2 * (λ / (2 * μ)) ** n

And then the answers are:

>>> n_state_probability(20, 29, 4)
0.01377612256456733
>>> sum(n_state_probability(19, 17, n) for n in range(3))
0.7760984526996149


Using Cache::remember for banners and stores

Could I use two Cache::remembers in the same method?

Of course. Using Cache::remember or not should not affect the decision on whether or not to use Cache::remember again for something else - the decision should be: do I want this data to be cached?

Could I join these two Cache::remembers (I need change the first param)?

You could but it is a bad idea.

Consider this contrived example:

$userId = $this->Auth->user('id');
$everything = Cache::remember('everything.' . $userId, function() use ($userId) {
    $allStuff = $this->Stuff->find('all');
    $myStuff = $this->Stuff->find('all')->where(['user_id' => $userId]);
    return compact('allStuff', 'myStuff');
});
...

And compare to this:

$allStuff = Cache::remember('allStuff', function()) {
    return $this->Stuff->find('all');
});

$userId = $this->Auth->user('id');
$myStuff = Cache::remember('mystuff.' . $userId, function() use ($userId) {
    return $this->Stuff->find('all')->where(['user_id' => $userId]);
});
...

In the first example, the same cache key is used for two purposes; One is to cache getting some data which applies to all users, and the second is to get some data that is one-user specific. There are a number of (potentially dire) consequences do doing that, most obviously:

There is one copy of "allstuff" in the cache store per user
The Cached data which is not user-specific cannot be reused

Attempting to bundle cached data together, unless it actually belongs together (e.g. total number of votes, total number of up votes, total number of down votes) is at best inefficient and at worst results in cache collisions, cache churn or similar.

The right way to manage cached data is atomically and independently; This does not mean it'll never be the case that two cache calls cannot be combined.

Is it possible load model outer Cache::remember

I'm not sure what this question means, code outside a cache call should not assuming the code in a cache call will run and vice versa. Also be aware that using $this inside a cache callback ties the code to the class where the callback is written.

Complete example

It is not clear why there are cache calls around the store information, it was suggested to wrap the banner information in a cache call in a previous question because the full/small banner information would be the same for all requests, for all users.

If the store information in the question should be cached, the user id should be in the cache key and should expect it as a parameter to the Cache::remember.

public function favoriteStores()
{
    $userId = $this->Auth->user('id');
    $username = $this->Auth->user('username');

    list($fullBanners, $smallBanners,) = Cache::remember(
        'banners', function(){
        $this->loadModel('Banners');
        $fullBanners = $this->Banners->full();
        $smallBanners = $this->Banners->small();
        return [$fullBanners, $smallBanners];
    });

    $myStores = Cache::remember(
        'stores.' . $userId, function() use ($userId) {
        $stores = $this->Stores->myStores($userId);
        $favoriteStores = $this->Stores->favoriteStores();
        return [$stores, $favoriteStores];
    });

    $this->set(compact('fullBanners', 'smallBanners', 'userId', 'username',
        'stores', 'favoriteStores'));
}

If favoriteStores is not user-specific it does not belong in that cache call. Without knowing the meaning/intended use of this data I would suggest to remove caching from the stores/favotite stores data:

public function favoriteStores()
{
    $userId = $this->Auth->user('id');
    $username = $this->Auth->user('username');

    list($fullBanners, $smallBanners,) = Cache::remember(
        'banners', function(){
        $this->loadModel('Banners');
        $fullBanners = $this->Banners->full();
        $smallBanners = $this->Banners->small();
        return [$fullBanners, $smallBanners];
    });

    // Don't needlessly cache this data
    $stores = $this->Stores->myStores($userId);
    $favoriteStores = $this->Stores->favoriteStores();

    $this->set(compact('fullBanners', 'smallBanners', 'userId', 'username',
        'stores', 'favoriteStores'));
}

Warning

If in doubt do not cache anything.

This may seem like a contradiction but if you're considering caching data "just because" without any real need or reason that's likely to end badly. Use caching to improve performance and address specific concerns/problems - when it's needed.


Stylistically, using itertools.count() rather than implementing your own counter would be a bit cleaner.

I also prefer using the any() over a generator rather than an explicit for loop with a break and else. I think it's easier to follow.

Algorithmically, the sieve has a big advantage because it uses the previously calculated primes to make checking the next prime faster. You don't need to check every number for divisions, just the primes. You could do something like:

past_primes = []
for x in itertools.count(2):
    if not any(x % prime == 0 for prime in past_primes):
        past_primes.append(x)
        yield x

Performing the division will still be more expensive than what the sieve has to do. You could implement the entire sieve algorithm in a generator. But I'm not sure what purpose that would serve.

Generally, generators work nicely when you don't have to maintain a lot of state for each value generated. But that's not the case for primes.


This gets to be a sticky point.  There are those who will argue fervently that an extension method should never work on a null reference, and there are those who are fine with that.

Personally, I don't mind extension methods on null if the name is a clear indicator that null is a possibility (like IsNullOrEmpty) but as I said, that's my opinion and may not match others.

Don't worry about the performance, method calls are not a serious impact and check methods like this eliminate some of the readability concerns over compound expressions when maintaining the code.  After all, that's what string.IsNullOrEmpty() does, but it does it through a static method instead of an extension method.

So the only concern, really, you may get push back that these are extension methods as opposed to ordinary static methods, but you'll get differing opinions on whether calling an extension method on null is bad/okay.

One could argue Microsoft disallows LINQ extension methods on null sequences, but then again Microsoft also doesn't disallow extension method calls on a null source in general.

So, the choice is yours, I don't have an issue with them since the names clearly indicate null is an accepted possibility, but I can see both sides of the argument.

On a side note, I'd keep your naming consistent:

NotNull -> IsNotNull
NotNullAndNotEmpty -> IsNotNullAndNotEmpty


That is a great start.  It's almost perfect logically.

First thing that caught my eye however is the lack of indentation.  It could just be that something got lost in the transition between your code and your post here, I don't know.  But you should indent whenever starting a new block.  You indented the if bodies, that's good, but you missed the function body of main(), the while block.  Had you done this, you would have been able to identify the following problem in your code.

The body of the while loop consists only of the first if statement that is counting newlines.  You are effectively counting only newlines and not counting the blanks or tabs.  This is how you have your code written but let's include some correct indentation:

while((c = getchar()) != EOF)
    if (c == '\n')
        ++newline;
if (c == ' ')
    ++blank;
if (c == '\t')
    ++tab;

Do you see the problem now?

There's a couple of ways to fix this but let me start with what you should have done always.  If you ever have a block that would span multiple lines, you should always wrap the block in curly braces.  That way there's no confusion what goes where.  It's more forgivable to not include them if it's just a single line (just like you have in your individual if statements) but all three of them belongs to the while body so they should be in braces.

The other thing to about this code is that those three if statements are mutually exclusive.  Only one of them could ever be hit for a given character, c.  So you shouldn't have created a series of if statements like you did here, but instead a set of if/else blocks.  That way the following if statements don't get executed if the preceding one was satisfied.
This could have fixed the logical error for the while loop too but it's still important to include the braces regardless so there's no confusion.

That block should have looked more like this:

while((c = getchar()) != EOF)
{
    if (c == '\n')
        ++newline;
    else if (c == ' ')
        ++blank;
    else if (c == '\t')
        ++tab;
}

Now there's some minor style issues in your code.  You can follow these if you wish, it's just personal preference.  But it could help other people read your code easier with little chance for confusion.

Your variable declarations should go on separate lines and the initializations of the variable should occur in the declaration.  I'd also pluralize the variables since they are used as counters.  In your head, if you read out the values of the variables what makes more sense?  "I have 5 tab," or "I have 5 tabs?  The comment was off a bit, we're not initializing c here, just declaring it.

Do this:

/* initializes blanks, tabs, and newlines and sets them all to 0 */
/* declares c to hold the read-in characters */
int c;
int blanks = 0;
int tabs = 0;
int newlines = 0;

And to a lesser degree, a call to printf() with parameters should be printed a single line at a time.  The newline characters sprinkled in the format string makes it less clear how many lines this will print out.

Do this:

printf("Blanks: %d\n", blanks);
printf("Tabs: %d\n", tabs);
printf("Lines: %d\n", newlines);

So applying all of the above, your code would look like this:

#include <stdio.h>

 /* count blanks, tabs and newlines */

int main(void)
{
    /* initializes blanks, tabs, and newlines and sets them all to 0 */
    /* declares c to hold the read-in characters */
    int c;
    int blanks = 0;
    int tabs = 0;
    int newlines = 0;

    while((c = getchar()) != EOF)
    {
        if (c =='\n')
            ++newlines;
        else if (c == ' ')
            ++blanks;
        else if (c == '\t')
            ++tabs;
    }

    printf("Blanks: %d\n", blanks);
    printf("Tabs: %d\n", tabs);
    printf("Lines: %d\n", newlines);

    return 0;
}


BouncyCastle Rijndael 256 Implementation

It's good that you used a more interesting test string instead of "value" and that in testEncryptRijndael you replaced assertNotNull with a more strict assertEquals.

Since your tests are different from the originals, it would be better to rename them to testEncryptRijndaelWithSalt and testDecryptRijndaelWithSalt, respectively. And keep the originals too.

In both the original tests and yours I don't see the point of the logging and printing statements. I think you can drop that. They do no harm, but they might invite the bad habit of reading test outputs instead of focusing on adding proper assertions.

There's a lot of duplication in the encryption and decryption cases. Perhaps you could move that logic to a common private helper method. That can reduce possible typing errors.

I don't see the point of this if block:

 if (outputLength != output.length) {
     // ...
 }

The thing is, in a unit test everything should be predictable: you should already know at this point the outcome of that condition. If outputLength should be equal to output.length, then drop the if but keep the block of code. Otherwise delete the whole thing. You can add an assertion for the condition as a sanity check.


Loading a combobox with an enum and binding to it

Naming
HemEnum, or any enum name that ends with the word Enum, is a bad name for an enum. Enum types should not contain the word "enum" in their names.
Similarly, HemEnum values should not contain "Hem" in their names either. Your HemEnum should therefore read something like this:
public enum HemType
{
    None = -1,
    Sewn = 0,
    Weld = 1,
    DoubleFold = 2
}

myObject is a bad name for a class - should be MyObject. Kidding (although not really - types should be named following a PascalCasing convention). Anything that ends with "Object" should be banned from being a class name. Note that myObject doesn't compile as provided. (where's this.HemType?)
The pseudo-Hungarian notation is ok in winforms for naming controls (i.e. the "cbo" prefix for ComboBoxes, "txt" for TextBoxes, etc.) - had you been using current technology (WPF) I would have strongly advised against such naming though.
Nitpicks
You seem to make static anything that can be made static. Don't. Just because a method doesn't use instance members now doesn't mean it never will, and changing a public static void method to be public void, is a breaking change.
vHemEnum doesn't seem to be a type defined anywhere. Typo?
I'll assume the out-of-whack indentation is a Copy+Paste glitch.
Binding?
You say you want databinding, and yet you're doing this:
foreach (var value in values)
{
    var s = GetHemTypeDescription((HemEnum)value.ID );
    cbo.Items.Add(s);
}

Create a type that exposes DisplayValue and EnumValue properties, and use @DanLyons' or @JesseCSlicer's answer to bind your combobox items.
Captions
A more extensible way (vs. attributes) of providing captions for your enums, would be to use a resource file (.resx) - call the strings per the enum's names, and then retrieve the caption from the resource strings:
var description = resx.ResourceManager.GetString(hemType.ToString());

Bottom line, I've seen worse WinForms code (and WPF for that matter), but it could be improved.


POSIX shell function to "dump" all given arguments

printf '%b' "dump_arguments()\\n----------------\\n$# arguments are being inspected"

We could make that easier to read by making each line a separate argument, and ending the line properly (rather than requiring a separate command):
punct=.
${1+false} true || punct=:
printf '%s\n'                                       \
       'dump_arguments()'                           \
       '----------------'                           \
       "$# arguments are being inspected$punct"

It seems odd to use %s here:

    printf '%s' "[$i]: '$1'"

Why not use the format string more clearly?  And this allows us to modify to use %q if we have a suitable printf:
    printf "[%d]: '%s'" "$i" "$1"

Perhaps even combine the type into a single print:
    type=
    [ -z "$1" ] && type=' (empty)'
    [ "$1" -eq "$1" ] 2>/dev/null && type=' (integer)'
    printf "[%d]: '%s'%s\n" "$i" "$1" "$type"

Is it intentional that strings such as ' 5' (with leading and/or trailing spaces) are counted as integers?

    shift 1

Normally written simply as
    shift

That said, I think it's more natural to iterate over arguments using a for loop instead.

} >&2

That's surprising, as the output isn't an error, but expected when calling the function.  It should be up to the caller to choose where stream 1 goes.

Modified code
#!/bin/sh

dump_arguments()
# string function - prints arguments (position and content)
# indicates empty arguments and integer numbers
{
    punct=${1+:}
    printf '%s\n'                                               \
           'dump_arguments()'                                   \
           '----------------'                                   \
           "$# arguments are being inspected${punct:-.}"
    i=1
    for v
    do
        if [ -z "$v" ]
        then type=' (empty)'
        elif [ "$v" -eq "$v" ] 2>/dev/null
        then type=' (integer)'
        else type=
        fi
        printf "[%d]: '%s'%s\n" \
               "$i"   "$v" "$type"
        i=$((i+1))
    done
}


Loading and Refreshing DataGrid in WinForms using C# .Net Framework

Single responsibility

Move the query logic to different class, let's call it DAL for example. In this implementation you are returning DataTable.  Returning a list of some class instead will make sure changes in the DB query/ schema will not affect the GUI but only the DAL class.

LINQ

You can write the sql query using linq and then if you have syntax errors they will be cache during completion

Grid

I wonder why  you set the columns headers multiple times?

Think about this scenario: when the form loads, If the query return 0 results or there is a connection problem, how the grid will look like?


Expand spreadsheet ranges to lists of cells in Scala

I couldn't get your code to compile until I took out the sorted. The output was still good so I don't know what purpose it was supposed to serve.

There's no point in casting validAlphabets to a Seq[Char].  As a Range[Char] the contains() method still works. Better still would be to cast it to a Set[Char]. Then the syntax is more concise and the lookup is faster.

val rows = corners filter validAlphabets
val cols = corners filter (!validAlphabets(_))

Due to the use of .head and .last, this solution won't handle rows past 9. There are also a number of input errors that it won't catch. These can be addressed if you use a Regex to parse the input.

def cells(range: String): Seq[String] = {
  val format = "([A-Z])(\\d+):([A-Z])(\\d+)".r
  val format(colStart, rowStart, colEnd, rowEnd) = range

  for {
    c <- colStart.head to colEnd.head    //from String to Char
    r <- rowStart.toInt to rowEnd.toInt  //from String to Int
  } yield s"$c:$r"  //back to String
}

This will throw if the input string doesn't match the expected format. If you'd prefer it print the error and return nothing (an empty Seq[String]) then you can use a match statement instead, with a default case _ => for the format failure.

Notice that I use a for comprehension here. Whenever you see a map() inside a flatMap() that's a flag indicating that a for might do the same thing in a clearer/cleaner manner.


You first need to select the bits in the flag you want to test by ANDing them with a mask containing all the bits.

This will zero all the bits that aren't being tested.

You then just need to check the value of the bits you want so the masks and values are:

const UINT EndMask = NOSIZE | NOOWNERZORDER | NOZORDER | NOACTIVATE;
const UINT MaxRestoreMask = FRAMECHANGED | NOACTIVATE | NOCOPYBITS | SHOWWINDOW;
const UINT EndValue = NOOWNERZORDER | NOZORDER;
const UINT MaxRestoreValue = FRAMECHANGED;

The test then becomes:

if ((flags & EndMask) == EndValue || (flags & MaxRestoreMask) == MaxRestoreValue)


You should use the directive "use strict" that will place the JavaScript context into strict mode. This will throw errors for some common bad practices.

Always declare variables as const, var, or let. If you are in strict mode you will get an error if you don't.

Don't use alerts or prompts as there is no way to know if they are actually displayed (clients can turn them off) and they are very annoying.

The key event properties KeyboardEvent.keyCode and KeyboardEvent.charCode have been depreciated and you should not use them. Use KeyboardEvent.code or KeyboardEvent.key instead

Rather than filter the input via the keybpoard events, listen to the input's keyup and change events, removing bad characters automatically. Use a CSS rule to unhide a warning and a JavaScript setTimeout to hide it again
Filtering keyboard events means you need to check many keys that are valid (left, right, backspace, delete, etc...) which is just unneeded complexity.

Don't wait for the user to click "Convert to Decimal", display the output automatically. This makes it a lot friendlier to use.

JavaScript can convert binary strings to decimal for you using parseInt. The second argument is the radix (AKA base) of the number that is being parsed.

If you are just setting text (no HTML) use the elements textContent rather than innerHTML

Rewrite
The rewrite is following the points you have set-out in your question. I have not implemented how your code differs from these points.
The rewrite uses

a RegExp to test and filter the input.
a ternary expression to create the decimal value as parseInt will return NaN for empty strings. The ternary checks if the string is empty evaluating to "" or if there is a number the ternary evaluates to the decimal value.
HTMLInputElement.focus (inherited from HTMLElement) to focus the input element when loaded.

I have modified the HTML and CSS to fit the snippet window a little better.

"use strict";
const binaryInput = document.getElementById("binaryInput");
const decimalOutput = document.getElementById("decimalOutput");
const inputWarning = document.getElementById("inputWarning");
binaryInput.addEventListener('change', update);
binaryInput.addEventListener('keyup', update);
binaryInput.focus();

const WARNING_TIME = 2000; // in ms
var warningTimer;
function hidWarning() {
   inputWarning.classList.add("hideWarning");
}
function showWarning() {
    clearTimeout(warningTimer);
    warningTimer = setTimeout(hidWarning, WARNING_TIME);
    inputWarning.classList.remove("hideWarning");
}
function update() {
    var value = binaryInput.value;
    if (/[^01]/g.test(value)){
        binaryInput.value = value = value.replace(/[^01]/g, "");
        showWarning();
    }
    decimalOutput.textContent = value === "" ? "" : parseInt(value, 2);
}
body {
    background: #2e2e2e;
    color: #fff;
    font-family: Heebo, sans-serif;
}
.form-body {
    display: flex;
    flex-direction: column;
    text-align: center;
}
input {
    margin: 0 auto;
    width: 100%;
    max-width: 300px;
    border: 0.125rem solid rgba(255,255,255,0.25);
    background: rgba(255,255,255,0.05);
    color: #fff;
    font-size: 2rem;
    text-align: center;
    font-weight: 300;
}

.inputWarning { color: #F88 }
.hideWarning { display: none }

Binary to Decimal Calculator

  Enter a binary value [Only valid digits 0 and 1 permitted]
  <input id="binaryInput" type="text" size="8" maxlength="8">

Decimal Value:


Some comments from this question still apply here.

You do not respect PEP 8 and you should try to split your code into smaller chunks.

Let's change things little by little :

Data over code

Copied from my other answer

Sometimes, you have to write a lot of code because "Hey, I have a lot of logic to write, I have to write code, that's the point of programming" but the point is more to keep things simple and to use the right tool (which is not always code) for the right thing.

Here you are comparing strings to get the relevant hint for an answer. It would be much clearer to store the hint are the words together in a structure. At the moment, I've decided to store this in a list of tuple (a dictionnary would also have done the trick).

WORDS = (
    ("python", "Its a snake..."),
    ("jumble", "Rhymes with rumble"),
    ("easy", "This one is so simple!"),
    ("difficult", "This is a hard one... its very ________________"),
    ("answer", "You cant find it? the _________ is ___________"),
    ("xylophone", "It is a toy..."),
)
...
    # pick one word randomly from the sequence
    word, word_hint = random.choice(WORDS)
...
        print(word_hint)
        print("Thanks for takeing the hint, idiot...")

Extracting logic in a function

The logic to create a jumble version looks like it could and should be put in a function on its own.

Also we can reuse already existing functions : shuffle.

Now, the whole code is much simpler (also, you don't need word AND correct) :

def get_jumble_word(word):
    l = list(word)
    random.shuffle(l)
    return ''.join(l)

...
    word, word_hint = random.choice(WORDS)
    print("The jumble is:", get_jumble_word(word))

A bif of logic

You have :

while guess != word and guess != "":
    # code with no break
if guess == word:
    foo()
elif guess == "":
    bar()

After the loop, we know that condition guess != word and guess != "" is not true anymore (because we would have stayed in the loop otherwise). In order for this condition not to be true, we must have : guess == word or guess == "".

Thus, if condition guess == word in the if branch is not true, we always go in the guess == "" part.

You can rewrite this :

if guess == word:
    foo()
else:
    assert guess == ""
    bar()

Do not repeat yourself

Do not repeat yourself.

Do not repeat yourself.

You have the same last line in both branches of :

if guess == word:
    print("That's it!  You guessed it!\n")
    print("Your score is: " + str(points))
    play = input("Do you want to play again? (yes or no)")
else:
    print("You failed...")
    play = input("Do you want to play again? (yes or no)")

It probably should be :

if guess == word:
    print("That's it!  You guessed it!\n")
    print("Your score is: " + str(points))
else:
    print("You failed...")
play = input("Do you want to play again? (yes or no)")

More functions

You can define a function to handle getting the yes value from the user, one to handle a game, one to handle the interface (asking yes/no between games) :

def get_input_in_list(prompt, values):
    while True:
        s = input(prompt + '(Your choices are : ' + ', '.join(values) + ')')
        if s in values:
            return s

def game():
    # pick one word randomly from the sequence
    word, word_hint = random.choice(WORDS)
    print("The jumble is:", get_jumble_word(word))
    points = 100
    guess = input("\nYour guess: ")
    while guess != word and guess != "":
        print("Sorry, that's not it.")
        hint = input("Do you need a hint?")
        if hint == "yes":
            points = int(points) - 10
            print(word_hint)
            print("Thanks for takeing the hint, idiot...")
        guess = input("Your guess: ")

    if guess == word:
        print("That's it!  You guessed it!\n")
        print("Your score is: " + str(points))
    else:
        print("You failed...")

def main():
    while input("Do you want to play? (yes or no)") == "yes":
        game()

if __name__ == "__main__":
    main()

Also, I took this chance to add an if main guard.


Async tcp socket client: send multiple requests with one connection

I want to know is it possible to use one connection to for multiple requests(i.e move that socket and connection to another method)?

In principle, yes. The easiest way would be to not create a socket in this method, but leave it up to the caller to create a socket, and pass a reference to it to AsyncClient::ReqSum(), so that the socket can be reused for multiple requests.
However, as you mentioned this doesn't work, and that is because you rely on the server to close the connection right after sending the response to a single request:
boost::asio::streambuf receiveBuffer;
boost::asio::read(_socket, receiveBuffer, boost::asio::transfer_all(), err);

The read() command here doesn't know how large the response is, but you told it to transfer all data sent by the server. The only way to signal the end of all data is for the server to close the connection. If the server would support multiple requests on a connection, then you need some way to deliniate responses. And in that case, you will have to use a function like boost::asio::read_until() to read data up to a certain point.
Don't throw strings
First of all, constructing a string using std::stringstream is quite expensive. But the main issue is that you are throwing a plain std::string. The problem is that any error handling code now has no idea what kind of error happened, unless it parses that string. That will also be inefficient.
You should instead throw a type that inherits from std::exception. In this case, either throw a std::runtime_error, or if you wish some custom type that inherits from that.
Avoid using std::endl
Prefer using "\n" instead of std::endl; the latter is equivalent to the former, but also forces a flush of the output stream, which is usually not necessary and might be bad for performance.


You can use np.cumsum and np.minimum.accumulate (which I found from this post).

Another way to look at what you want is you want the cumsum.

If the value goes below zero then you want to subtract a value to get it to zero, this value is itself. This means that you just need a running minimum. This is as you've subtracted the value from an earlier value so the effect propagates in your version but not in np.cumsum.

You also want to start this minumum from 0.

def pos_diff_cum_sum(flow_in, flow_out):
    delta = np.cumsum(flow_in - flow_out)
    return delta - np.minimum.accumulate(np.append([0], delta))[1:]

For reference below.

def fn(in_, out):
    delta = np.cumsum(np.array(in_) - np.array(out))
    print(delta)
    output = delta - np.minimum.accumulate(np.append([0], delta))[1:]
    print(np.minimum.accumulate(np.append([0], delta))[1:])
    print(output)

If you have an input that only increases then you can just use use np.cumsum:

>>> fn([1, 1, 1, 1, 1], [0, 0, 0, 0, 0])
[1 2 3 4 5]
[0 0 0 0 0]
[1 2 3 4 5]

However if the number goes negative you must subtract all values after it goes negative by that value. This is as the single -= affects the rest of the input in the OP:

>>> fn([1, 0, 0, 0, 0], [0, 1, 1, 0, 0])
[ 1  0 -1 -1 -1]
[ 0  0 -1 -1 -1]
[1 0 0 0 0]

This means you must subtract them even if the value becomes positive again:

>>> fn([1, 0, 0, 1, 1], [0, 1, 1, 0, 0])
[ 1  0 -1  0  1]
[ 0  0 -1 -1 -1]
[1 0 0 1 2]

If more numbers go negative then you have to decrease by these amounts too:

>>> fn([1, 0, 0, 0, 0], [0, 1, 1, 1, 1])
[ 1  0 -1 -2 -3]
[ 0  0 -1 -2 -3]
[1 0 0 0 0]

This allows the value to go positive again if it needs to:

>>> fn([1, 0, 0, 0, 1], [0, 1, 1, 1, 0])
[ 1  0 -1 -2 -1]
[ 0  0 -1 -2 -2]
[1 0 0 0 1]


Looks good!

I'm a bit surprised the linter didn't catch redundant semicolons at the end of some function declarations, for example here:

  function getSize() {
    return size;
  };

I would rename all the local variables and function parameters named x to data.

In enqueue, you could inline the newNode variable,
and assign the object literal {next: head, data: data} directly to head.

It would be good to test a bit more thoroughly,
for example dequeue everything from a non-empty queue,
and performing a mix of enqueue and dequeue operations.


single array or many single argument to call a constructor with params?

I'd always use the second version, since one could use type-hinting. The array style is less transparent.

At least the array style should read like this:

$config = array(
 Class::PARAM_1_INFO =>'abc'
 Class::PARAM_1_SOMETHING =>'dfg'
);

This way, Class is the single point, where the keys get defined.


A series of yes-no questions to predict yes-no outcomes

Unfortunately, without the two csv files, we are not able to test your code... Maybe if you could show us the profiler output (see the example in ?summaryRprof) on a few iterations, it would help. What I suspect is that it will show most of the time is wasted either in the lm fit, or in the write call. Here are suggestions to improve on both as potential issues:

Alternative to lm

Since you are doing simple linear regression, i.e. regression with a single variable, there is a closed-form solution for the R-squared and it is fast to compute with R's built-ins:

RSQ1 <- function(x, y) {
   mx  <- mean(x)
   my  <- mean(y)
   mxy <- mean(x * y)
   mxx <- mean(x * x)
   myy <- mean(y * y)
  (mxy - mx * my)^2 / (mxx - mx^2) / (myy - my^2)
}

Compare this with your implementation

RSQ2 <- function(z) {
  linearMod <- lm(y ~ x, data = z)
  ModSum <- summary(linearMod)
  ModSum$r.squared
}

Here I test both functions assuming your Bin_Matrix has 1000 rows. Your mileage may differ depending on how many observations you really have, something your question does not yet provide:

n <- 1000
z <- data.frame(x = runif(n), y = runif(n))

RSQ1(z$x, z$y)
# [1] 0.0007529693
RSQ2(z)
# [1] 0.0007529693

library(microbenchmark)
microbenchmark(RSQ1(z$x, z$y), RSQ2(z))
# Unit: microseconds
#            expr      min        lq      mean    median        uq      max neval
#  RSQ1(z$x, z$y)  111.707  120.8345  146.3035  126.5945  143.2855  689.371   100
#         RSQ2(z) 2531.381 2554.2105 2883.7659 2626.9020 2966.8550 5103.368   100

Inefficient write

The way you are using write is inefficient in that every time it is called, it must open the file, move the filehandle all the way to the end, write a line, then close the file. If your R squared is improved upon very often, this could start adding up. You would gain by doing the following.

Before your for loop, open a filehandle: fh <- open("RSQ.txt")
Make write append to the filehandle: write(toString(Perm_Best, nrows= 1), file = fh)  (notice, there is no need for append = TRUE anymore)
After the for loop, close the file handle: close(fh)

Can you please give these suggestions a try and let me know if it helps? If it doesn't, maybe provide the output of the profiler? I hope it helps, good luck!

P.S.: Regarding coding style, you might find this approach for computation  Bin_num a little easier on the eye; it should not have a significant speed impact:

idx <- as.numeric(rawData[cnt, 1:8])
bm  <- Bin_Matrix[, idx]
Bin_num <- data.table(result = c(Bin_Matrix[, 15]),
                      numb   = colSums(2^(0:7) * t(bm)))


Python 2.7 text adventure map and movement

Being more familiar with appropriate data structures is going to help a lot here. I will suggest a better map structure that will make things less confusing at the end. First I want to suggest an intermediate cleanup which will let me think and talk about things more easily.

Room class: You have class for Weapon, Enemy, etc. It will help a lot to make a class to contain an element of the map. I'm going to call it Room. Maybe there's a term more appropriate for your game. Then your initialization could look something like this. (I'm leaving out the connects field for now. Hang on.)

map.append(Room(name="The Courtyard of Castle Darkspur",
                info="A description of the room"))

Turning it into a graph: Now we have a nicer way to link rooms. Without going into too much detail, a graph is a common way to represent specific connections between objects. I'm sure there's a cool graph library we could use, but this should be all we need to get us going:

start_room = Room(name="The Courtyard...."
                  # etc
                  )
castle_entry = Room(name="The castle entry")
start_room.add_connection(Direction.North, castle_entry)

And add_connection just has to look like this:

def add_connection(self, direction, room):
    self.connects[direction] = room

(direction is an Enum, by the way)

Now you can go straight to the connected room without worrying about indexing

But now what about all the local variables? This still isn't great. You're probably going to have a lot of local variables lying around, and this is mixing data and code pretty heavily. A cleaner solution would be to store the map in a .txt file. It might look something like this:

Room
Name: The Courtyard of Caslte Darkspur
Id: courtyard-darkspur
Info: Courtyard descr.
Weapons: rusty-knife-simple
connects: South, castle-entry

Room
Name: The castle entry
Id: castle-entry
Connects: North, room-entry

You would need a class or function to first parse each item individually, and then use the id fields to create all the links between nodes. Common ways to store configuration data like this are JSON (mainly) or XML.

You could also choose a hybrid of these approaches. Perhaps a class you could use in the REPL to dynamically construct a part of the map, then it saves it to your configuration file when you're done.


Read numeric data from a text file using C++

A) I don't think that you improved performance of your code in this way. In both methods you get the single numbers with ">>", which is IMHO the best way to get the numbers. So I think it does not matter much.

B) First you can improve your code by regarding the "push_back" commands. This command regularly needs to reallocate your data to fit in a specific part of the main memory. If you know your total number of lines beforehand, you can call "reserve" before the first push_back with the number of lines. Depending on the number of lines you have in total this approach might save you a lot of time. There are more opportunities, just look it up here.
Second you can use binary data instead of a textual representation. In your example the code has to read multiple chars for every single number. With binary data every data has a fixed size, independent of the decimal length. Moreover the numbers then are already in the correct representation memory wise.

C) IMHO your approach is ok.

D) That, I cannot answer. I think there is a way to use streams, if you don't already do this.


Optimization of AngularJS function to load images on the page

Personally, I would create a 4th service that returns all data in 1 go and be done with it.

Other than, I would return the array in the first block immediately. Secondly, I would probably go for object notation for something that simple:

function datacontext(common) {
    return {
        getAllTagsByHttp: function getAllTagsByHttp() {
          return common.$http.get('/api/TagApi/alltags');
        },
        getBlogPostsByHttp: function getBlogPostsByHttp() {
          return common.$http.get('/api/BlogPostApi/AllBlogPosts');
        },
        getAllUserPicByHttp:     function getAllUserPicByHttp() {
          return common.$http.get('/api/BlogPostApi/AllUserPic');
        }
    };
}

Furthemore, for this part: The problem i am having is that it takes quite a few seconds for the second function to receive the data and an complete its operation. You really should use the Chrome Developer Tools (or their Firefox counterpart) and figure out what is taking so long ? ( Latency, server side processing, or JavaScript processing ). If the problem is on the server side then it makes even more sense to have only 1 API call (that's what Netflix does)


String[] capital = {"Lisbon", "Madrid", "Paris", "Berlin", "Warsaw", "Kiev", "Moscow", "Prague", "Rome"};
String[] country = {"Portugal", "Spain", "France", "Germany", "Poland", "Ukraine", "Russia", "Czech Republic", "Italy"};

Two string arrays with members that are supposed to match by index?  Extremely difficult to maintain, as I learned from my own experience.  Use a map instead, so you can do something like:

String capital = countryCapitalMap.get(countryName);

This will help ensure there is an entry for each country/capital and make it so you only have to update things in one place.

Don't hardcode the length of the array:

int randomint = r.nextInt(9);

Use the length of the array instead, or for a map, use the size() method.

Your naming isn't always clear.  How do I know what r stands for without seeing the definition?  How did you determine to use d as your loop variable?

Just use the ordinary false keyword instead of the explicit Boolean.FALSE field here:

while (was[randomint] == Boolean.FALSE)


Highlight strings that match a search term

Rather than extract the Search input in to a different component I would suggest you keep the input and list in the same component.

This way when printing the list you can highlight the search term directly.

const HighlightableList = (props) => {
  const [searchTerm, setSearchTerm] = React.useState("");
  const regex = new RegExp(searchTerm, "gi");

  const items = props.terms.map((term, index) => (
      <div
        className="label"
        key={index}
        dangerouslySetInnerHTML={{
          __html: term.replace(regex, match => `<span class="highlight">${match}</span>`)
        }}
      />
    ));

    return (
      <>
        <input
          type="text"
          value={searchTerm}
          placeholder="Search Labels"
          onChange={event => setSearchTerm(event.target.value)}
        />
        <div className="label-container">
          {items}
        </div>
      </>
    );
}

https://codepen.io/rockingskier/pen/YzKrGNR

Side notes:

Don't make each list item a label. From MDN

  The HTML  element represents a caption for an item in a user interface.

That would suggest that each item in the list has its own user input.  In fact there is only one input (search) and that should really have a label of its own.  I'll let you implement that.

Additionally due the the "list-iness" of the data I have converted it to a ul with each item as an li.


Usually let is used to create data or functionality that is the same for each individual spec. In this example, I don't see much difference between your code and:

it 'creates fire' do
  params = { firewood: true }
  post :create, params
  expect(response.body).to eql('fire!!!')
end

If you need to pass { firewood: true } to multiple specs, then using let to define the controller params makes sense. Furthermore, a before_each is more declarative for executing behavior. Use let to mock up data, but use before_each to execute the same behavior or methods for each spec:

RSpec.describe FireController do
  describe '#create' do
    context 'when we have firewood' do
      let :params, { { firewood: true } }

      before_each do
        post :create, params
      end

      it 'creates fire' do
        expect(response.body).to eql('fire!!!')
      end

      it 'is really really on fire' do
        expect(...).to ...
      end

      it 'does something else as well' do
        expect(...).to ...
      end
    end
  end
end

This way each spec is literally reduced to a single expect.

@jtmarmon said:

  the reason I didn't run the request in before_each is because some specs need to check if a method get called. those expectations need to be set before the request is made

In this case I would either:

Just call post :create, params in each spec, or
Group those specs inside additional contexts that contain their own before_eachs setting up the method call expectations

You aren't gaining clarity, or really reducing code by encapsulating post :create, params with a let. Every time I see a let I think it is setting up data, rather than executing behavior.


Counting K-mers (words) in a sequence string

Obligatory PEP8 reference: It is recommended to use lower_case names for variables and functions. camelCase is alright if you are consistent (you seem to be using lower_case for variables and camelCase for functions).

The hardest to read part is the calling of the Parallels part. I would make a few changes there to improve readability:

The way delayed is used I would think it is a decorator and you could do:

@delayed
def iterSlice(seq, start_idx, end_idx):
    """
    Slice sequence
    """
    return seq[start_idx:end_idx]

Unfortunately this does not work, I asked a stackoverflow question why here.

You can however do this:

def iterSlice(seq, start_idx, end_idx):
    """
    Slice sequence
    """
    return seq[start_idx:end_idx]
iterSlice = delayed(iterSlice)

This seems a bit too verbose to me:

iterSlice(seq=seq, start_idx=start_idx, end_idx=end_idx)

This is just as explicit:

itereSlice(seq, start_idx, end_idx)

Parallels has an implemented contextlib so you can do:

with Parallel(n_jobs=num_cores) as parallel:
    list_of_kmers = parallel(iterSlice(seq, start_idx, end_idx)
                             for start_idx,end_idx in zip(start_indices,end_indices))

It would also allow you to reuse the pool of workers if you had en explicit loop in there, which you don't.

You can probably move the definition of list_of_kmers directly into Counter(...) to avoid generating an intermediate list.

Regarding the performance:

The actually parallelized taks you are performing is getting the slice of the string. This is not really CPU intensive, so the overhead of setting up the parallelization might ruin the benefits.

For large files you will be limited by the reading of the file itself, which will be done linearly with the file size and with one CPU.

Have you tried comparing your code to a naive implementation like this:

from collections import Counter

def count_kmers(seq, K=5):
    """Count kmers in sequence"""
    return Counter(seq[start:start+K] for start in xrange(len(seq) - K))

(In python 3.x use range instead of xrange)


Try to think about this in a more generic way, you basically have:

Select data from DB
Put that data in a CSV (will you in the future want to use other formats like XLSX, etc? If so, we should abstract this step too, but I wont do this right now)
Return that CSV file (doesn't matter to who you're returning)

So we can create a few classes from those steps

Any class that can query the DB, your app probably has a bunch of them
AbstractWriter - this class is an abstraction/interface to write anywhere, you'll need to implement it for specific formats, like Writer/Csv, Writer/Xlsx, Writer/JSON, etc.
AbstractFileReturner - this class is an abstraction/interface to return it to anyone, you'll need to implement it for specific cases, AbstractFileReturner/like Sftp, AbstractFileReturner/HttpResponse, etc.

Any time you need more File formats or Returner, you just implement the AbstractWriter or FileReturner respectively one more time.

Doing all these, you'll be using Single Responsability Principle (each class do only one thing) and Open/Closed (the abstractions/interfaces are closed for modification, but open for extension).

Real code

Ok so I came up with a little bit of code having SOLID in mind and to make it easy to add more file formats and and way outs (Sftp, Response, etc).

This is a photo of the layers I tried to create, it might make the code more understandable.

Now embrace yourself for there are coming a few classes.

I didn't test this code and doens't know much of Laravel, so there might be a few bugs, but you'll get the big picture.

First, a sample controller and model which I thought was your Line.

class SomeModel
{
    // the chunk does not go here, it will go inside who's putting the data into the csv
    public static function someQuery()
    {
        return Line::with(['invoice', 'invoice.customer', 'item'])
            ->whereHas('invoice', function ($query) {
                $query->where('is_exportable', 1);
            });
    }

    public static function lineMapping(Line $line)
    {
        return [
            'Invoice number'            => $line->invoice->id,
            'Document type'             => self::DOCUMENT_TYPE,
            'Date'                      => $line->invoice->date,
        ];
    }
}

class SomeController
{
    public function exportCsvSftpAction()
    {
        $dataCollection = SomeModel::someQuery();
        $filename       = 'output.csv';

        $exporter = new SftpCsvExporter($dataCollection, $filename);
        $exporter->export();
    }

    public function exportCsvResponseAction()
    {
        $dataCollection = SomeModel::someQuery();
        $filename       = 'output2.csv';

        $exporter = new ResponseCsvExporter($dataCollection, $filename);
        $exporter->export();
    }
}

Than there's the first layer: Export, I created an interface to say what it should do (don't mind about how now) and a abstract class that implements some parts of it.

interface Exportable
{
    protected function createFile();

    protected function write($line);

    protected function deliver($filename);
}

abstract class Export implements Exportable
{
    protected $fileHandle = null;
    private   $dataCollection;
    private   $filename;

    public function __construct($dataCollection, $filename)
    {
        $this->createFile();

        // @TODO You should add validation for $dataCollection like
        // checking if it has data, if it really is a Collection so we can call chunk, etc
        // And check $filename for invalid characters
        $this->dataCollection = $dataCollection;
        $this->filename       = $filename;
    }

    protected abstract function createFile();

    protected abstract function write($line);

    protected abstract function deliver($filename);

    // this method is who makes it all work together
    // and let the controller be so simple
    public function export()
    {
        $this->dataCollection->chunk(200, function ($lines) {
            foreach ($lines as $line) {
                $this->write($line);
            }
        });

        $this->deliver($this->filename);
    }
}

Now there's the second layer: Csv, in this layer you will be able to add more file formats in the future if needed.
This layer knows how to write, but doesn't know how to open nor deliver the file.

abstract class CsvExporter extends Export
{
    const DELIMITER = ';';

    private $headerWritten = false;

    protected function write($line)
    {
        if (!$this->headerWritten) {
            fputcsv(
                $this->fileHandle,
                array_keys(SomeModel::lineMapping(SomeModel::first())),
                self::DELIMITER
            );

            $this->headerWritten = true;
        }

        fputcsv(
            $this->fileHandle,
            SomeModel::lineMapping($line),
            self::DELIMITER
        );
    }
}

And finally the third and last layer: this is responsible for opening and delivering the file. So we have Sftp and Response in this layer.

class SftpCsvExporter extends CsvExporter
{
    protected function createFile()
    {
        if ($this->fileHandle !== null) {
            throw new LogicException('Handle already initilized');
        }

        $this->fileHandle = fopen('php://temp', 'w');
    }

    protected function deliver($filename)
    {
        return Storage::disk('sftp')->put($filename, $this->fileHandle);
    }
}

class ResponseCsvExporter extends CsvExporter
{
    protected function createFile()
    {
        if ($this->fileHandle !== null) {
            throw new LogicException('Handle already initilized');
        }

        $this->fileHandle = fopen('php://output', 'w');
    }

    protected function deliver($filename)
    {
        $handle = $this->fileHandle;

        return new StreamedResponse(function () use ($handle, $filename) {
            // I don't know this StreamedResponse so you might want to correct this
            // the only thing left is to close the handle before send the file
            fclose($handle);
        }, 200, [
            'Content-Type'        => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ]);
    }
}


Calculating the biggest number of consecutive ones in a binary number

How about this? (maybe needs some adaption in Java):

int consBits(int x) {
    int consecutiveBits = 0;
    for(;x;consecutiveBits++)
        x &= (x<<1u);

    return consecutiveBits;
}

The idea is to binary & a number with a shifted version of itself. If it is not 0 there is a consecutive sequence of ones. Repeat until the result is 0 and we get the total length of consecutive ones.


I seem to get the feeling you are either not comfortable using maps as others have suggested here...so why not throw in a switch instead?

$volume = $array[1];

if($volume > 10000 && $volume < 50000){
    $selling = $volume - 250;
} else if($volume > 50000 && $volume < 100000){
    $selling = $volume - 500;
} else {
    $selling = $volume - 100;
}

$buying = $volume - 1000;

switch($volume){
    case 10000:
    case 20000:
    case 30000:
    case 40000:
        $buying = $buying - 1000; break;
    case 50000:
        $buying = $buying - 750; break;
    case 60000:
    case 70000:
        $buying = $buying - 500; break;
    default:
        $buying = $buying;
}

REVISIT 01/26/2015: Revisiting this to say that I would now rewrite this code as follows:

function bound_check($bounds, $bound_check, $default_value) {
    $return_data = NULL;
    foreach($bounds as $bound){
        if($bound_check >= $bound[0] && $bound_check <= $bound[1]){
            $return_data = $bound_check - $bound[2];
        }
    }
    return $return_data ?: $default_value;
}

$selling_bounds = [
    [10000, 50000, 250],
    [50000, 100000, 500],
];

$buying_bounds = [
    [10000, 40000, 1000],
    [50000, 50000, 750],
    [60000, 70000, 500]
]

$selling = bound_check($selling_bounds, $array[1], $volume - 100);
$buying = bound_check($selling_bounds, $array[1], $volume - 1000);


Converting numbers to words - JavaScript

I like how you've reduced all of the words to lists, that's the right start.

Let's get into it:

  for(let i = 0; tempNum; i++){

I have no idea what you've doing here, I assume when tempNum===0 then the loop stops?

Don't do this, it's confusing as hell.

I'm going to suggest that you rewrite the entire thing as a recursive function or a reducing function, but if you insist on using a loop, then just make it a while(true) loop and add a return or a break statement to it to exit it.

You have a lot of branching logic:

  for(let i = 0; tempNum; i++){
    if(hundreds){
      if(i){
      }
      if(tens){
        if(wordsForConstruction.hasOwnProperty(tens)){

        }else{
          if(ones){
          }
        }
      }

      if(hundreds){
      }
    }
  }

The term to think about here is cyclomatic complexity keeping track of which branch the code is currently in involves holding a lot of information in your head, and then you have to run through it again for the next number etc. If you code is looking like a lot of these nested if statements, that's a code smell, and you should be doing something else.

The real issue you have, is that you are manually writing the code to do the 'detect how many hundreds, thousands, millions', instead you you could abstract this to a map.

What I would do is:

const powerMap = {
  "million": 1000000,
  "thousand": 1000,
  "hundred" : 100,
  "rest": 1,
}; //And ofcourse you can extend this to billions, trillions, etc.

And then you can create a general abstraction to to count how many of each there are:

const powerMap = {
  "million": 1000000,
  "thousand": 1000,
  "hundred" : 100,
  "rest": 1,
}; //And ofcourse you can extend this to billions, trillions, etc.

function getUnitCounts(value) {
    const data = Object.entries(powerMap).reduce(({value, result}, [unitName, power]) => {
        const nCount = Math.floor(value/power);
        const nRemainder = value%power;

        return {
            value: nRemainder,
            result: {
                ...result,
                [unitName]: nCount
            }
        }

    }, {
         value,
         result: {}
    });

    return data.result;

}

console.log(getUnitCounts(20020000));
console.log(getUnitCounts(1100));
console.log(getUnitCounts(201110));

Now - if you're not familar with spread syntax and Array.reduce this might seem confusing. But notice how I don't use a single if statement - all I'm doing is looping over a list and returning an accumulator. Once you've familiar with the odd syntax, this is easier to keep in your head.

From the answer I've given here, it would now be a matter of converting the count of each unit into the words, and then also applying the words for 0-100 like you have.


Readability

First things first. Formatting. Indent after each brace, consistently. It is more or less impossible to read your code.

Secondly, variable naming. 1 (el) is a terrible name for a variable, since it looks exactly like a l (one), so much so that I just flipped them and you probably didn't notice. Not to mention that one of your Ls is really width. So you should name them length and width.

Rectangle

Rather than having setnum(), which is not a meaningful name, instead require your Rectangle to be constructed directly with the values:

class Rectangle {
public:
    Rectangle(int w, int h)
    : width_(w), height_(h)
    { }

private:
    int width_, height_;
};

Note the improved naming of the member variables and the class. Adding class to the type name is unnecessary and redundant. This constructor will additionally solve your other problem: accidentally misusing Rectangle by accessing its member functions before you set any of the values (uninitialized ints have indeterminate value). This way, you're guaranteeing that width_ and height_ are set.

Usage here would be like:

cin >> width;
cin >> height;
Rectangle ra(width, height);
cout << ra.area();

const-ness

The area() member function doesn't (and shouldn't) modify any of its members. So it'd be better to mark it const:

int area() const { ... }

This lets you get the area of a const Rectangle.


Converting multiple query to use parameters to avoid SQL injection

The recommended way to avoid SQL injection attacks is to use parameters.
Also I can recommend that you create a stored procedure instead of using dynamic SQL.

You can pass your dropdown indexes as parameters to your SP and use the old trick of using it as conditional on the where clause.

Your select can end up like this:

select CT.columnA, CT.columnB
from tableA CT
join tableB SE on SE.idA = CT.id
where
      (@ddlTaskName_SelectedIndex > 0 and (CT.ATTR2739 LIKE '%' + @ddlTaskName_SelectedItemText))
-- or (@ddlTaskName_SelectedIndex = 0 and (CT.ATTR2739 LIKE '%' OR CT.ATTR2739 IS NULL))     -- if you think enough ill see this line is unnecessary
and
      (@ddlService_SelectedIndex > 0 and (SE.ATTR2821 LIKE '%' + @ddlService_SelectedItemText + '%')
-- This "else" line is unnecessary too, since we don't really filter it because eveything is "like %" or "null"

And so on ...

Those dropdown texts are still prone to SQL injection since a smart hacker may be able to change its value depending on your system.
You can fix it to just set variables inside the SP, this mean you will not pass the drop down text, just the indexes and do some swith case to set that varchar variables before the select.

That can add some maintenance issue, since your dropdown texts must match the same texts hardcoded on your SP. A better approach can be to create a domain table for each dropdown:

Create table DropDownClientValues
(
 index int
,text varchar(50)
)

And list your dropdown values directly from those domain tables; that way all your selects/SP can refer the exact same values.

This has the advantage of making adding/removing options from your drop downs very easy and with no impact in your code. Sadly this can be a bit onerous to refactor a big app that way.


There are several approaches to Project Euler Question 1.  The one you have chosen is not particularly efficient, as it involves creating two lists, then merging them.  I'm not going to present alternative solutions here.  If you are going with this approach, you can write it much more simply:

sum_multiples :: Int -> Int -> Int -> Int
sum_multiples max factor1 factor2 = sum $ multiples1 `union` multiples2
  where
    multiples1 = [factor1, 2 * factor1 .. max - 1]
    multiples2 = [factor2, 2 * factor2 .. max - 1]

In particular,

foldr (+) 0 is just the built-in sum function.
f_multiple can be replaced with ranges.

In terms of style, your last line is hard to read due to its length.  To shorten it,

Use shorter variable names, e.g. factor1 instead of first_factor.
Give names to complex subexpressions using a where clause.
Use the $ operator to form a "pipeline", instead of nesting parentheses.


Computing the subtotal of all items on their property criteria: qty * price

You are computing the sum of an array, with a twist. Use Array.reduce() to compute sums.

Furthermore, if you are going to use the ECMAScript let language feature, you should also use arrow function notation.

function subtotal(items) {
    return items.reduce(
        ((total, item) => total + item.qty * item.price),
        0.00
    );
}

Better naming would help. "Get" implies that you are retrieving something that already exists, which is not the case here.  Also, i has a connotation of being an index counter, which makes its use in your forEach() confusing.


Python Secure Implementation Of AES-256-CTR Using Cryptography.Hazmat

A warning

You probably already saw this coming, but: I would be remiss if I didn't say it. 'Rolling your own to learn' is fine, but perhaps the most difficult and dangerous place to do it is cryptography. Cryptographic security is notoriously difficult to ascertain. The less you do yourself and the more you leave to well-reviewed, well-established libraries, the better.

Indentation

Python code typically sees three- or four-space tabs by convention; two is a little low.

Type hints

PEP484 allows for this:

def __init__(self,key):

to be (at a guess)

def __init__(self, key: bytes):

and this:

def encrypt(self,plain_text):

to become

def encrypt(self,plain_text: str) -> str:

Helpful comments

This isn't one:

#Encryption Function

you're better off either deleting it, or writing a docstring with non-obvious documentation:

def encrypt(self,plain_text):
    """
    Encrypts a string using this object's key and the AES algorithm.
    Returns the encrypted result, as a base58-encoded string.
    """


Building an undirected graph from depth-first sorted node list in Python

I believe you can get a similar result by creating and passing around an iterator on the nodes list:

def node_iterator(nodes, nit=None, parent=None):
    if nit is None:
        nit = iter(nodes)

    node = next(nit)
    yield (node, parent)

    for i in range(node.child_count):
        yield from node_iterator(nodes, nit, parent=node)


Photogallery First project in OOP review

The code below is good. I only changed the comments a bit to make them a bit clearer and more concise. However,
one glaring issue is that it seems you have your setters and getters mixed up. Note the getimage_*()
and setimage_*() functions you have in your class. Usually, setter and getter functions do exactly that:
they set a value and get a value. What you seem to be doing is using the set* functions to get the
value returned by another function. This is +wrong+.

<?php

class Image{
    public $imageFilepath = "";
    public $imageTitle;
    public $imageSize;

    /**
     * Construct
     */
    public function __construct() {
         echo 'Welcome to Dannys awesome Gallery';
    }

    /**
     * Get image filepath
     *
     * @return array
     */
    public function getimage_Filepath() {
        $image_files = get_files($imageFilepath);
        if (count($image_files)) {
            $index = 0;
            foreach($image_files as $index=>$file)
            $index++;
        }
        return;
    }

    /**
     * Output tile image found
     *
     * @return array
     */
    public function setimage_Filepath() {
        echo $this->getimage_Filepath();
    }

    /**
     * Generate image name derived from filename
     *
     * @return string
     */
    public function getimage_title($imageTitle) {
        //gets the image title using basename
        $imageTitle = $this->imageFilepath;
        basename($imageTitle);
        return $imageTitle;
    }

    /**
     * Output the image name
     *
     * @return string
     */
    public function setimage_title($imageTitle) {
        //displays the image title
        echo $this->imageTitle;
    }
}
?>

Now, let's get rid of the set* functions:

<?php

class Image{
    public $imageFilepath = "";
    public $imageTitle;
    public $imageSize;

    /**
     * Construct
     */
    public function __construct() {
         echo 'Welcome to Dannys awesome Gallery';
    }

    /**
     * Get image filepath
     *
     * @return array
     */
    public function getimage_Filepath() {
        $image_files = get_files($imageFilepath);
        if (count($image_files)) {
            $index = 0;
            foreach($image_files as $index=>$file)
            $index++;
        }
        return;
    }

    /**
     * Generate image name derived from filename
     *
     * @return string
     */
    public function getimage_title($imageTitle) {
        //gets the image title using basename
        $imageTitle = $this->imageFilepath;
        basename($imageTitle);
        return $imageTitle;
    }
}
?>

Great! Looking much better. Now, remember that your construct should be used to set variables or initialize
functions that the object requires - NOT echoing something out (unless its an Exception, in which case you'd
use throw new Exception('')). So let's move the echo OUT of the class, initialize the $imageFilepath
variable:

<?php

class Image{
    private $imageFilepath;
    private $imageTitle;
    private $imageSize;

    /**
     * Construct
     */
    public function __construct(string $imageFilepath) {
        if(empty($imageFilepath)){
            throw new Exception("Expecting image file path, nothing given.");
        } else {
            $this->imageFilepath = $imageFilepath;
        }
    }

    /**
     * Get image filepath
     *
     * @return array
     */
    public function getImageFilepath() {
        return $this->imageFilepath;
    }

    /**
     * Get the files in a directory pointed by imageFilepath
     *
     * @return array
     */
    public function getFilesInFilepath(){
        $directoryContent = scandir($this->imageFilepath);
        foreach($directoryContent as $key => $value){
            $path = $this->imageFilepath . PATH_SEPARATOR . $value;
            if(is_file($path) && is_readable($path)){
                $files[] = $path;
            }
        }
        return $files;
    }

    /**
     * Generate image name derived from filename
     *
     * @return highlight_string(str)
     */
    public function getImageTitle(string $imageFile) {
        return basename($imageFile);
    }
}

// We initialize the object and set the imageFilepath at the same time
$image = new Image("/home/jsanc623/Pictures/");

// We can get the image filepath
$imageFilepath = $image->getImageFilepath();

// We can get an array of all the files in a directory
$filesInFilePath = $image->getFilesInFilepath();

// We can then get the image titles for each image/
foreach($filesInFilePath as file){
    $imageTitle[] = $image->getImageTitle($file);
}

print_r($imageTitle)
?>


Makes sense to me. A couple small things:

lambda f: float(f) should be equivalent to just float if I'm not mistaken. You can simplify the loop a bit too since you're not actually using the dictionary keys.

types = [
  (r'(regex)', float),
  (r'(regex)', int),
  (r'(regex)', str),
]
for pattern, fn in types:
  match = ...


The Home variable can be modified by any package. Pretty dangerous. Maybe use a private variable (or a struct that contains a private string field) and a getter method.
You're assuming that any HTML page won't be modified semantically by your transformation. This is correct for your minimalistic example, but not in the general case. For example, within
 or  tags, whitespace matters. There are probably many other ways this could go wrong. You should probably use a minifier package like this one instead.

Edit: actually, your strings.Replace(htmlJoined, "> <", "><", -1) will probably have undesired effects even for very simple HTML pages. Consider:

this pretty simple example.

If you delete the space between  and , it effectively deletes the visible space between "simple" and "example" when you display the page. All the more reason to use a minifier library.


Solving the sliding pyramid problem in Python3

My main critiques are:

doug is a baffling variable name.
You shouldn't have to store the entire file in memory, nor should you have to invert the triangle.  Doing so hurts scalability.  You should be able to process each line as you read it.

Instead of your build_tree() implementation, I recommend using a generator function to parse the input, such that you only need to store one line at a time.

min_sum() could be made more elegant without relying so much on indexes.

def triangle_rows(filename):
    with open(filename) as f:
        int(next(f))    # Skip first line, which specifies the number of rows
        for line in f:
            yield [int(entry) for entry in line.split()]

def min_sum(triangle):
    row = next(triangle)
    for row_below in triangle:
        row = [min(l, r) for l, r in zip(
            [a + b for a, b in zip(row + [row[-1]], row_below)],
            [a + b for a, b in zip([row[0]] + row, row_below)]
        )]
    return min(*row)

if __name__ == '__main__':
    print(min_sum(triangle_rows('input.txt')))