Making use of a decorator within a python script

While decorators are fun to learn about (especially when you get to decorators taking arguments and class decorators) and they can be quite useful, I think this decorator should not be one. Sorry.

Your code becomes much easier to read and understand by making this into two functions, one that gets the links and one that gets the title from a link, which you then apply to each link:

import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

def get_title(link):
    """Load a link to get the page title."""
    res = requests.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    return soup.title.text.split(" - ")[1] # Will only work exactly like this  with Stackexchange
    # return soup.select_one("h1[itemprop='name'] a").text

def get_links(link):
    """Get all links from a page."""
    res = requests.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    relative_urls = soup.select(".summary .question-hyperlink")
    return [urljoin(url, items.get('href')) for items in relative_urls]

if __name__ == '__main__':
    url = "https://stackoverflow.com/questions/tagged/web-scraping"
    links = get_links(url)
    link_titles = [get_title(link) for link in links]
    print(link_titles)

If you really want to, you can then make a new function that uses these two functions:

def get_link_titles(url):
    """Get the titles of all links present in `url`."""
    return [get_title(link) for link in get_links(url)]

In addition, you should use requests.Session to reuse the connection to the website (since you are always connecting to the same host).

You could put getting a page and parsing it with BeautifulSoup into its own function:

SESSION = requests.Session()

def get_soup(url):
    res = SESSION.get(url)
    return BeautifulSoup(res.text,"lxml")

You might also want to check the headers for a rate limit, because when I ran your code and tried to time it, Stack Exchange temporarily blocked me after some time because the request rate was too high :).


Having initialization code certain to run only once

This could execute more than once pretty easily if called on multiple threads at the same time. This should make it a bit more foolproof:

  public static class Setup
  {
    private static readonly object _locker = new object();
    private static bool _intialized = false;

    public static void Initialize(IWindsorContainer Container)
    {
      lock (_locker)
      {
        //Check if it has already run
        if (_intialized)
        { return; }

        var connectionString = config.ConnectionStrings["ccsMongo"].ConnectionString;
        var dbName = config.AppSettings["ccsMongoDb"];

        //Initialization code here.
        Container.Register(
            Component.For<IOrgRepos>().ImplementedBy<OrgRepos>()
              .DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName}),
            Component.For<IIndividualRepos>().ImplementedBy<IndividualRepos>()
              .DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName}),
            Component.For<IScoreboardRepos>().ImplementedBy<ScoreboardRepos>()
              .DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName})
          );

        //Mark as run
        _intialized = true;
      }
    }
  }


Max Increase to Keep City Skyline in Java

Here:

for( int i = 0; i < ncols; i++ )
{
    int max = Integer.MIN_VALUE;

    for( int j = 0; j < nrows; j++ )
    {
        if( max <= grid[j][i] )
            max = grid[j][i];
    }
    topBot[i] = max;
}

You don't need an extra variable max as a reference. You can simply use topBot[i] as a reference instead (the elements of an int array will be initialized to the default value 0 upon the array's creation, and since the height of a building cannot be less than 0, 0 is an adequate initial value). Also, it would suffice to check if(max < grid[j][i]) (i.e. using < instead of <=), because you don't need to assign the variable if the two values are equal. In fact, there's an even more concise way to write this:

topBot[i] = Math.max(topBot[i], grid[j][i]);

And with the local variable max eliminated, you can fill both topBot and leftRig in one loop:

for (int i = 0; i < ncols; i++) {
    for (int j = 0; j < nrows; j++) {
        topBot[i] = Math.max(topBot[i], grid[j][i]);
        leftRig[j] = Math.max(leftRig[j], grid[j][i]);
    }
}

In your final loop, min is not needed outside the inner for loop, so it would suffice to declare it inside this inner loop. Reducing the scope of variables to the smallest extent necessary makes code easier to read, because, in this case, it would make it instantly obvious that the variable is not needed outside the loop.


The list comprehension you use in diceCode is a bit overkill: after all, you only want to split the list of characters into two. You can use break instead.

Here I have to use fmap tail to act on the second list because break retains the value it breaks the list at (the 'd' character here). This would be a good place to handle the sort of errors that would arise if there is no 'd' in the string.

diceCode :: String -> Dice
diceCode die = (read rolls, read sides) where
  (rolls, sides) = fmap tail $ break ('D' ==) $ fmap toUpper die

Your rollDice is a bit complex. Here is how I would rewrite it:

(rolls, sides) on the left hand side exposes the two components of the tuple
[1..rolls] generates a list of length rolls
mapM (const $ rollDie sides) replaces all the numbers in that list with an invocation of rollDie sides and performs the same job as sequence thus returning an Random g [Int]
sum <$> (or fmap sum $) goes under the Random g part and sums the elements in the [Int] value.

Putting all this together we get:

rollDice :: (RandomGen g) => Dice -> Rand g Int
rollDice (rolls, sides) = sum <$> mapM (const $ rollDie sides) [1..rolls]

The rest of the code is quite idiomatic. One thing I was a bit concerned about is the fact that a Dice is represented as a pair of Ints: to understand which is which, you need to read the code manipulating them and if you make a mistake the compiler won't warn you: they have the same type! It's quite annoying. One thing you could do is use a record type instead in order to name the two fields:

data Dice' = Dice' { rolls :: Int
                   , sides :: Int }

This way you can access them by their names, build the Dice' using the named syntax, etc.


Generally a singleton is declared as

    static let shared = URLs()

or for lazy instantiation

    static let shared = { URLs() }()

I would suggest naming the static property shared. That's a convention used throughout the standard library and Foundation.

In your case, if you change the value of instance, I'd use an optional. Your app init method (such as applicationDidFinishLaunching) should instantiate the instance of URLs with a guard and display the message if it fails.

If you are only setting the value once, I'd suggest something like

static var instance: URLs! { willSet {
    guard instance == nil else { fatalError("value has already been set") }
} }

I normally only use unwrapped optionals when working with an Objective-C based class where I can't overload the initializer (such as view controllers and XCTestCase). In those cases, you know viewDidLoad(), awakeFromNib(), or setUp() will be called (or something is seriously wrong and it isn't safe to continue execution).

Over the last year I've switched to using dependency injection instead of referencing singletons. I even use DI for things like NSNotificationCenter and NSUserDefaults. That makes unit testing a lot easier.


Finding the predominant number in an array

This is a very straightforward implementation and fairly easy to read. Nice work! Here are some ways it could be improved:
Performance
Since you asked about performance, let's start there. Looking at your inner loop, it looks like you are going through the entire array for every element of the array. (Actually, I think there's a mistake here. It looks like you intended to write for (j = i + 1... on the inner loop, but instead wrote for j = 1 + 1....)
Rather than doing it that way, what if we had the numbers already in order? Then it would be really easy to do, wouldn't it? You could just make 1 pass through the array, counting up the number of occurrences of each number as you go. Once you find the predominant one, you can skip the rest.
Furthermore, if at any point you have fewer than 1/2 + 1 numbers left and you switch to a new number, you automatically know that there is no predominant number. So you never have to traverse the entire array, unless the entire second half of the array contains the same number. So in the vast majority of cases you won't traverse the entire array.
So I would add a call to qsort() to sort the numbers after reading in the array. Then your remaining code would be significantly simplified, and would probably be significantly faster.
Naming
Your variable names could use some help. You're on the right track, but I would go further. Instead of number which is quite generic (everything's a number to the computer!), why not numEntries or numElements? i and j are fine for loop indexes.
What does Ap stand for? I see currentElAp, maxAp, etc. But I don't understand what it means. As such, I'd expand it to whatever it stands for.
Functions
I would break the program into separate functions with good names that describe what it does. For example, you could have a readEntries() function that reads in the array, a findPredominantNumber() function that finds the numbers you're looking for, and a displayResults() function that prints everything out. It would make the code more readable and easier to understand at a glance.
Stylistic Stuff
I would suggest a few stylistic improvements. In general it's best to put one variable declaration per line. It's easier to read and can avoid some common errors, like thinking that you're declaring a pointer when you're not.
Use more whitespace! I see only a single blank line in your function. It would be nice to see some more between the last for and the final if.
I would also recommend using brackets around single-line statements in an if or for body because this can also reduce the possibility of errors. This one is especially important on code that will be maintained over years.


Here's the "naïve" way to go

"this is a test".split.map { |word| "\"#{word}\"" }.join(" ")

But a better way is to use a regular expression, since those are made specifically for string manipulation/substitution

"this is a test".gsub(/\S+/, '"\0"')

The expression matches 1 or more (the +) non-whitespace characters (the \S) in a row, and replaces the match with the same string (the \0) but surrounded by quotes.


The check is needed, because SetSelected() would throw an ArgumentOutOfRangeException.

See reference source: http://referencesource.microsoft.com/System.Windows.Forms/a.html#fcae9a622a947f54 or read the documentation where it clearly states

Condition for ArgumentOutOfRangeException

  The specified index was outside the range of valid values.


Naming Items

You should avoid abbreviations like Dict in DictReaderCSV, spelling it Dictionary is cleaner.

Next, it's much more natural to use nouns for class names and verbs for methods. As such, I would name your class CSVDictionaryReader and your main method EnumerateEntries(). LinesEnumerator didn't give any hint that the class is also responsible for parsing CSV.

Unused code

ReadFirstLine and ReadFirstLine don't seem to be used in the current code.

Streams

The StreamReader class already provides constructors that receive a disk path, so no need to manually create a FileStream just to pass it onto the StreamReader.

What would however give much more flexibility is for the class to allow the user to provide it with an already constructed Stream or TextReader. Perhaps the user wants to parse a 100 MB CSV as it's arriving over the wire, without writing it to the disk.

Parsing CSV

CSV files allow for quotes to be used so that entries can contain the separator. A parser should be prepared to correctly deal with this.

Id,Name,Age
1,John,20
2,"Jack, the second", 21


Display A Random Tic-Tac-Toe Board Using Java Swing

Math.random is not very intuitive to use. Random makes it much easier. Create an instance of Random somewhere before the main loop, and generate the random indexes with random.nextInt(3) for values 0 1 2.

It's fine to use an array like you did to pick from the values randomly. When there are only few choices, like in this example, another option is to use a switch.

"display" is not a great name for an array of icons. icons would seem more natural.

A simple way to initialize an array:

ImageIcon[] icons = {
    new ImageIcon("images/x.gif"),
    new ImageIcon("images/o.gif"),
};


Find Index of SINGLE odd / even number in array

You only need to iterate the first 3 numbers of the array.

for(let i = 0; i < 3; i++) {

You are iterating through the array twice. You should only iterate once. You can do this by setting the values in the first loop:

let evenCount = 0;
let oddCount = 0;
let evenNumber = 0;
let oddNumber = 0;

for(let i = 0; i < 3; i++) {
    if(integers[i] % 2 === 0) {
      evenCount++;
      evenNumber = integers[i];
    } else {
      oddCount++;
      oddNumber = integers[i];
    }
}

return evenCount > 1 ? oddNumber : evenNumber;


Variant optional to return error string or value

You said:

  I need to know if it's as fast as possible

The only thing I could think of that would make your program potentially faster is:

Initialize the member variable using initialization list syntax

Result(const std::string& errorString) : contents(errorString) {}

// boost::variant already has a constructor that takes a rvalue reference.
Result(T&& value) : conents(value) {}

Other suggestions:

Add operator T functions instead of unwrap

This may be a matter of stylistic preference but I think it is better to use:

Result<int> r = <some function call>;
if ( r && r == 10 )
{
    // Do something with r
}

than

Result<int> r = <some function call>;
if ( r && r.unwrap() == 10 )
{
    // Do something with r
}

You can use the former syntactic construct by providing const and non-const versions of user defined conversion operators.

operator T const& () const
{
   return boost::get<T>(contents);
}
operator T& ()
{
   return boost::get<T>(contents);
}

Decide how to deal with use of Result<std::string>

If you use Result<std::string>, the function operator bool will always return true. For that use case, there is no way to tell whether a function returned with success or failure.

One way to deal with the problem will be to prevent use of Result<std::string> using static_assert.

static_assert(std::is_same_type<T, std::string>::value == false,
              "Can't use std::string as template paramete");

Use a better name than unwrapErr()

I would prefer to use something like getError() or getErrorString().

Update

The operator T functions will be problem when T is bool. If you like to use the operator T functions for all types, it will be better to change operator bool to a different function, such as isGood().

bool isGood() {
    //is the active value our T
    return contents.which() == 0;
}

then, you'll have to use

Result<int> r = <some function call>;
if ( r.isGood() && r == 10 )
{
    // Do something with r
}


Hashing an arbitrary object to a sparse array of bits

Wasting space?
I don't know if there's a better way of generating your hashed bits, but you are using 32x the amount of space that you need to.  I would suggest using all the bits in your keys array rather than just 1 bit per int.
What is l for?
One thing I don't understand about your hash is the use of l.  You are already using random numbers to generate your hash, so why do you need to add two random numbers together?  Is it supposed to generate more randomness?  I don't think it does.
An example of packing the bits
// Only allocate one int for every 32 bits.
keys = new int[(size+31)/32];
for(int i=0;i<bpe;i++){
    int bitNum = (r.nextInt(size)+l)%size;
    keys[bitNum >> 5] |= (1 << (bitNum & 31));
}

To retrieve the bit, previously, you would do:
isBitSet = keys[bitNum] != 0;

Now you would do:
isBitSet = (keys[bitNum >> 5] & (1 << (bitNum & 31))) != 0;


The could looks like it would work properly, and I think it's clearly written and easy to understand.

When you check that a user is logged in, you should check for something in the session that clearly states they are logged in. For instance you could check that $_SESSION['user']['loggedIn'] === true. It's risky to simply test for  isset($_SESSION['session']) as another programmer, or even you in six months time, could write code to set that when the user is not logged in. Perhaps they will want to store a message in the session, like "sorry your password didn't match try again".

I would replace $_SESSION['session'] with $_SESSION['User']. You might then want to only access $_SESSION['User'] from the User class of your application. Other parts of the application may want to store other things in the session - messages to display on next request, or a basket of goods, or whatever the app deals with.

I assume you have called session_start() before the code we see runs.

Using password_verify() is good. Far too many apps implement their own insecure password algorithms.

I don't see the 'new' keyword, which is good - that means you may be doing dependency injection by having the constructor of User take a db as a parameter. If that's true you can easily write a test for the login function that uses a mock db.


In this case you just want your input to be an integer (or a long).
So using the regex is one idea.

But you should also consider malicious users. What if you try

  example.com/article.php?id=1000000000000000000000000000

Which is too big for int/bigint. When the exception is not caught well and your error pages expose information. Worst case this may expose information about the underlying directory structure. Which can be used by hackers while doing other attacks. And even when this is not the case, passing through exceptions are not a best practice.

I would rather use a built-in php method for that like intval.

As an addition to this, you can also use prepared statements which is another very good way to protect against sql injections.

$idv = intval($_GET['id']);
if($idv > 0)
{
    $stmt = $mysqli->prepare("SELECT name, description, date, id, date_created FROM articles WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $idv);
    $stmt->execute();
    $stmt->bind_result($result);
    $stmt->fetch();
    $stmt->close();
}

ref:

http://php.net/manual/en/function.intval.php
http://www.w3schools.com/php/php_mysql_prepared_statements.asp
https://phpbestpractices.org/


Create a deck of playing cards & draw a hand of cards

Shuffling the Deck

Your comment # The deck is shuffled only once, when the deck is first built is wrong.  You are shuffling the deck 52 times; once after before each card is added:

    deck = []
    for value in range(13):
        suit_list = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
        for suit in suit_list:
            ...
            random.shuffle(deck) # This line is executed 13 * 4 times!
            deck.append((name, face, suit, value))
    return deck

Additionally, you are grabbing cards from a random location in the middle of the deck, so it doesn't matter if you shuffled the deck or not:

        selected_card = (random.choice(deck))
        ...
        deck.remove(selected_card)

You should build the complete deck, and then shuffle it once:

    deck = []
    for value in range(13):
        suit_list = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
        for suit in suit_list:
            ...
            deck.append((name, face, suit, value))

    random.shuffle(deck)
    return deck

And then, deal from the top of the deck:

        selected_card = deck.pop(0)

Suits

    for value in range(13):
        value += 1
        suit_list = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
        for suit in suit_list:

The suit_list doesn't change.  It doesn't need to be recreated for each of the 13 card ranks.  You should move it out of the inner loop.

There it is still a local variable.  Code which wants to use your deck of cards might want/need to know the what all the suits in your deck are.  Is it a normal playing card deck, or a deck of Tarot cards?  Is the spade suit represented as "Spades", "SPADES", "S", "♠" or "♤"?

An enum would be a better entity to use as a card suit:

from enum import Enum

Suit = Enum('Suit', 'Clubs, Diamonds, Hearts, Spades')

Then a program could safely refer to the spade suit as Suit.Spades, and iinstead of:

        suit_list = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
        for suit in suit_list:

You'd simply iterate over the Suit enum:

        for suit in Suit:

You can still use suit.name to get a nice string for the suit.

range(start, end, step)

Instead of writing:

    for value in range(13):
        value += 1
        ...

use the fact that a range can start at any value, so you don't need to add 1 to the card's rank at each iteration; just iterate over a different range:

    for value in range(1, 13+1):
        ...

Each tuple represents a card ...

Ok ... lemme think.  The card[0] is the card's rank, and card[1] is the card's suit?  Or do have have that backwards ; card[0] is the suit and card[1] is the rank?

With a tuple, it is easy to forget which member is stored in which field.  It is way easier to use a named tuple:

from collections import namedtuple

Card = nametuple('Card', 'name, face, suit, value')

Then we wouldn't have to remember; card.rank is the the card's rank, and card.suit is the card's suit.

The only downside is ... uhh ... no, sorry, there are no downsides.  A namedtuple is just as efficient time and space wise.  You'd create the cards like this:

        deck.append(Card(name, face, suit, value))

And instead of

    print('You drew %s.' % (selected_card[0]))

you'd write:

    print('You drew %s.' % selected_card.name)

Formatting

The inner parenthesis are unnecessary here:

    print('You drew %s.' % (selected_card[0]))

They take the value "the Ace of Spaces", and ... return that string unaltered.  So we end up with the expression str % str, and since the first string contains only one %s code, the argument is directly used.

if you had used (selected_card[0], ), that would have constructed a tuple of 1 values, a string, which could also be applied to that format string.  Without the trailing comma, you don't have a tuple.

It is easier to use f-strings.  There, the format arguments are placed directly in the format codes, instead of at the end where they have to be match up by positions.  Instead of:

            name = 'the %s of %s' % (face, suit)

you could write:

            name = f'the {face} of {suit}'

which is slightly more compact, and much easier to tell where the values are going in the resulting string.

Hand size

def draw_hand(hand_size):
    player_hand = []
    for draw in range(int(hand_size)):

Wait ... what is that int(...) doing there?  What are you expecting to pass to draw_hand, if not an integer?  Why would you allow it to be a string?

It should be the caller's responsibility for any string to integer conversions.  This function should only expect an integer for hand_size.

Improved code

Using NamedTuple instead of namedtuple, a Rank enumeration, and reducing Card to just a tuple of rank and suit, with str(card) corresponding to the card's name, and card.rank.value for the card's value ... along with some other structural modifications:

from random import shuffle
from enum import Enum
from typing import NamedTuple, List
from itertools import product

Suit = Enum('Suit', 'Clubs, Diamonds, Hearts, Spades')
Rank = Enum('Rank', 'Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King')

class Card(NamedTuple):
    rank: Rank
    suit: Suit

    def __str__(self):
        return f"{self.rank.name} of {self.suit.name}"

def build_deck() -> List[Card]:
    deck = [Card(rank, suit) for rank, suit in product(Rank, Suit)]
    shuffle(deck)
    return deck

def draw_hand(hand_size: int) -> List[Card]:
    return [deck.pop(0) for _ in range(hand_size)]

def print_hand(hand: List[Card]) -> None:
    print("You drew:", ", ".join(str(card) for card in hand))

if __name__ == '__main__':
    deck = build_deck()
    n = int(input(f"How many cards? There are {len(deck)} cards in the deck: "))
    hand = draw_hand(n)
    print_hand(hand)

Result:

  How many cards? There are 52 cards in the deck: 5
  You drew: 2 of Hearts, 9 of Clubs, 5 of Hearts, 7 of Hearts, Queen of Clubs


Also a beginner but one thing I would like to point out is naming function, Style Guide for Python Code states:

  Function Names
  Function names should be lowercase, with words separated by underscores as necessary to improve readability.

  mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

So, in your case write bubble_sort instead of bubbleSort.


Use Prepared Statements

Your code is vulnerable to SQL injection attacks.  Use PDO or mysqli prepared statements to avoid this. See this answer for how to use PDO for this.  If you are using mysql_* you should know that it is already in the deprecation process.

Miscellaneous

Consider using empty to check for empty strings (see comment from Corbin below).
Personally I would use an if else rather than have two identical ternary conditions.


Comparison of 2 values based on custom operator

public class FieldComparer<TFieldValue>
{
  protected FieldComparer()
  { }
}

The right way to prevent a type from being created and allowing only derived types to do it is... to use an abstract class. By making the FieldComparer abstract you won't need to hide the default constructor.

An example implementation could look like this where you have a private class DefaultFieldComparer that implements the FieldComparer:

public abstract class FieldComparer<TFieldValue>
{
    ..

    internal static FieldComparer<TFieldValue> Default { get; } = new DefaultFieldComparer();

    private class DefaultFieldComparer : FieldComparer<TFieldValue> { }
}

I find this is a cleaner solution becasue it informs me that the FieldComparer is a base class and intended be subclassed becasue on its own it has no use but if it has, then it should be instantiable.

private readonly Dictionary<string, Regex> myRegexes = new Dictionary<string, Regex>();

private Regex GetRegex(string left)
{
  Regex regex;
  if (!myRegexes.TryGetValue(left, out regex))
  {
      regex = new Regex(left, RegexOptions.Compiled | RegexOptions.IgnoreCase);
      myRegexes.Add(left, regex);
  }
  return regex;
}

I'm not sure whether it's really necessary to use a dictionary for the regexes. In most cases the static Regex.IsMatch is sufficient and it already does the caching thing:

  The static IsMatch(String, String) method is equivalent to constructing a Regex object with the regular expression pattern specified by pattern and calling the IsMatch(String) instance method. This regular expression pattern is cached for rapid retrieval by the regular expression engine.


Improving the performance of my "type" function

Interesting question, since there is only 1 line to review and a limited amount of ways to get the 'type` of an object

I will say that

function type(obj){
  return  Object.prototype.toString.call(obj).replace(/([\[\]]|object|\s)/gi, "");
}
var o = new (function Name(){})();
console.log( type(o) );

returns ""

whereas

function type(o){
  return  o !== undefined && o.constructor ? o.constructor.name : "Undefined";
}
var o = new (function Name(){})();
console.log( type(o) );

returns "Name" which is more correct.

It seems ( though I fudged it a little, a re-test is required ) that the second approach can be faster on IE and Safari ). All in all, I would copy the jQuery source, it takes care of all corner cases and is sufficiently fast.


Summing the digits of a number (subtracting the first digit if it is negative)

The key to a clean solution is to make it so that the negative sign is not a special case.  Instead of splitting the string character-by-character, capture the digits, such that the first digit might be negative.

function sumDigits(num) {
  return num.toString()
            .match(/-?\d/g)
            .map(function (s) { return parseInt(s) })
            .reduce(function (a, b) { return a + b });
}

console.log(sumDigits(-316));

Also, your variable names are weird and misleading:

The result of .split() is an array, so don't call it a string.
The process of converting a string into a number (i.e. function(x) { return Number(x); }) would be appropriately called toInteger, but once you have applied the string-to-integer conversion to each element of the array, the result would be more appropriately named digits.


Java: Constructor- and Method-overloading exercise

In java, you can just set the value at the given index using that index. Thus, starting out with the simpler update book (which uses the book object), this becomes:

public Book updateBook(int index, Book book) {
    Book oldBook = books[index];
    books[index] = book;
    return oldBook;
}

Alike in the ... string title ... method, but now, you can even use the method from before:

public Book updateBook(int index, String title) {
    return updateBook(index, new Book(title));
}

Disclaimer: this has not been typed in an IDE or compiled, but just done on the fly, thus it might include bugs. But the concept should be clear.


User interface decisions
Having a start option is an odd choice. If the user started the program itself, is it likely that they don't want to start the rest of its logic?
Successive concatenation
This:
decision_prompt = "\nWould you like to bring back a character you killed?"
decision_prompt += "\nOr would you like to kill off another character?"
decision_prompt += "\nEnter 'kill off' or 'bring back' ->"

is better off as
DECISION_PROMPT = '''
Would you like to bring back a character you killed?
Or would you like to kill off another character?
Enter 'kill off' or 'bring back' ->'''

Data structures
It seems that the order of killed_tv_characters does not matter, so it should be a set, not a list.
Input validation
This:
"""Checks user input for decision."""
if user_input in valid_decision_input and user_input == 'kill off':
    return user_input
elif user_input in valid_decision_input and user_input == 'bring back':
    return user_input
else:
    invalid_input == True
    print("Please enter a valid input!")

has a few problems:

invalid_input == True doesn't do what you think it does; it's a no-effect statement
This doesn't really benefit from the combination of valid_decision_input (which should be a set) and checking for specific strings
Early-return means that you don't need to use else

Here is an alternative:
if user_input in valid_decision_input:
    return user_input
invalid_input = True
print("Please enter a valid input!")

Other concerns:

This will set a local invalid_input unless you declare it global at the top
Rather than returning a string, consider returning an Enum to narrowly represent user choice

Booleans
This:
if tv_characters == False:

should be
if not tv_characters:


Edit: Your code is working beyond 15 bits, it's just really slow..... More about that later.

I am not sure why your code does not work beyond 15-bit BigIntegers either.... it's not something daft like the fact you have size = 15, now, is it?

Two suggestions

Apart from that, there are two items that may interest you:

you can probably improve performance by using the two methods:

nextProbablePrime()
isProbablePrime()

With these methods you can check your candidate prime before you do the hard work... i.e. your first call in the isprime() method can be:

if (!n.isProbablePrime()) {
     return false;
}

Then, if it is probably a prime, you will need to check it, and you can do that in a way that may be faster with:

for(BigInteger i=three; i.compareTo(half)<=0;i=i.nextProbablePrime()) {
    ....
}

This may, or may not be faster. Check it.
What will be faster is if you only check to the square-root of n, instead of 'half'. BigInteger does not have a method square-root, but you can get an approximate limit quite fast with just a few iterations through the Babylonian method. You don't need to find the actual square-root, just some value that is slightly larger than the root. This will save many, many, many potential iterations for when the input value really is prime.

Test implementation

I have put together some example code which shows a few things:

your code is, in fact working....
when you have large numbers, your prime factoring guesses are going to pretty much take forever.... and I am not sure if forever-running code is working code...
It uses the faster isProbablyPrime(int) method to short-circuit the slow math.
It computes an approximate square-root of the input value.
It uses nextProbablePrime() instead of checking every odd number in the loop.

Note that I think your algorithm could also be optimized by changing the outer loop. If the goal is to find a large random number, then the better way to do it would be to choose a large number randomly, make sure it is odd, and then test it for prime-ness. If it is not prime, then keep adding 2 until the value is prime. This will significantly reduce the random hunting for prime values.

Here is the code:

private static int size = 1024;
private static Random r = new Random(1);
private static BigInteger two = new BigInteger("2");
private static BigInteger three = new BigInteger("3");

public static void main(String[] args) {

    while (true) {
        BigInteger p = new BigInteger(size, r);
        System.out.println("Processing prime " + p + " with input " + size
                + " bits");

        if (isprime(p) == true) {
            System.out.println("prime=" + p);
            break;
        }
    }
}

public static boolean isprime(BigInteger n) {

    if (!n.isProbablePrime(10)) {
        return false;
    }

    if (n.compareTo(BigInteger.ONE) == 0 || n.compareTo(two) == 0) {
        return true;
    }
    BigInteger root = appxRoot(n);
    System.out.println("Using approximate root " + root);

    int cnt = 0;
    for (BigInteger i = three; i.compareTo(root) <= 0; i = i
            .nextProbablePrime()) {
        cnt++;
        if (cnt % 1000 == 0) {
            System.out.println(cnt + " Using next prime " + i);
        }
        if (n.mod(i).equals(BigInteger.ZERO)) {
            return false;
        }

    }
    return true;

}

private static BigInteger appxRoot(final BigInteger n) {
    BigInteger half = n.shiftRight(1);
    while (half.multiply(half).compareTo(n) > 0) {
        half = half.shiftRight(1);
    }
    return half.shiftLeft(1);
}

And, here is the output

Processing prime 98329376886274465203040498066651959157640182809094020631664385777551847591123638109144698149095205744886312777380124671380640351550097713803874959847367838878126620008205910502904640512240477769179755530216157310355581410760731210073213721673064659778570224177036380289355437254781245378941806708640626915896 with input 1024 bits
Processing prime 37646605107187235792943122848905725816642680759921726391069038948580233504043310475106107937453362419670194263133240792533036542339813188374350574945196545621538046755833078747457686689427373500864049860688062396137214885740182673993779980005699518336257562987964318771232237070594662691795239179395907746381 with input 1024 bits
Processing prime 125205778308571596366364664578026315265996047681538536772575342694310454438809896771367811860534210488218628994364991251294455216205362342490618659150824104797110134588899854049460243713711039304748274575425927846133394573799688746650452867761117377057477970221094526444104587198668516522314203910650060775297 with input 1024 bits
Processing prime 29927154392784343780961536475173096429548596167420203155112563329853022850079385324824305227046118707802338722443720119949840770560558670171973682574167343679095711827324930773450204678598945005042160247713118600168856758838352856602314407651532633576632941646038272135258001495947267516367654449573770447978 with input 1024 bits
Processing prime 139243961902015178358905340711072637999780823861985238094201532190345570854225223205633490036395897038352240416702384303956261085630258304397095684303936086294128301544469715824139689002062508603332475411268227340511899314982630226967627021263463712185132048978641948260688280239972303621025851700017991795656 with input 1024 bits
Processing prime 122363695497135362876334096986750092237187818163935289528269643131788940948676195886148173694943587069178270471951802290191005226421476324835369279161430725594938044767129988205836293228618396536013056503441398180392306035348529131293104302985721904196513857471448257453900973803574632148674525698706255968469 with input 1024 bits
Processing prime 6766841734279494121695202528813564426876102386393672096192548380596947610679150306271345703101761193843898532659901726349258449119163161846636750914151571614552775446973414312295356121082306016346670297986250268817217032557516075488000173517339258842372202954513367225234606811784912645921661651252301210439 with input 1024 bits
Processing prime 1244168157289385582197158692756366939639032807157147509726417844315011285784938824776953893721289756574282393714469772808628985336160381884771437651533388861457165174027710304927221871555060351769769251837444763151883211741263529676654328058488380773866083064897587855677058477160609886235025932428799595897 with input 1024 bits
Processing prime 132158916583424296773989292524518115815097623427134119856232403777863313269411230253297504275469503273779555561857087644449894885032508020437681301637184423517233528793784318637110731993459739195119489689739447166431101193405592878819600262595536763785155730768337651779977312858406291899622027075197339272533 with input 1024 bits
Processing prime 69992427855596672916046274609831358925004102231151217146504934042278719263838690406603474915165537361784459455893083094877744290705302384633321340170916902155546529977673369310451021181970658193490668498069273542381636608842630759935789234533400192866934709438808312038202012904797132388392567889891155748450 with input 1024 bits
Processing prime 21158035183654230873794938382538380103022588111151171726822340627470812338126036440129555658534288545561323627229661551179395796822536779689099195780624577722259563387380039125533382285521378162912552760478091032365155104156393389243223430957343814123541441495493412606366108994001798740793143149348566611849 with input 1024 bits
Processing prime 15252401507860116139044993701109820472568933087608994119874588139374351833868522812721998308899653583211533913737970680874956499213716249151797416323727562426289207703789447617206459217803392887453871279176965603731348358876019227478462392987492580262414905238078166067132705908043224132942658110708655117575 with input 1024 bits
Processing prime 79207591965644170299922757157810677225143754875497695785333916966745459024878221535386104794074683912029219571613935837926395463393267459748825400976839505450111313617312314479345019735666163348592463847785881480127339787201145529464779061029020193892147298882124349322947190382379671430079191833914102173464 with input 1024 bits
Processing prime 61030497376329633328073316647655267262303694060711488520514344109326325543945802124423073251577269169186781440230219553617205658081336472411027108746182826458446589150653587257149674878699689258298746835269894603933930803472419590290016677183062036325055276717300539131443014986954057041180792801863470921160 with input 1024 bits
Processing prime 169114037779361593124142841783629182425924353804019723914654438093025578377446888507229925252227113606029383048794273249003173542629081468619397107139204307145864334149929493619281837363125251731861465625382815511697458723930987915758447225669236647982784800507786813022174334313252476414285766502413871475837 with input 1024 bits
Using approximate root 25226202323750862638468707057345770204269264134797015774704159175996067529790533462300444165020098361223682946889361283140757213132269147109605325588573982
1000 Using next prime 7927
2000 Using next prime 17393
3000 Using next prime 27457
4000 Using next prime 37831

by my estimates, on my machine, it will probably take a few years to test all primes up to 25226202323750862638468707057345770204269264134797015774704159175996067529790533462300444165020098361223682946889361283140757213132269147109605325588573982 .... but, that is much faster than what it would to calculate all the primes up to half of the test value which is 169114037779361593124142841783629182425924353804019723914654438093025578377446888507229925252227113606029383048794273249003173542629081468619397107139204307145864334149929493619281837363125251731861465625382815511697458723930987915758447225669236647982784800507786813022174334313252476414285766502413871475837

If you follow my suggestion and loop to find primes using +2 instead of random, then your main method could be:

public static void main(String[] args) {

    BigInteger p = new BigInteger(size, r);
    if (testBit(0)) {
        p = p.add(BigInteger.ONE);
    }
    while (true) {
        System.out.println("Processing prime " + p + " with input " + size
                + " bits");

        if (isprime(p) == true) {
            System.out.println("prime=" + p);
            break;
        }
        p = p.add(TWO);
    }
}


Uppercase the initial char of every string in a list

Start by writing a method that returns the initials of a single string.

private static string GetInitials(string name)
{
    ???
}

You have the right idea, but there are some overloads we can use that will make the code a bit nicer:

private static string GetInitials(string name)
{
    var initials = name
        .Split((char[])null, StringSplitOptions.RemoveEmptyEntries)
        .Select(w => char.ToUpper(w[0]));
    return new string(initials.ToArray());
}

Here we've used the overload of Split that won't return empty entries, so we don't have to check for empty entries. We've also used the string(char[]) constructor instead of building up the string ourselves.

Now Initials we be written as

return names.Select(GetInitials);

There's a problem with both versions in that the method will not return if the input sequence is infinite (which you've mentioned is a case you want to handle).

Suppose we have this helper method to create an infinite sequence of a single value

private static IEnumerable<T> Repeat<T>(T value)
{
    while (true)
    {
        yield return value;
    }
}

Then our method should be able to handle this client code:

foreach (var cl in Repeat("Mickey Mouse").Initials().Take(5))
{
    Console.WriteLine(cl);
}

The versions posted must process every element of the sequence before they return, which isn't possible for infinite sequences.


Find a serial port device through WMI (windows management instrumentation)

The code works well, but I want to know where I can improve it to make it more resilient and less error prone.

A very good start would be to always use braces {} although they might be optional.
By stacking the using blocks you can save some horizontal spacing.
By reverting the condition of if (portList.Count != 0 && matchingEntities != null) you could return early and the else would be (like now) redundant and could be removed which will save some spacing too.
The naming of the variables could need some imporvements too, e.g the plural matchingEntities doesn't match the result of the call to First().
Storing the result of matchingEntities["DeviceID"].ToString() into a variable will speed up things.

Implementing the mentioned points will lead to

string comportInfo = string.Empty;

using (var entitySearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE Caption LIKE '%" + SerialPortToFind + "%'"))
using (var serialPortSearcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSSerial_PortName"))
{
    //testBase.SamplerWithCancel is like a for loop with exception control, a time between interations and amount of iterations to be made. It expects a true or false value to determine whether a desired condition is met. Failing to return a true value in the specified iterations throws an exception.
    testBase.SamplerWithCancel(() =>
        {
        var portList = serialPortSearcher.Get().Cast<ManagementBaseObject>().ToList();
        var matchingEntity = entitySearcher.Get().Cast<ManagementBaseObject>().First();

        if (portList.Count == 0 || matchingEntity == null)
        {
            return false;
        }

        string entity = matchingEntity["DeviceID"].ToString();

        foreach (ManagementBaseObject port in portList)
        {
            if (port["InstanceName"].ToString().Contains(entity))
            {
                comportInfo = port["PortName"].ToString();
            }
        }

        return true;

    }, "Serial port not found", 3, 1500, 500, false, false);
}


Cumulative transition matrix Markov Chain simulation

I see nothing wrong with your implementation, in the sense it does exactly what you described in plain English, and somewhat efficiently. Here are however a few pieces of advice, mostly about improving your coding standards.

Add some spaces to your code to make it more readable. Have a look at the body of basic functions (e.g. lm) to see what clean code should look like. In particular, spaces after commas and spaces on both sides of <-, =, and all binary operators.
Replace your hardcoded values (5 and 25) with variables. 5 can be derived from the number of rows in cum_trans and 25 is an input to your process. By assigning it to a variable (or a function input), and reusing that variable throughout your code, your code becomes easier to read and maintain, and more robust to changes. Imagine for example what would be required of you if you wanted to change the size of the transition matrix or wanted to have 50 iterations instead of 25.
Using a 1-row matrix is overkill and error-prone: use a vector.
Choose well how you name your variables and comment your code. Again, to make it easier to read and understand.
Learn the difference between numerics and integers. Here your states are obviously integers, yet your code stores numerics. Granted, it is not critical here, but using integers use less memory and can make your code faster. Integers are also not subject to floating point errors so they can make your code more robust in some instances.
Marginal speed improvement. The 25 random calls to runif(1) being independent, you can make a single call to runif(25) and store the results.
Think of your code in terms of inputs of outputs, then write a function.

Updated code taking some of these into account:

random.walk <- function(cum_trans, length.out = 25L) {
   num.states <- nrow(cum_trans)
   states  <- vector(mode = "integer", length = length.out)
   # pick the initial state randomly
   states[1L] <- sample(num.states, 1L)
   # jump randomly using the cum_trans matrix
   num.jumps <- length.out - 1L
   randoms <- runif(num.jumps)
   for (i in seq(num.jumps)) {
      current.state  <- states[i]
      current.prob   <- cum_trans[current.state, ]
      states[1L + i] <- findInterval(randoms[i], current.prob) + 1L
   }
   return(states)
}

Next, think of the assumptions your code is making: cum_trans must be a square matrix with each row being an increasing vector of positive values ending with 1. length.out must be an integer vector of length 1. All of these assumptions can be checked at the top of the function's body; I am only implementing a few of them here:

stopifnot(nrow(cum_trans) == ncol(cum_trans),
          all(cum_trans >= 0),
          is.integer(length.out),
          length(length.out) == 1L)

This way, there is no way you or your end-user can mess up with the inputs.

I hope you find this useful and it encourages you to write better code.


lsblk

The -s option to lsblk was introduced to util-linux rather recently, in release 2.22.  You may experience compatibility issues on slightly older GNU/Linux installations.

But I don't see why you would want the -s option at all — it just gives you an inverted device tree.  For example, on my machine:

$ lsblk -o name -n -s -l
sda1
sda
sda2
sda
sr0
vg-root
sda3
sda
vg-var
sda3
sda
vg-data
sda3
sda

In the output, sda appears multiple times.  To understand the output, you need to drop the -l flag so that the list appears in tree form:

$ lsblk -o name -n -s
sda1
└─sda
sda2
└─sda
sr0
vg-root
└─sda3
  └─sda
vg-var
└─sda3
  └─sda
vg-data
└─sda3
  └─sda

Now, it's more apparent that the -s option isn't helpful.  If you drop it, then the output makes more sense:

$ lsblk -o name -n
sda
├─sda1
├─sda2
└─sda3
  ├─vg-root
  ├─vg-var
  └─vg-data
sr0
$ lsblk -o name -n -l
sda
sda1
sda2
sda3
vg-root
vg-var
vg-data
sr0

To list the devices on sda, it would be better to run lsblk -o name -n -l /dev/sda — that would immediately drop sr0 from consideration, for example.  Note that LVM volumes (such as vg-root above) would still appear in the output.  I don't think that doing a substring search (if x != disk and disk in x in your code) is a reliable filter.  It could be fooled if there are more than 26 physical disks: the 27th disk would be named sdaa.  It might also be fooled by exceptionally tricky naming of LVM volumes.

Subprocess execution

Whenever practical, I recommend avoiding the shell when executing subprocesses.  The shell introduces a set of potential security vulnerabilities — for example, shenanigans with the PATH environment variable.  Best practice would be to run the command with a specific executable and pre-parsed command-line options:

run('/bin/lsblk -o name -n -s -l'.split(), stdout=PIPE)

Alternative solution

I actually wouldn't bother with parsing the output of lsblk at all.  After all, lsblk is just a way to report the contents of the sysfs filesystem.  You would be better off inspecting /sys directly.

from glob import glob
from os.path import basename, dirname

def physical_drives():
    drive_glob = '/sys/block/*/device'
    return [basename(dirname(d)) for d in glob(drive_glob)]

def partitions(disk):
    if disk.startswith('.') or '/' in disk:
        raise ValueError('Invalid disk name {0}'.format(disk))
    partition_glob = '/sys/block/{0}/*/start'.format(disk)
    return [basename(dirname(p)) for p in glob(partition_glob)]


You can make it pretty short in Python 3 if you use functools.reduce():

from functools import reduce

interest_list = [0.5, 0.4, 0.3, 0.5, 0.7, 0.4, -0.2, -0.5, 0.3, 0.7, 0.9, 1.0]

l = [1 + n / 100 for n in interest_list]

accrued = (reduce(lambda x, y: x * y, l) - 1) * 100

In Python 2.7 no imports are needed.


Better way for accumulating a value than using inject/reduce with conditional operator?

There's a built-in count method which handles your example cleanly:

names.count {|name| triangles.include?(name.points) }

Also, the accumulator version should use +, not +=. reduce uses the block's return value; there's no need to modify acc.

In general, though, there's no simpler way to accumulate values than reduce. It's not very clear, but all of the alternatives are worse.

Don't be afraid of the conditional operator. It's just a different way to spell if...else.


There are a few ways of going about this. One is creating an aggregate type that can forward to the call to the correct comparator.

template <typename T>
struct comp
{
private:
    bool desc;
    std::greater<T> great;
    std::less<T> less;

public:
    explicit comp(bool descending = false)
      : desc(descending)
    { }

    bool operator()(const T& f, const T& g) const
    {
        return (desc) ? great(f, g) : less(f, g);
    }
};

The downside of this is that a comp object will be at least sizeof(greater + less + bool). This may or may not be a problem. Your call to sort would then look something like:

typedef std::wstring str_t;
bool descending = true;
std::sort(vec.begin(), vec.end(), comp<str_t>(descending));

If the decision is always known at compile time, you can play some template tricks:

template <typename T, bool desc>
struct comp;

template <typename T>
struct comp<T, true>
{
private:
    std::greater<T> great;

public:
    bool operator()(const T& f, const T& g) const
    {
        return great(f, g);
    }
};

template <typename T>
struct comp<T, false>
{
private:
    std::less<T> less;

public:
    bool operator()(const T& f, const T& g) const
    {
        return less(f, g);
    }
};

This requires descending to be const or constexpr:

constexpr bool descending = false;
std::sort(v.begin(), v.end(), comp<str_t, descending>());

This might be a one step forward, two step back kind of solution. It's quite a bit of code to avoid an if/else - you'll need to decide if this is worth it at all.

Edit: As @LokiAstari pointed out, you can simplify the above with inheritance:

template <typename T>
struct comp<T, true>
  :  std::greater<T>
{ }

template <typename T>
struct comp<T, false>
  : std::less<T>
{ }


Statistical calculations with sets of genes

Your code have a complexity of O(N*N) [genesPerSet=N]. But using the fact that the order of the values is irrelevant for you we can order it in O(N•log(N)) and compute the “scores” in O(N). (With potentially can be thousands time faster).

Also, we have a total of N*N comparisons. Then U_Original + U_Random = N*N, meaning we don’t need to compute U_Random.
Also your statistic Zn= Umin-N*N/2;[Umix=min(U_Original,U_Random)], when you only abs(Zn/Zd) is symmetric around N*N/2. We need only one algorithm.

1.- A first thing can be to take arguments by (const) reference :

int WilcoxinRST::work(const GeneSet &originalGeneSet, const vector<string> &randomGenes)

2.- You fill into vector geneIDs; but dont use it ? Why?

3.- You can iterate only 2 times.

4.- You keep the signal values (probe intensitat?) together in one vector and use another vector to signal what is each item – simple keep in two vector.

5.- You don’t need the score vector, only the summa.

6.- Why 20 millions times? I gess your are computing some “statistic” stability or BStrap. Probably you use the same originalGeneSet many time. I think you can in another question post the code that call this function to spare in making each time the vector of values and sorting.

7.- If you aproximatly know the espected size of the vectors you can reserve() it, add new item with push_back(), and access with .at() (somewhere write a try/catsh). But here we know exactly the numer of item, and we can set it in the cinstructor and then use [] with is the faster way.

Here is first the new O(N•log(N)) code.

What follows is a cleanup of your code but still O(N*N), fast but only by a constant factor.

Then the same code but mixed with yours original code and with more comments.

Please, debugg this and tell me how was.

#include<vector>
#include<algorithm>

int WilcoxinRST::work(const GeneSet &originalGeneSet , const vector<string>& randomGenes)
{
    size_t genesPerSet = originalGeneSet.geneCount();
    std::vector<double> valueOri(genesPerSet), valueRnd(genesPerSet);
    /**
     * Fill the valueOri vector with original gene set data, and valueRnd with random data
     */
    for (size_t i = 0; i < genesPerSet; i++)
    {
      valueOri[i] = std::fabs(expressionLevels.getValue( originalGeneSet.getMemberGeneAt(i) , statType ));
      valueRnd[i] = std::fabs(expressionLevels.getValue( randomGenes.at(i)                  , statType ));
    }
    std::sort(valueOri.begin(),valueOri.end());
    std::sort(valueRnd.begin(),valueRnd.end());

    /**
     * calculate the scores Ua, Ub and U
     */
    long U_Original=0 ;

    if (statType == Fold_Change || statType == T_Statistic  || statType == Z_Statistic
        statType == FDR_PValue  || statType == PValue )
    {
        //      Higher value is a winner
        size_t j=0;
        for (size_t i = 0; i < genesPerSet /*totalGenes*/; i++)      // i   -  2x
        {
            while(valueOri[i]  > valueRnd[j]) ++j ;
            U_Original += j;
        }
    } else { cout << endl << "ERROR. Statistic type not defined." << endl;  }

    /**
     * calculate z
     */
    double Zn, Zd, Z;
    Zn = U_Original - ((genesPerSet * genesPerSet) / 2);
    Zd = std::sqrt( (double) (((genesPerSet * genesPerSet* (genesPerSet + genesPerSet + 1)))) / 12.0);
    Z = Zn / Zd;

    /**
     * Return 0/1/2
     * 2: p value < 0.01
     * 1: 0.01 < p value < 0.05
     * 0: p value > 0.05
     */
         if (std::fabs(Z) > 2.303)  return 2;
    else if (std::fabs(Z) > 1.605)  return 1;
    else                            return 0;
}

What follows is a cleanup of your code but still O(N*N), fast but only by a constant factor.

#include<vector>
using namespace std;
class GeneSet ;
class WilcoxinRST;

int WilcoxinRST::work(const GeneSet &originalGeneSet , const vector<string>& randomGenes)
{
    size_t genesPerSet = originalGeneSet.geneCount();
    vector<double> valueOri(genesPerSet), valueRnd(genesPerSet);
    /**
     * Fill the valueOri vector with original gene set data, and valueRnd with random data
     */
    for (size_t i = 0; i < genesPerSet; i++)
    {
        valueOri[i]   =  fabs(expressionLevels.getValue( originalGeneSet.getMemberGeneAt(i) , statType ));
        valueRnd[i]   =  fabs(expressionLevels.getValue( randomGenes.at(i)                  , statType ));
    }
    /**
     * calculate the scores Ua, Ub and U
     */
    long U_Original = 0, U_Random = 0, U_Final;

    if (statType == Fold_Change || statType == T_Statistic  || statType == Z_Statistic)
    {
        //      Higher value is a winner
        for (size_t i = 0; i < genesPerSet /*totalGenes*/; i++)      // i   -  2x
        {   for (size_t j = 0; j < genesPerSet; j++)
            {   U_Random  +=  (valueRnd[i]  > valueOri[j]);// i en 2 set=Rnd, j in 1 set=Ori. count how many Ori are less than this Rnd
                U_Original+=  (valueOri[i]  > valueRnd[j]);// i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are less than this Ori
            }
        }
    } else
    if (statType == FDR_PValue || statType == PValue)
    {
        // Lower value is a winner
        for (size_t i = 0; i < genesPerSet; i++)
        {
            for (size_t j = 0; j < genesPerSet; j++)
            {   U_Random  +=  (valueRnd[i]  < valueOri[j]);// i en 2 set=Rnd, j in 1 set=Ori. count how many Ori are > than this Rnd
                U_Original+=  (valueOri[i]  < valueRnd[j]);// i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are > than this Ori
            }
        }
    } else { cout << endl << "ERROR. Statistic type not defined." << endl;  }

    U_Final = (U_Original < U_Random) ? U_Original : U_Random;

    /**
     * calculate z
     */
    double Zn, Zd, Z;
    Zn = U_Final - ((genesPerSet * genesPerSet) / 2);
    Zd = sqrt(
            (double) (((genesPerSet * genesPerSet
                    * (genesPerSet + genesPerSet + 1)))) / 12.0);
    Z = Zn / Zd;

    /**
     * Return 0/1/2
     * 2: p value < 0.01
     * 1: 0.01 < p value < 0.05
     * 0: p value > 0.05
     */
         if (fabs(Z) > 2.303)       return 2;
    else if (fabs(Z) > 1.605)       return 1;
    else                            return 0;
}

the same code but mixed with yours original code and with more comments.

int WilcoxinRST::work(const GeneSet &originalGeneSet , const vector<string>& randomGenes)
{
    size_t genesPerSet = originalGeneSet.geneCount();
    unsigned int totalGenes, tempScore;
    totalGenes = genesPerSet * 2;

    //vector<string> geneIDs;
    //vector<bool>   isOriginal;
    //vector<int>    rank;
    vector<double> valueOri(genesPerSet), valueRnd(genesPerSet);
    //vector<int>    score;
    /**
     * Fill the first half of the vectors with original gene set data
     */

    for (size_t i = 0; i < genesPerSet; i++)
    {
        //geneIDs.push_back( originalGeneSet.getMemberGeneAt(i)  );
        //isOriginal.push_back(true);

        valueOri[i]   =  fabs(expressionLevels.getValue( originalGeneSet.getMemberGeneAt(i) , statType ));
        valueRnd[i]   =  fabs(expressionLevels.getValue( randomGenes.at(i)                  , statType ));
    }
    /**
     * Fill the second half with random data
     */
    //for (unsigned int i = genesPerSet; i < totalGenes; i++) {
    //  geneIDs.push_back(randomGenes.at(i - genesPerSet));
    //  isOriginal.push_back(false);
    //  value.push_back(fabs(expressionLevels.getValue(geneIDs[i], statType)));
    //}
    //totalGenes = geneIDs.size();
    /**
     * calculate the scores
     */
        /**
     * calculate Ua, Ub and U
     */
    long U_Original = 0, U_Random = 0, U_Final;
    //for (int j = 0; j < genesPerSet; j++) // j in 1 set=Ori. count how many Ori are less than this Rnd
    //{
    //  U_Original += score[j];
    //}
    //for (unsigned int j = genesPerSet; j < totalGenes; j++) // j in 2 set=Rnd, count how many Rnd are less than this Ori
    //{
    //  U_Random += score[j];
    //}

    if (statType == Fold_Change || statType == T_Statistic  || statType == Z_Statistic)
    {
        //      Higher value is a winner
        for (size_t i = 0; i < genesPerSet /*totalGenes*/; i++)      // i   -  2x
        {   //tempScore = 0;
            //if (!isOriginal[i])  // i en 2 set=Rnd, j in 1 set=Ori. count how many Ori are less than this Rnd
            for (size_t j = 0; j < genesPerSet; j++)
            {   U_Random  +=  (valueRnd[i]  > valueOri[j]);// i en 2 set=Rnd, j in 1 set=Ori. count how many Ori are less than this Rnd
                U_Original+=  (valueOri[i]  > valueRnd[j]);// i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are less than this Ori
            }
            //} else
            //{
            //  for (unsigned int j = genesPerSet; j < totalGenes; j++)  // i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are less than this Ori
            //  {   if (value.at(i) > value.at(j)) {    tempScore++;        }
            //  }

            //}
            //score.push_back(tempScore);
        }

    } else
    if (statType == FDR_PValue || statType == PValue)
    {
        // Lower value is a winner
        for (size_t i = 0; i < genesPerSet; i++)
        {
            for (size_t j = 0; j < genesPerSet; j++)
            {   U_Random  +=  (valueRnd[i]  < valueOri[j]);// i en 2 set=Rnd, j in 1 set=Ori. count how many Ori are > than this Rnd
                U_Original+=  (valueOri[i]  < valueRnd[j]);// i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are > than this Ori
            }
            //} else
            //{
            //  for (unsigned int j = genesPerSet; j < totalGenes; j++)  // i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are less than this Ori
            //  {   if (value.at(i) > value.at(j)) {    tempScore++;        }
            //  }

            //}
            //score.push_back(tempScore);
        }

        //for (unsigned int i = 0; i < totalGenes; i++)
        //{   tempScore = 0;
        //  if (!isOriginal[i])
        //  {   for (int j = 0; j < genesPerSet; j++) {
        //          if (value.at(i) < value.at(j)) {  // Rnd i < Ori j increm U_Random
        //              tempScore++;
        //          }
        //      }

        //  } else {
        //      for (unsigned int j = genesPerSet; j < totalGenes; j++) { // Ori i < Rnd j. Increm U_Original
        //          if (value.at(i) < value.at(j)) {
        //              tempScore++;
        //          }
        //      }

        //  }

        //  score.push_back(tempScore);
        //}

    } else { cout << endl << "ERROR. Statistic type not defined." << endl;  }

    U_Final = (U_Original < U_Random) ? U_Original : U_Random;

    /**
     * calculate z
     */
    double Zn, Zd, Z;
    Zn = U_Final - ((genesPerSet * genesPerSet) / 2);
    Zd = sqrt(
            (double) (((genesPerSet * genesPerSet
                    * (genesPerSet + genesPerSet + 1)))) / 12.0);
    Z = Zn / Zd;

    /**
     * Return 0/1/2
     * 2: p value < 0.01
     * 1: 0.01 < p value < 0.05
     * 0: p value > 0.05
     */
    if (fabs(Z) > 2.303)
        return 2;
    else if (fabs(Z) > 1.605)
        return 1;
    else
        return 0;
}


Implement State Monad transformer in Haskell from scratch

Your implementation is correct. The additional comments are also welcome. I would write <*> without runState, but that's personal preference.

Keep in mind that you've re-implementend Control.Monad.Trans.State.Strict.StateT. For the lazy variant Control.Monad.Trans.State.Lazy.StateT, you would have to use lazy pattern matches in several places, so I assume you wanted to implement the strict variant.

To answer your question: no, we cannot implement Applicative (StateT s m) in terms of Applicative m. A Q&A on StackOverflow contains some hints, but let's reiterate them:

Suppose you have two values f, x and want y with the following types:

f :: StateT m s (a -> b)
x :: StateT m s a
y :: StateT m s b

We first remove the newtype:

f :: s -> m (s, (a -> b))
x :: s -> m (s, a)
y :: s -> m (s, b)

If our initial state is p, we have

f p :: m (s, (a -> b))
x   :: s -> m (s, a)

We want to use the s from f p in x to feed into x and the function to use the a. Now, let's suppose that m is an Applicative. This gives us only pure, fmap and <*> to work with. Let's try to write an expression that only uses those three functionspure, fmap and <*>:

z s = fmap (\(s', f') -> fmap (\(s'', x') -> (s'', f' x')) x s') (f s)

Let's check whether that implementation is sane. It's easier to deciper if we swap fmap's arguments:

x ~~> f = fmap f x
z s = f s                                   --  1
      ~~> (\(s', f') ->                     --  2
           x s'                             --  3
           ~~> (\(s'', x') -> (s'', f' x')  --  4
         )

We run f s to get our new state and our function.
Both are in m, so we use fmap to get in there.
We run x s' to get our new state again and our value.
Both are in m, so we use fmap yet again. However, we're using fmap inside fmap, which already tells us that we're not going to end up with a simple m ....

In (4), we end up with the correct new state s'' and the correct value f' x'. However, our type is s -> m (m (s, b)). Applicative does not provide any methods to reduce the number of m's, so we're stuck. We need to use join :: Monad m => m (m x) -> m x.

If we go back, we see that the problem arises due to x's type s -> m (s, a). If it was m (s -> (s, a)), we could simply use Applicative. Petr provides a detailed answer on SO.


Counting the frequency of certain entries in a list of JSON objects

The approach in your code is straightforward and hence easy to understand.

Nits:

use more of ES2015+ if you use some parts of it anyway - for example Map is handy here;
don't mix function and => notations - unless the former is absolutely required;
don't use array .map if you don't need the output array - to avoid garbage collection lags;

const getSectionFrequencyData = data => {
  const getSection = entry => /[a-z]+|$/.exec(entry.url || '')[0];

  const frequencies = new Map();
  for (const entry of data) {
    const section = getSection(entry) || 'home';
    frequencies.set(section, (frequencies.get(section) || 0) + 1);
  }

  const sorted10 = new Map(
    [...frequencies.entries()]
      .sort((a, b) => b[1] - a[1])
      .slice(0, 10)
  );

  return [
    ['sections', ...sorted10.keys()],
    ['frequency', ...sorted10.values()],
  ];
};


Shortest regex search and sum for integers

You can use map and sum. It good practice to use with statement when working with  a file.

with open('text.txt', 'r') as f:
    result = sum(map(int, re.findall(r'[0-9]+', f.read())))

print(result)


I agree with Anonymous that there isn't much to review here.
I would like to point out a few general things.
The db connection credentials are the type of thing that I'd put in a config.php file and include it where necessary.
$timezone is probably going to be useless in the longterm.  date_default_timezone_set() returns a boolean value to inform you of whether or not you have supplied a valid timezone.  Basically, once this tested once, there is no need to check the return value ever again (until it is changed, of course).
$dbCredentials = [
    "localhost", //server name
    "username",
    "password",
    database"database"
];

date_default_timezone_set("America/New_York");

Then just include the file and connect by unpacking the indexed array of credentials like this:
$con = new mysqli(...$dbCredentials);

Notice this is object-oriented syntax.  You should not be mixing styles.
When you are in a development environment (not a production environment), you may return raw error messages. In production, you must never provide raw error messages to users.
When checking for a failed connection, a falsey check (no function call) will be sufficient.  It is vital that you spell your connection variable correctly.
if (!$con) {
    die("Connection failed: " . $con->connect_error);
}

That said, an overarching refinement is to perform error handling elsewhere. See YourCommonSense's advice on error reporting.
session_start(); is usually something that you would put at the top of an include that is run before anything else.


Stop

This instruction is outright dangerous in any production code (assuming that code could be used in anything that ends up in the hands of users that don't understand what's happening when the VBE pops up). And because it's easy to forget about it and remove every instance of it everywhere, I usually reserve it for debugging only - for example:

CleanFail:
    Stop
    Resume CleanExit
    Resume
End Sub

When debugging, execution breaks at the Stop keyword, and then I can drag the yellow "next instruction" arrow to Resume and jump back at the error-causing line.

If you're going to be outputting an error message and stop execution, you might as well raise an error to do so. Runtime error 5 "Invalid procedure call or argument" is more or less analoguous to .NET's ArgumentException, which seems to be the most accurate existing error to throw/raise here - I'd do it like this:

Err.Raise 5, TypeName(Me), NULL_ERROR_TEXT

That will only PrintErrorMessage if the caller handles the runtime error though, which changes the way your code works. But it's more semantically correct I find.

Same here:

    Case Else
        '/ TODO: Error Handling
        Stop

The function received an invalid argument; there's an existing runtime error specifically for this: just use it!

Public Enum ComparisonOperator
    NotEqualTo = 0
    LessThan = 1
    LessThanOrEqualTo = 2
    EqualTo = 3
    GreaterThanOrEqualTo = 4
    GreaterThan = 5
End Enum

Every single enum value here has the same value is would have if an explicit value wasn't specified, and the values themselves are meaningless. Better leave 'em out and only specify explicit values when these values mean something or can be combined (and then they would be valued with powers of 2).

Objects are indeed not comparable. But not because they're objects - because in and by themselves, they don't specify how they should be compared. The .NET framework solved this problem by introducing a fairly simple interface, IComparable:

Option Explicit

Public Function CompareTo(ByVal other As Variant) As Integer
End Function

Given an object that implements this interface, your code would be able to evaluate all operators, assuming both operands are of the same type; so instead of systematically refusing to compare objects, you could instead raise an error that says something like "Both objects must be the same type and implement IComparable".

Private pOperator As ComparisonOperator
Private pRightValue As Variant

I've seen p used to mean "parameter". Not sure what it stands for here, as typically the Hungarian prefix would be m_ for module-scope variables.

I like to solve this problem like this:

Private Type TComparer
    Operator As ComparisonOperator
    RightValue As Variant
End Type
Private this As TComparer

And then you don't need prefixes anymore:

Public Property Let Operator(ByVal value As ComparisonOperator)
    this.Operator = value
End Property

Notice I'm using a general-purpose value parameter in property setters (let/set); this makes properties read consistently, and pretty much identical to modern VB.

Public Property Let RightValue(ByVal value As Variant)
    If IsNull(value) Then
        PrintErrorMessage NULL_ERROR_TEXT
        Stop
    ElseIf IsObject(value) Then
        PrintErrorMessage OBJECT_ERROR_TEXT
        Stop
    End If

    this.RightValue = value
End Property

Are you sure IsNull is doing what you're using it for here?

  The Null value indicates that the Variant contains no valid data. Null is not the same as Empty, which indicates that a variable has not yet been initialized. It is also not the same as a zero-length string (""), which is sometimes referred to as a null string.

  https://msdn.microsoft.com/en-us/library/office/gg278616.aspx

It's actually pretty hard to supply a Null value by accident to a required Variant parameter. I'm not saying the check isn't needed, just that it's rather uncommon in VBA code. I'm not even sure how one would manage to actually pass a null in there without explicitly specifying Null.

It's good that you're checking for Null. But then, why stop there? Why not check for vbEmpty? If one can pass Null, they could also pass vbEmpty... and how would you compare against vbEmpty?


"Stardust" 2D Gravity Simulator - Follow Up 1: The Planets

Btw I like the idea of the game/demo!

It would be nice to see a case where a binary star emerges.

Back to code review:

In Class CicleBody

 get mass () {
         return this.area * this.density;
 }

the this.area - did you intentianally wanted to hit the getter of area or perhaps will be better to use the internal this._area?

PhysicsBody class:

As naming goes, the usual convention is to name functions so they reflect what's going on in the code. In that context, I would have that as a function createVelocity() to indicate that in fact you're creating an object.

 get velocity () { // better name: createVelocityVector()
     return new Vector(this.vx, this.vy);
 }

That is important for the performance conscious programmers cause every extra new object or function call might have impact on the performance.

CircleSkin class:

class CircleSkin extends Skin {
    constructor (x, y, radius, color) {
        super(x, y, color);
        this.radius = radius;
        this.redraw(); // <------?!!
    }

It is not usual to have canvas work inside of a object constructor.
Normally you'd have the draw logic invoked by the render timer.
Normally as the JS games are implemented with two continuous timers:

1) core timer - this timer runs the game logic.

2) render timer - this timer runs every ~300 ms, reads the some shared data structure, updated by the core timer, and renders it to the canvas. This way you guarantee 30 fps and your game feels smooth and responsive.

redraw (resolution) {
        var r = this.radius;
        this.graphics.clear();
        this.graphics.f(this.color).dc(0, 0, r);
        //this.cache(-r, -r, r * 2, r * 2, resolution || 1);
    }
}

From the alone is not clear what are resolution and graphics.

graphics feels like enhanced canvas.context2d, if yes, in my opinion is better to pass it as parameter. This way you can easily reuse the code with different graphic context.

My version of that method would look something along the lines:

render(graphics) {
  var r = this.radius;
  graphics.clear();
  graphics.f(this.color).dc(0, 0, r);
}

You mentioned you are using EasyJS .. I am not familiar with that library but it cannot be too different than the above mentioned structure. Perhaps the library is implementing the timers for you and is providing you with this.variable for a canvas like object.

That's okay, however, I would recommend you to open the hood and read the code of the library - you will need to understand in order to be able to write code with good performance.

I wrote a review for a similar question, have a look : https://codereview.stackexchange.com/a/135326/111698.
Hope it helps you.

-- side note --

Ha-Ha on Utils.getRandomInt(0, innerWidth)
I think everyone has implemented a version of that in his code.
Perhaps, they could add that to the Math lib :)


Switch / Dictionary containing multiple values with same keys

Dictionary and switch are far from the same, even in your case.

As a general guideline I use a dictionary as a lookup mechanism and a switch as flow control.

As a lookup mechanism a switch is less efficient than a dictionary.

Maintenance wise, adding new values to a dictionary is not changing code per se. Modifying the dictionary will not cause a change to the code calling it. And a dictionary has a built in error check - you can't have the same key twice with different values.

However the switch is very much involved in program flow control. Therefore changing the switch code is higher risk than changing dictionary content.

Finally, using a dictionary decouples your data from the code that uses it. It makes the data re-usable. And you don't have duplicate switch code everywhere the data is used.


Passing arguments to a SendMail function referenced by addressOf operator

The System.Timers.Timer.Elapsed event needs a handling method with the signature sender As Object, e As ElapsedEventArgs. This means that any method which you want to assign this event to, by using the AddressOf operator has to have exactly this signature by the meaning of the type and order of the parameters.

Public Sub MailTimerElapsed(sender As Object, e As ElapsedEventArgs)
    ' the code which should be processed if the timer is elapsed
    ' should be either called here or be placed here
End Sub

If you plan to use the System.Timers.Timer without setting the SynchronizingObject property, you need to know that the event is raised on a ThreadPool thread, so interaction with a UI (at least with setting any value like assigning a value to a Text property of a TextBox) needs to be synchronized by your code.

Also, if the time needed to finish the codeexecution from the eventhandler exceeds the set Interval it will reentrant if the mentioned property is not set.

Read more: Timer class

These fields

Public UserMailId As String
Public UserPassword As String
Public HostName As String
Public HostPort As String

should better be properties instead of public variables. You could also consider to pass these values at calling the constructor, and make the fields Private.

You should get used to the NET style. This means calling methods which has been kept for downward compatibility like MsgBox should be avoided and replaced by the MessageBox.Show() method

Instead of placing the eventhandler for the Timer.Elapsed event inside the Details class you should place it in the calss where you create the timer object and call from inside the handler your desired mail sending method.


A fractal picture - John Zells graphics.py

(When) is it better to replace comments with longer descriptive variable and function names?

That's one of the finer arts of programming, and varies by language. Much of the time, code should be clear enough and variable names sensible enough that comments are rarely needed, except for in the important places like method docstrings (which should exist regardless).

Since Python is not a strongly-typed language, it needs a little bit of encouragement to add type information, but it can still be (kind of) done via PEP484. Doing this will further enhance your ability to understand the code without needing to rely on explanatory comments. For example (these are only educated guesses):

def brushes(win: GraphWin, center_x: int, center_y: int, brush_max_radius: float):

Note the underscore convention for Python variable names.

  Does this code make sense to you?

I mean... not really? But that's just because I don't understand the fractal algorithm.

Some of the variable names are not English - koordinat? Since most of your other names are English, you should make this English, too. Some people argue that English is the universal language of development. I'm less convinced, but at least you should be internally consistent.

brushes is a confusing name. A method name should be an action - perhaps draw_brushes.

Another trick to get shorter, but still understandable, variable names - drop redundant information. windowwidth is the only width in your code, and it's used right next to the place where it's called, so call it simply WIDTH (capitals because it's a constant).

  Would it be better off with comments?

Yes, definitely - but only comments that are useful.

A comment like this:

# spiral revolutions
spiral_revolutions = 10*pi

is useless. However, a comment like this is very important and useful:

"""
This is an implementation of the fractal algorithm xxx from chapter
yyy of Zells' Python Programming.

:param win: The window object to which the fractal will be drawn.
:param center_x: The x-coordinate of the fractal's origin, in window space.
:param center_y: The y-coordinate of the fractal's origin, in window space.
:param brush_max_radius: The maximum radius of the circles constituting the fractal.
"""


Nested while loop for getting db data. Timing out at random times because of the PHP. Any way to make this more efficient?

First of all, does you tables have indexes? If you run the queries with EXPLAIN on MySql console (for example EXPLAIN SELECT DISTINCT confName, tableName FROM conferences WHERE enabled='1' ORDER BY id DESC), does it show that it uses indexes?

I'm not sure that it's a real performance issue or not but the current mysql_free_result calls doesn't free all resources, just the last one because the code runs lots of queries in loops. You should put these calls immediately after the last use of the resource, for example:

while (...) {
    ...
    while($winner = mysql_fetch_array($catWinner)) {
        echo "<li>".$winner['place']. " ".$winner['name']."</li>";
    }
    // free $catWinner at the end of every iteration
    mysql_free_result($catWinner);
}

I don't think that (generally) a good design to create separate tables for (probably) the same type of records. Instead of creating separate tables for every conference, consider creating only one table. It should have a conferenceId attribute as well as the conferences table should have a conferenceId too (instead of the tableName attribute). (Don't forget the foregin keys.)

If I'm right, this conferenceId could be in the event table and you don't need separate conference tables at all. (Feel free to post your database schema too. It could be worth a new question.)

Using sprintf does not make any sense here and in the similar calls:

$getExistingEvent = sprintf("SELECT DISTINCT event FROM " . $conference['tableName']);

It's the same as

$getExistingEvent = "SELECT DISTINCT event FROM " . $conference['tableName'];

Or it could be

$getExistingEvent = sprintf("SELECT DISTINCT event FROM %s", $conference['tableName']);

where sprintf does the including/formatting.

Edit:

I'd create the following indexes:

ALTER TABLE `conferences` ADD INDEX `enabled`(`enabled`);
ALTER TABLE `2012rlc` ADD INDEX `event_id`(`event`);

I hope it helps.


Perhaps instead of an ini file, a JSON would suit the purpose better. I've seen this multiple times, even in large, well-known PHP frameworks.

You can find a lot about decoding JSON from the docs. Here's a little blog post about handling decoding. And here's a StackOverflow question regarding the external file.

Also, if you keep the same class, I suggest passing Configuration through the constructor to practice dependency injection.

public function __construct(Configuration $ini) {
    $this->host = $ini->getField('Database', 'host');
    $this->user = $ini->getField('Database', 'user');
    $this->pass = $ini->getField('Database', 'password');
    $this->dbname = $ini->getField('Database', 'name');
}


plz help optimize the small code snippet, VS2010 profiling chart provided

You're doing way more iterations than are necessary.. you don't need 2 enumerables of ints just to do this, that's a lot more heap references when all your need are 2 integers right on the stack, and a nested for loop:

int upperLimit = length - 1;
int lowerLimit = totalWeight[thisBlock].Num;
List<string> recentBlock = RecentBlock(length - 1, reelLayout);
List<string> stringResults = new List<string>();

for(int upper = 1; upper < upperLimit; upper++)
{
  for(int lower = 1; lower < lowerLimit; lower++)
  {
    if (upper + lower = length)
    {
      stringResults.Add(
        string.Join(",", recentBlock.Skip(length - 1 - upper)) + "," +
        string.Join(",", splits.Take(lower)));
    }
  }
}

return stringResults;

also instead of doing the stringResults.Add you could just yield return the string right there if you wanted to allow delayed execution.

Remember, just because we now have tuples and all the happy linqiness, they can be used to simplify complex things, though sometimes they just make operations more complex. If performance is important, study up on what goes on underneath the linq before throwing it around too much.


Are you wanting to direct this to a specific application? It's usually better to send WM_KEYDOWN and/or WM_KEYUP using the SendMessage function.

If not, then I would suggest using the keybd_event function. You can find some good examples on Code Project


Is there a better way to assign two variable to two others conditionally?

One alternative, note how we must store the bool result to ensure identical semantics (otherwise you risk calling tag.Equals twice... which in addition to performance considerations might change its result between calls or have side effects!)

bool swap = tag.Equals(pathBallTagName);
GameObject newBall = swap ? other.gameObject : gameObject;
GameObject pathBall = swap ? gameObject : other.gameObject;

Alternatively one could implement a Swap function elsewhere:

GameObject newBall = other.gameObject;
GameObject pathBall = gameObject;
if (tag.Equals(pathBallTagName)) Swap (ref newBall, ref pathBall);


Simplify

This could be written a lot simpler.
For each number until binaryLimit,
you could iterate over the bits using bit shifting,
and moving the current index in the array,
printing values when the bit is set.

private static void printAllSubsets(int... arr) {
    int size = arr.length;
    int binaryLimit = (1 << size) - 1;

    for (int i = 1; i <= binaryLimit; i++) {
        int index = size - 1;
        int num = i;
        while (num > 0) {
            if ((num & 1) == 1) {
                System.out.print(arr[index]);
            }
            index--;
            num >>= 1;
        }
        System.out.println();
    }
}

Calculating powers of 2

Note that Math.pow takes and returns double. Converting between types is ugly, and what's worse, floating point math is fraught with problems in general. Fortunately, for calculating powers of 2, a clean and blazingly fast alternative is to use bit shifting, as demonstrated in the code above.

Naming

subset is a poor name for a void method that prints subsets of elements of an array.

Usability

As there is no punctuation between elements as they are printed,
this method will not be very useful for larger arrays,
or arrays where values have more than one digit.

Java conventions

Capitalized variable names are normally used for constants,
never for local variables.

Method decomposition

Your implementation is very long,
and could have been split to smaller pieces that are easier to read and test individually.


A simple C WinAPI program for terminating processes via process image names

There is a subtle bug:
Process32First(snapshot, &entry)

already fills entry with the information about the first process in the snapshot. Your code misses that entry because Process32Next() is called immediately. The loop structure should be
if (Process32First(snapshot, &entry) == TRUE) {
    do {
        // ... do something with `entry`...

    } while (Process32Next(snapshot, &entry) == TRUE);
}

instead. Other things that come into my mind:

If the program is called with the wrong number of arguments then the error/usage message should be printed to the standard error and the program should terminate with a non-zero exit code, e.g. EXIT_FAILURE.
The return value of CreateToolhelp32Snapshot() is not checked.
PROCESS_ALL_ACCESS is not needed in the call to OpenProcess, only PROCESS_TERMINATE.
The return values of OpenProcess() and TerminateProcess() are not checked. I would expect a diagnostic message if they fail. In particular, TerminateProcess() and CloseHandle() should only be called if OpenProcess() succeeded.
It may be a matter of taste, but == TRUE can be omitted when checking a boolean condition.
As a user of this tool I would expect some feedback to see if a matching process was found, and how many processes were killed.


The optimization you are looking for is very simple:
Ask your self - what do I really need to keep?
The answer: only the password guess I am currently checking.
There is no need to store all the old guesses, so there is no need for files or huge lists.
All you really need is one string you will keep updating.
To visualize this, think of your string as a growing number, with each letter being a base 58 digit.
Now. all you really need is to do a +1 on the first digit, checking for carry and updating following digits if needed just like usual addition.
Unfortunately, Python strings don't allow assignment by index, but they do support slicing.
Here is a function that would generate sequential passwords running through all the letters and growing the length as needed (one password per call!):
def make_next_guess(guess):
    carry = 1
    next_guess = guess

    for i in range(len(guess)):
        cur_char = ord(guess[i]) + carry
        if cur_char > ord('z'):
            cur_char = ord('A')
            carry = 1
        else:
            carry = 0

        next_guess = next_guess[:i] + chr(cur_char) + guess[i + 1:]
        if carry == 0:
             break

    if carry = 1:
        next_guess += 'A'

    return next_guess

With this you can use one loop for all the possibilities up to the maximum length:
guess = 'A'

for _ in range(58 ** 14): #password maximum length 14 and there are 58 characters that can be used

    if hash_password(guess) == secure_password:
        print(guess)
        break

    guess = make_next_guess(guess)


Tag specific Git commits based on commit message contents

If I had to write a "single-use" quickie command, I would write it like this:

while read version commit; do
    git tag -a v0.0.$version -m "Tag v0.0.$version" $(git rev-parse :/'Commit '$commit)
done

Then, as the script awaits input, type:

1 5
2 10
^D

In contrast to your parallel arrays, the main advantage of this approach is that each line constitutes a commit-version pair.


Python Rock-Paper-Scissors via a class to handle the game

I think it makes sense to use dictionaries to store values for win/tie/loss:

    def __init__(self):
        """
        Initialize the variables for the class
        """
        self.options = {'rock': 0, 'paper': 1, 'scissors': 2}
        self.outcome_count = {
            "tie": 0,
            "win": 0,
            "loss": 0,
        }

This makes check_win a bit more "mechanical" since you can now refer to the outcomes by name and by looking things up in static data, instead of needing a bunch of if/else:

    def check_win(self, player, opponent):
        """
        Check if the player wins or loses.
        :param player: Numeric representation of player choice from self.options
        :param opponent: Numeric representation of computer choice from self.options
        :return: Nothing, but will print whether win or lose.
        """

        result = ["tie", "win", "loss"][(player - opponent) % 3]

        self.outcome_count[result] += 1

        outcome_message = {
            "tie":  "The game is a tie! You are a most worthy opponent!",
            "win":  "You win! My honor demands a rematch!",
            "loss": "Haha, I am victorious! Dare you challenge me again?",
        }
        print(outcome_message[result])

though of course it ends up making print_score less self-explanatory:

    def print_score(self):
        """
        Prints a string reflecting the current player score.
        :return: Nothing, just prints current score.
        """
        wins   = self.outcome_count["win"]
        losses = self.outcome_count["loss"]
        ties   = self.outcome_count["tie"]
        print(f"You have {wins} wins, {losses} losses, and {ties} ties.")

Lastly, I think that the run_game loop can be made slightly clearer by writing instead

        while True:
            userchoice = input("Choices are 'rock', 'paper', or 'scissors'.\nWhich do you choose? ").lower()
            if userchoice in self.options.keys():
                break
            print("Invalid input, try again!")

I find an explicit "early-exit" with no else to be easier to follow [note that the condition is not inverted, which I think helps for clarity in this case] though this could be jarring if it's not conventional for the larger codebase.