Immutable binary search tree using Scala

I think it would be an improvement to define an empty element. Currently you have no way to represent an empty collection. But that is required if you would want to integrate your data structure with scala collections.

(In scala collections, you usually build up an immutable data structure like a Set or Map by starting with the empty element and adding elements. The apply methods defined in the companion objects are just convenience methods)

Defining an empty element will also simplify your code a lot. For example: you won't have to use Option for left and right, but can just use the empty value if e.g. left does not contain elements. For iteration for example you don't have to check whether left or right is empty by checking for None, but just call the method on the child.

In the simplest case this will look something like this:

object BST {
  def empty[T](implicit c:(T,T) => Int) : BST[T] = new EmptyBST(c)
}

sealed abstract class BST[T] {
  // abstract: whatever methods you want to support
}

case class EmptyBST[T](c:(T,T) => Int) extends BST[T] {
  // trivial implementation of all methods for an empty BST
}

case class NonEmptyBST[T](left:BST[T], right:BST[T], value:T, c:(T,T) => Int) extends BST {
  // non-trivial implementation of all methods for the non-empty case
}

Another thing: using (T,T) => Int is perfectly fine for educational purposes. But if you want this to match the style of other scala collections, you should use scala.math.Ordering. There are already predefined orderings and some utility methods to create orderings for composite objects like tuples.

For the traversal, I would not return a List[T] of all elements but instead just implement the Traversable[T] trait by defining a foreach method for each traversal order. That is much more efficient in case the user is not interested in everything but just the first few elements. And if the user wants a List[T] he can always make one by calling .toList. Traversal using foreach uses side effects internally, but for the end user these are not observable, so it's OK.


Some notes:

I think the LINQ version would be more readable if you extracted a variable for the collection. Something like:

var serials = /* the whole LINQ query here */

Items.Clear();
Items.AddRange(serials);

The LINQ version might be more efficient if there were lots of widgets, because Intersect() uses hashing to achieve O(n+m) time complexity, while your imperative code is O(n·m).
You don't need ToArray() in your LINQ version. (Assuming Items is List<string>.)
I really don't think the string "No relevant widgets found." should be the default value if the list is empty. List of widget serial numbers should contain widget serial numbers, nothing else. And you should separate your business logic and presentation.

With the mentioned changes, I think the LINQ version will be more readable, primarily because Intersect() explains what you want to do better.

Also don't forget that you don't have to use only LINQ or only imperative code, you can combine the two in a single method (e.g. improve the imperative approach by using Intersect()).


Regular Expression for text that validates IPV4 or Hostname followed by a port number eg: 127.0.0.1:8080 or localhost:8080

While this appears to work, there are a few things about it that are not very clear.

Reconsider the use of regex

Rather than using a regex, for the numeric ranges in particular, it may make more sense to capture those values and check them with Java statements.  It would certainly reduce the size and complexity of the regex.

Document non-obvious constraints

The current regex includes a 1,253 count, the origin of which is decidedly non-obvious.  RFC 1035 and RFC 822 are both obvious candiates for an authoritative source, but this regex does not conform to either of those.


You could make your life a lot easier if you used the fact that Python allows you to give custom classes built-in behavior. This allows you to define classes for which e.g. a + b is defined or, as in this case for x in obj.

The way Python allows this is via so called dunder (short for double-underscore) or magic methods. These are special method names which get invoked under certain circumstances.

If you ask Python to iterate over an object obj, it calls the method obj.__iter__ (or at least tries to). If you write a + b it first calls a.__add__(b) and if that does not work b.__radd__(a).

A linked list is predestined to have this method:

class Linked(object):
    def __init__(self):
        self.head = None
        self.tail = None

    def add(self, data):
        temp = Node(data, None, None)
        if self.head is None:
            self.head = self.tail = temp
        else:
            self.tail.next = temp
            temp.prev = self.tail
            self.tail = temp

    def __iter__(self):
        current = self.head
        while current is not None:
            yield current.data
            current = current.next
        raise StopIteration

Together with a greatly simplified Node class:

class Node(object):
    def __init__(self, data, prev=None, next=None):
        self.data = data
        self.prev = prev
        self.next = next

    def __repr__(self):
        return repr(self.data)

This already allows simple things like iterating:

l = Linked()
l.add(1)
l.add(3)
print(list(l))
# [1, 3]
for x in l:
    print(x)
# 1
# 3

The other methods can then take advantage of the fact that it is easy to iterate over the object:

class Linked(object):
    def __init__(self, data=None):
        self.head = None
        self.tail = None
        if data is not None:
            for x in data:
                self.append(x)

    def append(self, data):
        if self.head is None:
            self.head = self.tail = Node(data)
        else:
            node = Node(data, self.tail)
            self.tail.next = node
            self.tail = node

    def __iter__(self):
        current = self.head
        while current is not None:
            yield current
            current = current.next

    def find(self, data):
        for x in self:
            if x.data == data:
                return x
        return None

    def __len__(self):
        return sum(1 for _ in self)

    def __repr__(self):
        return repr(list(self))

    def remove(self, data):
        x = self.find(data)
        if x is None:
            return
        if x is self.head:
            if x is self.tail:
                self.head = self.tail = None
            else:
                self.head = x.next
                self.head.prev = None
        elif x is self.tail:
            x.prev.next = None
        else:
            x.prev.next = x.next
            x.next.prev = x.prev

Here I modified the __iter__ method to yield the nodes, not just the data, removed the manual raising of StopIteration (it is not needed and actually deprecated in Python 3), added a __len__ and __repr__ method for convenience (the latter gets called when you call repr(obj) or when you just enter the variable name in an interactive session), renamed add to append (to mirror the normal list interface), added an optional argument to the constructor to ease initializing a linked list from an iterable and used the optional arguments of Node to make the append method slightly easier to read.

Also note that your class is actually a doubly-linked list, since each node has a pointer to the previous and the next node.


build a string based on user's input python

You can take _type and _link as keyword arguments, and so would simply your code. This can be as simple as func(_type=None, _link=None). However you may want to only take them if they are keyword arguments, and that method would allow them to be passed as normal positional arguments. To do this you can use prepend * to the function to do this. And so you can use func(*, _type=None, _link=None).


Extracting Linux configuration information using Bash and Perl

[...] there's a lot of perl and I'm wondering if it could be done better.

When you need to process the output of multiple commands,
as in your example acpi, free, amixer, xbacklight,
it's acceptable to call a perl for each.

The part needs improvement the most is the loop over the network interfaces,
where you call iwconfig $interface and ifconfig $interface repeatedly to extract different part of the output into different variables.
It would be better to rewrite this to call ifconfig and iwconfig just once per interface.

At a glance, it seems to me that everything you do with Perl, you could also do with awk, which might be slightly lighter.

If performance is extremely important,
you could parse the output of all the commands with a single Perl or awk process, by carefully adding some marker lines in between commands, something like this:

marker='==== section ===='

{
    acpi -b
    echo $marker

    free -m
    echo $marker

    amixer get Master -c 1
    echo $marker

    xbacklight
    echo $marker

    iwconfig
    echo $marker

    ifconfig
} | perl -ne '...'

This way the number of processes spawned will be drastically reduced,
and the performance difference will be noticeable.


Your biggest problem is the first line:

column = (sum(1 for line in open(file) if line.strip("\n")))*[0]

Opening the file twice is a bad idea for performance, probably much worse than not knowing how large of a list to allocate.  Furthermore, that statement only allocates one element per non-empty line, whereas the counter_row counts every line in the file.  So, the code would crash with an IndexError if there are any empty lines.

The inner for loop is just a complicated way to do indexing.

Assuming that you want empty lines to be represented by 0, you could write:

column = []
with open(file) as f:
    for line in f:
        row = line.strip("\n")
        column.append(row.split(",")[n_column] if row else 0)

If you don't need to test for empty lines, then you could just write:

with open(file) as f:
    column = [line.strip("\n").split(",")[n_column] for line in f]

You should consider using the csv module, though, which can handle CSV quoting properly.


Poker deck class /w generator function and list comprehensions

[card for card in Deck.generator(…)] could be written as list(Deck.generator(…)).

Better yet, use itertools.product():

self.cards = [
    {'suit': suit, 'rank': rank}
    for suit, rank in itertools.product(xrange(4), xrange(13))
]

In Python 2, you should be using xrange() rather than range().

It's probably worth defining a Card class.  At some point, you'll want to have suits that are named rather than numbered, and ranks A, J, Q, K rather than 0..12.

To deal multiple cards, you can slice the list instead of popping one card at a time:

def deal(self, n):
    hand = self.cards[-1 : -n-1 : -1]
    self.cards = self.cards[: -n]
    return hand


Apply arbitrary action during recursive generator function

Good things:

all lines terminated with a semi-comon
strict equality used when checking for objects

I would suggest using const by default since none of the variables/functions get reassigned. If you determine reassignment is necessary then use let. This will help avoid accidental re-assignment.

And is the variable naming oclone Hungarian notation? If so, why not use it for all variables instead of cloned variables?


Your code will work for one level deep working directories such as:

servername/admin/index.php
servername/sample/test.php

However, go one level deeper and it will not work. If I have servername/one/two/index.php, I will get a servername/two. It is because the basename() returns the working folder of the file.

I find this code useful for common applications:

$request = explode('/', $_SERVER['SCRIPT_NAME']);
array_pop($request);
echo $_SERVER['SERVER_NAME'] . implode('/', $request);

It makes use of server's script name. Given the sample servername/one/two/index.php, it will return /one/two/index.php. We then remove the script from the directory using explode and popping the result, and then finally concatenating it to the server name.


Naive prime finder, unexpected behavior in Python

Duncan's explanation is incorrect. This isn't my best piece of writing - bear with me.

First lets deal with n < 2 and n == 2 or n == 3:

It is true that they let a lot more input go past them than they stop. But they don't account for the difference in time.

Even the old definition has n < 2 and n == 2.
The time spent on this part of the function is very insignificant compared to that spent in the rest of the function.

Next n%2 == 0 or n%3 == 0:

Again n%2 == 0 is in the old definition also.
n%3 == 0 is the first check in old's for loop
The time spent on this part of the function is also insignificant compared to that spent in the rest of the function.

I could've clubbed this with the previous section but didn't for the following reason:

These checks work on 4 out of every 6 input numbers. And 4 > 6-4. But is that the way to look at it? If say they'd worked on 3/6 [As in the case of old] are these checks useless? If say they'd worked on 2/6 should they be avoided? No.

By doing one(or two) comparison(s) on 6 inputs, they stop 2 from reaching the work horse of the code - the loop - that does most of the work. That's not to be avoided!

Also, by imposing additional constraints on the input that reaches the loop, the loop itself has been made faster! Knowing that no multiple of 3 enters the loop, you don't test divisibility of n by any other multiple of 3. Don't forget your main idea behind moving from old to new!

Faster loop + lesser numbers reaching loop should make new faster than old.

How much faster exactly?

I mentioned "lesser numbers reaching loop" being good only as a general guideline. It doesn't help much here because : In old 3,5,7,9... enter the loop, and in new 5,7,11,13... enter the loop. But in old 3,9... get stopped at the first check of the for loop. So only faster loop is important.
new's loop jumps in steps of 6 but old's jumps in steps of 2. So is new 3 times faster than old? No. At every step new does 3 comparisons - one for the while loop condition and two inside the loop. old does 2 - one at for loop condition and one inside the loop. So, new is (6/3) * (2/2) = 2 times faster than old.

So far I've only been explaining why new should be faster. Finally I'll address your question of why this isn't observed:

for loops are much faster than while loops. python doesn't know how i is going to change inside while. So the while loop's condition check is like any other comparison. On the other hand for loop's condition check is highly optimised. Henceforth lets assume that for loop's condition check doesn't count as a comparison.

Then old's time/new's time will be

6/3 * 2/2 = 2 if both use while
6/2 * 1/2 = 1.5 if both use for
6/2 * 2/2 = 3 if old used while and new used for
6/3 * 1/2 = 1 if old used for and new used while

That still means that old and new should be (at least approximately) equally fast. This is where I was stumped. I had to resort to experimenting to figure this out. The reasons for this not occurring, as it turns out, are

All the unnecessary arithmetic (*6) in the while loop
while i*6 < sqr+1: Here sqrt is a floating point number. As it turns out float comparison is costlier than int comparison. while i*6 < int(sqr+1) isn't good either. You should use sqrp1 = int(sqr+1); while i*6 < sqrp1

Note that the ratios provided are from rough calculations and far from being accurate - there are so many more things to consider. One major assumption is that time spent in the loops is much larger than time spent at base case checks - not true if all your input are multiples of 2.

To summarise, the reasons for new being slower, despite being expected to be faster, are:

Usage of while instead of for (this is not as important as the other two)
Unnecessary arithmetic inside while
Usage of float comparison instead of int comparison in while condition check.

The code given below illustrates some of the points made here.

import math, timeit

def is_prime_new_slowest(n):
    if n < 2: return False
    if n == 2 or n == 3: return True
    if n%2 == 0 or n%3 == 0: return False
    sqr = math.sqrt(n) #This is insignificant as it is outside the loop
    if sqr == int(sqr): return False
    sqrtp1 = sqr + 1 #Note that sqrtp1 is a float
    i = 1
    while i*6 < sqrtp1: # Comparison of floats adds some time
        if n % (i*6-1) == 0 or n % (i*6+1) == 0: return False #Unnecessary arithmetic
        i += 1
    return True

def is_prime_new_slow(n):
    if n < 2: return False
    if n == 2 or n == 3: return True
    if n%2 == 0 or n%3 == 0: return False
    sqrtp1 = int(math.sqrt(n) + 1)
    i = 6
    while i < sqrtp1:
        if n % (i-1) == 0 or n % (i+1) == 0: return False
        i += 6
    return True

def is_prime_new_fast(n):
    if n < 2: return False
    if n == 2 or n == 3: return True
    if n%2 == 0 or n%3 == 0: return False
    sqrtp1 = int(math.sqrt(n)+1)
    for i in xrange(6, sqrtp1, 6):
        if n % (i-1) == 0 or n % (i+1) == 0: return False
    return True

def is_prime_old_slow(n):
    if n < 2: return False
    if n == 2: return True
    if n%2 == 0: return False
    sqrtp1 = int(math.sqrt(n) + 1)
    i = 3
    while i < sqrtp1:
        if not n%i: return False
        i += 2
    return True

def is_prime_old_fast(n):
    if n < 2: return False
    if n == 2: return True
    if n%2 == 0: return False
    sqrtp1 = int(math.sqrt(n)+1)
    for i in xrange(3, sqrtp1, 2):
        if not n%i: return False
    return True

def sundaram3(max_n):
    numbers = range(3, max_n+1, 2)
    half = (max_n)//2
    initial = 4
    for step in xrange(3, max_n+1, 2):
        for i in xrange(initial, half, step):
            numbers[i-1] = 0
        initial += 2*(step+1)
        if initial > half:
            return [2] + filter(None, numbers)

i = sundaram3(10**6)[-1]

print "Input: largest prime less than 10^6, No. of runs: 25000"
print "new slowest:", timeit.timeit('is_prime_new_slowest(i)', setup="from __main__ import is_prime_new_slowest, i; import math", number=25000)
print "new slow:", timeit.timeit('is_prime_new_slow(i)', setup="from __main__ import is_prime_new_slow, i; import math", number=25000)
print "new fast:", timeit.timeit('is_prime_new_fast(i)', setup="from __main__ import is_prime_new_fast, i; import math", number=25000)
print "old slow:", timeit.timeit('is_prime_old_slow(i)', setup="from __main__ import is_prime_old_slow, i; import math", number=25000)
print "old fast:", timeit.timeit('is_prime_old_fast(i)', setup="from __main__ import is_prime_old_fast, i; import math", number=25000)

print "\nInput: range(1000000), No. of runs = 1"
print "new slowest:", timeit.timeit('for i in xrange(1000000): is_prime_new_slowest(i)', setup="from __main__ import is_prime_new_slowest; import math", number=1)
print "new slow:", timeit.timeit('for i in xrange(1000000): is_prime_new_slow(i)', setup="from __main__ import is_prime_new_slow; import math", number=1)
print "new fast:", timeit.timeit('for i in xrange(1000000): is_prime_new_fast(i)', setup="from __main__ import is_prime_new_fast; import math", number=1)
print "old slow:", timeit.timeit('for i in xrange(1000000): is_prime_old_slow(i)', setup="from __main__ import is_prime_old_slow; import math", number=1)
print "old fast:", timeit.timeit('for i in xrange(1000000): is_prime_old_fast(i)', setup="from __main__ import is_prime_old_fast; import math", number=1)

Output on my machine:

Input: largest prime less than 10^6, No. of runs = 25000
new slowest: 7.37190294266
new slow: 4.19636297226
new fast: 3.49502682686
old slow: 6.08556985855
old fast: 4.03657603264

Input: range(1000000), No. of runs = 1
new slowest: 21.5607540607
new slow: 13.8396618366
new fast: 12.3734707832
old slow: 20.0376861095
old fast: 14.1358599663

Note that for - while deterioration becomes less important as the number of comparisons inside the loop reduces [old - one comparison - time goes from 14 to 20, new - two comparisons - 12.3 to 13.83]. This is expected because 1 comparison becoming 2 has a greater effect on final time than 10 comparisons becoming 11. This is why while-for performance difference generally doesn't matter in real life.


Ruby methods to enable and disable attributes

How about:

def toggle_attribute
  statement1
  @response = yield(
    param1: param1value,
    param2: param2value
  )
  statement2
end

def disable_attribute
  toggle_attribute { |params| Client::Service.disable_attribute(params) }
end

def enable_attribute
  toggle_attribute { |params| Client::Service.enable_attribute(params) }
end

If you want to be more succinct, you could:

def toggle_attribute(method_name)
  statement1
  @response = Client::Service.send(method_name,
    param1: param1value,
    param2: param2value
  )
  statement2
end

def disable_attribute
  toggle_attribute(:disable_attribute)
end

def enable_attribute
  toggle_attribute(:enable_attribute)
end

And if you want to really impress your friends, you could write:

def toggle_attribute(method_name)
  statement1
  @response = Client::Service.send(method_name,
    param1: param1value,
    param2: param2value
  )
  statement2
end

def method_missing(method_name, *args)
  %i[disable_attribute enable_attribute].include?(method_name) ?
    toggle_attribute(method_name) : super
end


Commenting on this section:

; test-data mocks fetching a url by returning the string of a random int
(defn test-data [_] (str (rand-int 100)))

(def pages> (chan 1))
(pipeline 4
          pages>
          ; add the fetched page to the object getting passed around
          (map (fn [{:keys [url] :as obj}]
                 (conj obj {:page (test-data url)})))
          db-objs>)

In real-life, test-data will either do blocking I/O or be asynchronous.
Therefore, you should use pipeline-blocking or pipeline-async instead, otherwise you'll exhaust the "go thread pool".

Commenting on this part:

(go-loop []
  (let [{:keys [id scraped]} (<! selections>)]
    (test-append [id :vals] scraped))
  (recur))

You should account for the fact that the selections> channel may close, in which case the object will be nil and you should stop the loop.

(go-loop []
  (when-let [{:keys [id scraped]} (<! selections>)]
    (test-append [id :vals] scraped)
    (recur)))

Commenting on this part:

(doseq [[id data] @test-db] (go (>! db-objs> (conj data {:id id}))))

Because go is asynchronous, this consists of putting all the objects in test-db at once into the processing pipeline, which potentially consumes a lot of memory. Core.async channels are designed to give you back-pressure, you should use it.

How about instead:

(go (doseq [[id data] @test-db] (>! db-objs> (conj data {:id id}))))

Which you can express at a higher-level using onto-chan

(onto-chan db-objs (map (fn [data] (conj data {:id id})) @test-db) false)


From looking a little into this

You derive mediaContentURL through response.responseXML and title through xml, I would stick in both cases to xml
As you guessed, your approach to getting the mediaContentURL is pretty terrible.
Use getElementsByTagName and attributes, do not hardcode array indexes
Do not use console.log in production code

I would use something like this:

function getItemTitle( xml , itemNumber )
{
  //Skip the title number of the playlist
  return xml.getElementsByTagName('title')[itemNumber+1].textContent
}

function getItemURL( xml , itemNumber )
{
  return xml.getElementsByTagName('content')[itemNumber].attributes.getNamedItem('url').value;
}


Would you write the whole procedure differently?

Absolutely. In it's current form, it does far too much stuff and (at least in my opinion) is not really flexible enough. Every time you try to add something (e.g. other card patterns, loading patterns from a file, change the card border, ...) the function will just get more and more bloated.

Actually, I'd implement it in a class CardPrinter. This way, you can transfer state (e.g. card patterns) between calls in a nicely, encapsulated way. Also, I'd split the functionality into multiple member functions, so it's easier to reason about them.

  (paraphrasing:) How would you handle multiple patterns?

For patterns as simple as these, I'd probably not bother to encode them in any special format. Just an array of lines is fine (unless you're programming under heavy memory constraints).

These patterns can be set statically, loaded from somewhere or even generated dynamically. Choose what fits your circumstances best! E.g. loading from a file could allow for different patterns, allowing for customization.

  Example:

struct CardPattern {
    std::vector<std::string> lines;
};

class CardPrinter {
    std::vector<CardPattern> patterns;
    std::string delimiter_left;
    std::string delimiter_right;
    std::string delimiter_top;
    std::string delimiter_bottom;
    size_t internal_width;

public:
    CardPrinter(const std::vector<CardPattern>& pats, size_t w = 13, std::string del_left = "|", std::string del_right = "|", std::string del_top = "-", std::string del_bottom = "-")
            : patterns(pats), delimiter_left(del_left), delimiter_right(del_right), delimiter_top(del_top), delimiter_bottom(del_bottom), width(w - del_left.length() - del_right.length()) {
    }

    void print(const Carta& card, std::ostream& stream = std::cout) {
        stream << get_card_visual(card);
    }
private:
    std::string get_card_title(const Carta& card) {
        auto nome_semi = create_semi(card.seme);
        auto nome_valore = create_nome_valore(card.valore);

        return nome_valore + " " + nome_semi;
    }

    const CardPattern& get_card_pattern(const Carta& card) {
        // assuming pattern exists for that value
        return patterns[card.valore];
    }

    std::string format_line(const std::string& line) {
        // just cut off parts that are too long
        // if too short, fill rest with spaces (could be changed, e.g. center text in that case)
        auto visible_part = line.substr(0, internal_width);
        auto filler = std::string(internal_width - visible_part.length(), ' ');

        return delimiter_left + visible_part + filler + delimiter_right + "\n";
    }

    std::string format_card_pattern(const CardPattern& pattern) {
        auto formatted = std::string("");

        for(auto& line : pattern.lines) {
            formatted += format_line(line);
        }

        return formatted;
    }

    std::string format_top() {
        auto top = std::string();
        while(top.length() < internal_width) {
            top += delimiter_top;
        }

        return format_line(top);
    }

    std::string format_bottom() {
        auto bottom = std::string();
        while(bottom.length() < internal_width) {
            bottom += delimiter_bottom;
        }

        return format_line(bottom);
    }

    std::string get_card_visual(const Carta& card) {
        return format_top() + format_line(get_card_title(card)) + format_card_pattern(get_card_pattern(card)) + format_bottom();
    }
};

// Usage example
auto patterns = /* up to you, e.g. */ load_patterns();
auto printer1 = CardPrinter(patterns);
auto printer2 = CardPrinter(patterns, 15, "::", "::", "=", "=");

auto cards = /* get some cards */;
for(auto& card : cards) {
    printer1.print(card);
    printer2.print(card);
}


Two AngularJS controllers for camera actions

Looks ok, but here are some suggestions.

Your picture configuration looks the same for both controllers. You could move that out to an angular constant/value. If you anticipate the API mutating that config object, you can always shallow-copy them with Object.assign.

Next, proceed with your service. I'd move everything into it. All your controller has to do is call the API and receive the data URL. Move the ionic popup warning into the service as well for a centralized handling of the popup.

Another thing is the use of $rootScope. It's a quick way to share values, but like globals, $rootScope is modifiable everywhere. Your app is depending on data that may or may not be there and depends on changes whose origins you may not know. For small apps, that's fine as two-way binding is really handy but just in case your app becomes big, you might consider moving off data into a service/factory to draw a line between data and presentation.

.value('PICTURE_SETTINGS', {
  quality: 75,
  destinationType: Camera.DestinationType.DATA_URL,
  sourceType: Camera.PictureSourceType.CAMERA,
  allowEdit: false,
  targetWidth: 1024,
  targetHeight: 567,
  encodingType: Camera.EncodingType.JPEG,
  popoverOptions: CameraPopoverOptions,
  saveToPhotoAlbum: false
})
.factory('cameraFactory', function($cordovaCamera, $ionicPopup, PICTURE_SETTINGS){

  return {
    takePicture: function(){
      $cordovaCamera.getPicture(Object.assign({}, PICTURE_SETTINGS)).then(function(imageURI) {
        return "data:image/jpeg;base64," + imageURI;
      }, function(err) {
        $ionicPopup.alert({
          title: 'Camera',
          template: 'Something went wrong: ' + err
        });
      });
    }
  }
})
.controller('pictureOfTheDamageCtrl', function($scope, $rootScope, cameraFactory) {
  $rootScope.width = document.getElementsByTagName('ion-content')[0].clientWidth;

  scope.takePicture = function() {
    cameraFactory.takePicture().then(function(imageURI) {
      $rootScope.damage = imageURI;
    });
  }

})
.controller('pictureOfTheVehicleCtrl', function($scope, $rootScope, cameraFactory) {
  $rootScope.width = document.getElementsByTagName('ion-content')[0].clientWidth;

  $scope.takePicture = function() {
    cameraFactory.takePicture().then(function(imageURI) {
      $rootScope.vehicle = imageURI;
    });
  }

})


You're storing your verses in a format that's a little more complicated than necessary. If you have a dictionary that you're keying by a continuous range of number (and you don't need to handle removals), you likely shouldn't be using a dictionary. Just use a list here:

verses = [["first", "and a Partridge in a Pear Tree."],
          ["second", "two Turtle Doves, "],
          ["third", "three French Hens, "],
          ["fourth", "four Calling Birds, "],
          ["fifth", "five Gold Rings, "],
          ["sixth", "six Geese-a-Laying, "],
          ["seventh", "seven Swans-a-Swimming, "],
          ["eighth", "eight Maids-a-Milking, "],
          ["ninth", "nine Ladies Dancing, "],
          ["tenth", "ten Lords-a-Leaping, "],
          ["eleventh", "eleven Pipers Piping, "],
          ["twelfth", "twelve Drummers Drumming, "]]

If you think about, lists are already indexed by number. Now you don't need to manually increment the number keys if you add a new verse. The change just requires tweaking some numbers to account for 0-based indexing (which I think is more appropriate anyways):

def get_verses(line):
    verse = f"On the {verses[line][0]} day of Christmas, my true love gave to me: "
    for i in range(line, -1, -1):  # -1 stop
        verse += f"{verses[i][1]}"
    return verse.replace("and ", "") if line == 0 else verse  # line 0 now

def recite(start_verse, end_verse):
    return "\n".join([get_verses(line)
                      for line in range(start_verse, end_verse + 1)])

I also changed how you're splitting up the last list comprehension. If you wanted to split it, I would keep the iteration part all on one line, and get_verses on another. I also don't think the line in get_verses needed to be split. It isn't that line.

I'd still change some more things though:

In get_verses, you named the parameter line. It isn't a line though, it's a line number. I'd change it to, at the very least, line_n.
You don't need a strict list comprehension in recite. You can get rid of a pair of brackets by making it a generator expression that uses join's brackets.
The imperative loop in get_verse could be changed to a joined generator expression.

I ended up with this:

verses = [["first", "and a Partridge in a Pear Tree."],
          ["second", "two Turtle Doves, "],
          ["third", "three French Hens, "],
          ["fourth", "four Calling Birds, "],
          ["fifth", "five Gold Rings, "],
          ["sixth", "six Geese-a-Laying, "],
          ["seventh", "seven Swans-a-Swimming, "],
          ["eighth", "eight Maids-a-Milking, "],
          ["ninth", "nine Ladies Dancing, "],
          ["tenth", "ten Lords-a-Leaping, "],
          ["eleventh", "eleven Pipers Piping, "],
          ["twelfth", "twelve Drummers Drumming, "]]

def get_verses(line):
    opener = f"On the {verses[line][0]} day of Christmas, my true love gave to me: "
    verse = "".join(str(verses[i][1]) for i in range(line, -1, -1))
    return opener + (verse.replace("and ", "") if line == 0 else verse)

def recite(start_verse, end_verse):
    return "\n".join(get_verses(line_n)
                     for line_n in range(start_verse, end_verse + 1))

print(recite(0, 11))

On the first day of Christmas, my true love gave to me: a Partridge in a Pear Tree.
On the second day of Christmas, my true love gave to me: two Turtle Doves, and a Partridge in a Pear Tree.
On the third day of Christmas, my true love gave to me: three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.
On the fourth day of Christmas, my true love gave to me: four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.
On the fifth day of Christmas, my true love gave to me: five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.
On the sixth day of Christmas, my true love gave to me: six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.
On the seventh day of Christmas, my true love gave to me: seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.
On the eighth day of Christmas, my true love gave to me: eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.
On the ninth day of Christmas, my true love gave to me: nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.
On the tenth day of Christmas, my true love gave to me: ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.
On the eleventh day of Christmas, my true love gave to me: eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.
On the twelfth day of Christmas, my true love gave to me: twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.

Some further things though:

The verse.replace("and ", "") if line == 0 else verse seems like a code smell. It would probably be cleaner to not have "and" in the saved verse, and to add it when needed, instead of removing it in the special case.
Instead of using range(line, -1, -1) to get reversed indices, you could probably use reversed and islice from itertools to get a sliced reversed iterator of the verses. That way you wouldn't need to index the list.

I'd elaborate, but I need to get going. Good luck.


Flag words that would be difficult for an early reader

The code you presented is not readable and definitely needs refactoring.

You can simplify several code constructions and apply the "Extract Variable" refactoring method to improve readability of the program:

  You have a complicated expression.
  Put the result of the expression, or parts of the expression, in a
  temporary variable with a name that explains the purpose.

For instance, check_pattern() may use the variable unpacking and condition merging, resulting into an explicit and understandable code. I've also renamed it to is_cvc:

def is_cvc(text):
    """Checks if a word is CVC: consonant-vowel-consonant."""
    has_3_characters = len(text) == 3
    if not has_3_characters:
        return False

    first, second, third = text[:3]
    first_is_consonant = first not in vowels
    second_is_vowel = second in vowels
    third_is_consonant = third not in vowels

    return first_is_consonant and second_is_vowel and third_is_consonant

Then, we can reuse this for the cvce check as well:

def is_cvce(text):
    """Checks if a word is CVCE: consonant-vowel-consonant-E."""
    has_4_characters = len(text) == 4
    if not has_4_characters:
        return False

    ends_with_e = text[-1].lower() == 'e'
    is_also_cvc = is_cvc(text[:3])

    return ends_with_e and is_also_cvc

Also note that I've moved the function comments into proper docstrings.

Note that I've also applied .lower() to the last character to handle both e and E.

  In particular, as I look at it, there are an awful lot of "if"
  statements. Is there some way to cut down on those, or does it even
  matter?

Yes, it matters a lot.

The code is much more often read than written. The more if statements and branches you have, the more complicated, less readable and more difficult to maintain it is. There are some code complexity measurement metrics like "Cyclomatic code complexity" or "Maintainability Index" that may give a rough idea of how readable and maintainable the code is. It is also important to note that a more complex code tend to have more bugs in it:

  Some studies find a positive correlation between cyclomatic
  complexity and defects: functions and methods that have the highest
  complexity tend to also contain the most defects.

Also, since you are dealing with natural language here and the input comes in a form of a text, see if switching to nltk for word tokenization would be easier and more robust (especially, in terms of handling punctuation).


Drag Drop, get filename and last 23 characters

Yes, you can write everything in one line, but you will not be happy with the result. And no, .Net creators did not think of implementing a single call which would return exactly 23 characters of dropped file name. :) Silly them. :)

Meanwhile, your code makes sense. I see only two possible issues:

You do not handle multiple files being dropped (that is why there is an array)
You do not handle fileList being null.


How do I improve the print_cpu_data function in the way it shows the information ?

Well, nowadays the most common architectural pattern (design scheme) for many projects is the MVC its principle is to separate the classes and code constructs in your project into 3 packages (model-view-controller)

In the model goes all the code which constitutes your application logic for example your class GameCpu
In the view goes the code which displays the information that the user is supposed to see in exmaple a class which uses tkinter, Pygame etc.
In the controller goes the code which allows communication between model and view.

You need to be aware that Desktop apps and Web apps have a different approach for the MVC due its nature.

If I wish to make a GUI for the game (e.g tkinter, Pygame, etc), what part of the code should be made into functions and how to do so efficiently ?

As I said, you could use an MVC pattern which is basically 3 packages named model, view, controller and import classes accordingly.

I believe your question is more likely to be answered with modularization and refactoring

Modularization is to split independent code blocs into functions, and refactoring is to simplify the code you have written.

Well, I hope it helped you, maybe you need a couple of youtube videos to understand how MVC works. I know, it seems more work, but when you are debugging medium to semi-large personal projects it is worthy, in great scale projects its indispensable. (not just MVC, to use an architectural pattern with an enterprise architecture [the names makes it sound complex but actually it isn't]).

Note: You may ask why did i not answered your first question, well, the code does not work when I execute it, so I can't make suggestions in the air, plus if I recommend a new form to solve this problem, many mods request answers to be bassed on the poster's code.


Here are some critiques. I focused on what is most important for a beginner to think about.

Use Objects

You have conceptually clear units of data you should consider breaking into formally declared objects with constructors. Take a look at this link, especially "Using an Object Constructor". In the long run, this will keep you from writing spaghetti code that is hard to debug, longer than it has to be, and lacking in conceptually-based structure. For example, I would think instead of your allQuestions array you should make the questions with an object constructor method and put them in the array. If you ever want to do anything with the questions later, this will save you a headache.

function Question(q, choices, answer) {
    this.question = q;
    this.choices = choices;
    this.correctAnswer = answer;
}

allQuestions = [...];    // using the class you defined above

Structure

Your structure is confusing. You declare a function, call that function, then declare some other functions. Why not keep all your function declarations together?

Timing

It can be tempting to just dump invocation of your functions into the <script> body, but it's cleaner to link these with an onload event.  You can read more here. This way you have tighter control and understanding of when/why functions execute. For example you wouldn't want to display the quiz when you hadn't yet set up the necessary HTML elements to do so.

Avoid global variables when possible

Read more in this Stack Overflow about why folks generally recommend not using global variables. They result in a crowded namespace and things happening that you don't expect, where the problem can be hard to track down. I know this is just a small project, but it's best to develop coding habits that are sustainable in larger projects. It's not actually more work, and it saves you a lot of debugging later.

Seems like many of your global variables do not need to be global. For example, aChoices is only used in one function. That's probably true for many of the others.


ReentrantReadWriteLock lock upgrade method

Your fears are valid. Once you let go of the lock, all bets are off. When you get the write lock, you will need to check if another thread has mutated the cache. Don't think of it as "ugly"; think of it as "correct". Continue to use comments to explain what you're doing and why you're doing it.

In a nutshell, a read/write lock can't support both upgrading and downgrading. Multiple locks must always be acquired in the same order (in this case, write then read), otherwise a deadly embrace can occur. So when going the other way (read then write), you must let go of the lock, at which point any decisions you made based on current state must be reconsidered.

But there are other options, depending on the details of your situation.

One is to always a get a write lock in anticipation of needing to make a modification and downgrading to a read lock if the data's already there. This is probably not what you want, especially if the majority of operations are read-only, as it will lead to lock contention and poor response times under load.

Other options might involve allowing multiple threads to (redundantly) perform the expensive load, and acquiring the write lock just at the moment of insertion to the table. Or it might be appropriate to just blindly overwrite the existing entry (in this last case, all you would really need is ConcurrentHashMap) . It all depends on the scenario what you're willing to tolerate.

Hope this helps.


Fractional binary number to decimal number

Here are some thoughts about your code:

Don't use using namespace std. This is considered bad practice and you can find many reasons on the internet why this is the case (for example here). You can, for example write std::cout instead.
You should use variable-names that tell the person who reads the code the purpose of the variable.
To improve the legibility of your code, you really should use indentation.
To further improve legibility, you can leave spaces between operators.
I made your code a bit shorter by avoiding redundant code. You could even make it a lot shorter still, but I wanted to maintain your code structure.
Finally, you should have a look at edge cases: Empty strings, strings that only contain "." and strings that don't have positions after/before the decimal point (for example 101 = 5 or .101 = 0.625).

The result looks like this:

#include <iostream>
#include <cmath>
#include <cstring>

double abc(char* b);

int main() {
    std::cout <<  abc(".101") << "\n";
    return 0;
}

double abc(char* b){

    if(strcmp("", b) == 0 || strcmp(".", b) == 0) {       //Empty String or only "."
        return -1;
    }

    if(b[0] == '.') {       //No positions before the decimal point
        int length = std::strlen(b);
        char* newB = new char[length + 1];
        newB[0] = '0';
        for(int k = 0; k < length; k++) {
            newB[k + 1] = b[k];
        }

        b = newB;
    }

    int countDots = 0;
    int index = 0;
    int dotIndex = -1;
    do{
        if ((b[index] == '1') || (b[index] == '0') || (b[index] == '.')){
            index++;
            if(b[index] == '.'){
                countDots++;
                dotIndex = index;
            }
            if(countDots == 2){
                return -1;
            }
        }
        else {
            return -1;
        }
    } while(b[index] != '\0');

    if(dotIndex == -1) {    //No dot found, but not empty string, so you have a natural number
        int length = std::strlen(b);
        char* newB = new char[length + 2];
        for(int k = 0; k < length; k++) {
            newB[k] = b[k];
        }
        newB[length] = '.';
        newB[length + 1] = '0';
        dotIndex = index;
        b = newB;
    }

    double sum = 0;
    index = 0;
    int exponent = dotIndex;

    while(exponent != 0) {
        if(b[index] == '1'){
            sum = sum + pow (2, exponent-1);
        }
        index++;
        exponent--;
    }

    while(b[index] != '\0'){
        if(b[index] == '1'){
            sum = sum + pow (2, exponent);
        }
        exponent = exponent - 1;
        index++;
    }

    return sum;
}

I will leave it to you to comment the code properly.

Please note: The code now is a bit longer than yours, but it is able to handle more things.

EDIT:

After one of the comments below, I decided to also show a version without C-style arrays, and without new. This also should solve the problem with possible memory leaks. So all in all, this is the better version (I will leave the old version, because the questioner asked for a function double abc(char* b)):

#include <iostream>
#include <cmath>
#include <string>

double abc(std::string b);

int main() {
    std::cout <<  abc("1101.101") << "\n";
    return 0;
}

double abc(std::string b){

    if(b.compare("") == 0 || b.compare(".") == 0) {       //Empty String or only "."
        return -1;
    }

    if(b[0] == '.') {       //No positions before the decimal point
        b.insert(0, "0");
    }

    int countDots = 0;
    size_t index = 0;
    int dotIndex = -1;
    do{
        if ((b[index] == '1') || (b[index] == '0') || (b[index] == '.')){
            index++;
            if(b[index] == '.'){
                countDots++;
                dotIndex = index;
            }
            if(countDots == 2){
                return -1;
            }
        }
        else {
            return -1;
        }
    } while(index < b.length());

    if(dotIndex == -1) {    //No dot found, but not empty string, so you have a natural number
        b.push_back('.');
        b.push_back('0');
        dotIndex = index;
    }

    double sum = 0;
    index = 0;
    int exponent = dotIndex;

    while(exponent != 0) {
        if(b[index] == '1'){
            sum = sum + pow (2, exponent-1);
        }
        index++;
        exponent--;
    }

    while(index < b.length()){
        if(b[index] == '1'){
            sum = sum + pow (2, exponent);
        }
        exponent = exponent - 1;
        index++;
    }

    return sum;
}


I would find it easier to understand if the comments were in English, but I'm not the one who will be making changes later, so write your comments for that person (whatever is most useful to future-you).
What I find actively harmful is the very long lines such as

//----------------------------------------------------------------------------------------------------------------------------------------------------------------------

and

        b=-b; //como todas las operaciones con "b" son su multiplicación *-1 y su cuadrado, decidí solo volver b negativo (o positivo dependiendo del caso)

For the first, I think an empty line would be better; for the second, consider word-wrapping it as a block comment.
The global variables a, b, c, total and resultado make it harder to reason about each function in isolation.  I can't even see where that last one is actually used.  Prefer to pass values to and from functions rather than communicating via globals.
These function declarations would be better as prototypes (i.e. specify that they take no arguments, rather than unspecified ones):
void value_input(void);
void display(void);

I'd declare all the helpers with static linkage (this becomes more important when you write programs with multiple source files, but it's a good habit to form), and I'd accept the arguments to discriminante() in the less surprising order a, b, c.
void main() is incorrect - the main function must return an int, so we need int main(void).  Your compiler should have warned you about this; make sure you're enabling enough warning options (e.g. gcc -Wall -Wextra).
When we read input using scanf(), it's important to use the return value that indicates how many conversions were successful.  I would write a function to get a single value (and accept non-integer coefficients, since that's what we can expect from real equations - pun intended):
double read_double(const char *prompt)
{
    for (;;) {
        printf("%s: ", prompt);
        double x;
        int conversions = scanf("%lf", &x);
        if (conversions == 1) {
            return x;
        }
        if (conversions == EOF) {
            /* not much we can do now */
            fputs("Reading failed\n", stderr);
            exit(1);
        }
        /* consume the invalid input and start again */
        puts("Input should be a valid number");
        scanf("%*[%\n]");
    }
}

discriminante() declares total which it never uses, and returns a value that gets ignored.  There's clearly something wrong there.
This line doesn't do what you think it does:

   else if(total=0){

Thankfully, it's harmless, since if total>0 and total<0 are both false, we know that total is already zero, and the assignment has no effect.
When we know a number n is negative, we can make it positive simply with -n rather than calling abs().

Modified code
Here's what I ended up with after fixing the above:
/* El programa calcula la ecuación general de segundo grado, no tiene
   mayor proposito más que practicar C y hacer trampa en los exámenes
   -w-, trato de usar funciones claras para hacer más legible el
   código, tómese nota de que me gusta main en primer lugar main y
   luego el resto de funciones.
*/

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

static double read_double(const char *prompt);
static double discriminante(double a, double b, double c);
static void display(double a, double b, double d);

int main(void)
{
    const double a = read_double("Dame el valor de a");
    const double b = read_double("Dame el valor de b");
    const double c = read_double("Dame el valor de c");

    const double d = discriminante(a, b, c);

    display(a, b, d);
}

static double read_double(const char *prompt)
{
    for (;;) {
        printf("%s: ", prompt);
        double x;
        int conversions = scanf("%lf", &x);
        if (conversions == 1) {
            return x;
        }
        if (conversions == EOF) {
            /* not much we can do now */
            fputs("Reading failed\n", stderr);
            exit(1);
        }
        /* consume the invalid input and start again */
        puts("Input should be a valid number");
        scanf("%*[%\n]");
    }
}

// La función calcula la discriminante y devuelve su valor
static double discriminante(double a, double b, double c)
{
    return b * b - 4 * a * c;
}

// display calcula el divisor de la ecuación y determina como imprimir
// la ecuación basado en el discriminante
static void display(double a, double b, double d)
{
    printf("El resultado es: ");
    if (d > 0) {
        printf("(%g±%g)/%g\n", -b, sqrt(d), a);
    } else if (d < 0) {
        printf("(%g±%gi)/%g\n", -b, sqrt(-d), a);
    } else {                /* total == 0 */
        printf("%g/%g\n", -b, a);
    }
}


Probe for open application on a TCP port

First, I'd suggest to improve on naming. checkAppPr doesn't really tell me anything about what this function does. Naming it to checkAppPort would make more sense.

Next, you've got some hard-coded literals in your code like 127.0.0.1, 20, 1000. Without some sensible names, they don't mean anything. Put them in constants along with the convention of using capital letters and underscores as names.

Your code is an example of one function trying to jam too much functionality. You can split this into two functions, one that checks for any port and resolves/rejects, and another function that repeatedly calls the first one. You've done it already, except the function is nested in the other.

Here's my take on your code. Longer, but splits out responsibilities.

// Returns a promise that resolves when the port is open
checkPortStatus: function(port, host){
  return new Promise((resolve, reject) => {
    portscanner.checkPortStatus(port, host, function(error, status) {
      if(error)
        reject(error);
      else if(status === 'open')
        resolve(status);
      else
        reject(new Error('Port is not open'));
    });
  });
},

// Your API function
checkAppPort: function(port, retriesLeft) {

  const TIME_BETWEEN_CHECKS = 1000;
  const HOST = '127.0.0.1';
  const RETRIES = 20;

  // Setting a default to retriesLeft
  retriesLeft = retriesLeft === void 0 ? RETRIES : retriesLeft;

  if(!port) throw new Error('Port is required');
  if(retriesLeft === 0) return Promise.reject('Timed Out');

  return new Promise((resolve, reject) => {

    // We call our checker. When it resolves, it calls this promise's resolve.
    // If it rejects, we do added work.
    this.checkPortStatus(port, host).then(resolve, error => {
      setTimeout(() => {

        // Call this function again, with one less retry. However, we hook our
        // resolve and reject to the promise of the new call effectively making
        // a chain when it keeps failing.
        this.checkAppPort(port, retriesLeft - 1).then(resolve, reject);

      }, TIME_BETWEEN_CHECKS);
    });
  });
}


Random Plinko path using functional programming style

In Scala the if-else pattern is an expression, which means we can use it to return a value (similar to Java's or C++'s ternary operator). You don't have to change much in order to take advantage of this:

def getPath(prevSlot: Double): Stream[Double] = {
  val left =
    if (prevSlot <= 0.0) false
    else if (prevSlot >= 8.0) true
    else Random.nextBoolean

  if (left) prevSlot #:: getPath(prevSlot - 0.5)
  else prevSlot #:: getPath(prevSlot + 0.5)
}

And then of course you could get a readout of your path with the following:

getPath(4.0).take(13).toList.foreach(println)


Yet Another Regex-Based MarkDown to HTML converter

The whole approach of using regexes to parse Markdown and convert it into HTML is broken.

You have no way of knowing whether any html you generate with one call to gsub is violating the constraints of the HTML containing it.
After the first gsub call, you iteratively apply it to text which now contains some html.  You may mistakenly replace parts of an html element with an html element.

Some of the individual gsub calls are fragile in themselves but none of that compares to the basic flaws of the approach.

Having said that, the way you are using regexes is duplicating code.  You have typed each matched pattern twice: first in the regex, then in the closure.  This would not be necessary if you used capture groups and back-references.


Particularly with your example, I'm not sure if is the kind of functionality what you want, but you can use pure html + css for get a similar approach, using :hover selector.

http://jsfiddle.net/4cywb3yg/4/

If doesn't work for you, and want to keep your code, I refactored a couple of things.

I think you are add/remove the same class. I extracted in a generic function, and apply independently to each element.

    function setToggles($mainElement, $subElement) {

    var hoverIn = function () {
       $subElement.addClass("shown-sub");
    };

    var hoverOut = function () {
       $subElement.removeClass("shown-sub");
    };

    $mainElement.hover(hoverIn,hoverOut);
}

Also I extract a couple of variables with the convention $variable for jQuery elements.

Particularly in this example you are using a lot of jQuery selectors,that can be re-use extracting in a variables. (that was the way what i found the extract code)

Also you chain a lot of jQuery calls, Is not bad, but in excess is easy lose who is receive the last message.And can be a mess for human-reading.

http://jsfiddle.net/4cywb3yg/3/


Adding some properties to an Active Directory user

Disclaimer: I never wrote code like that, I do not see a reason to do it and I discourage everyone to do it.
This however may be seen as nothing else aside of a preference.

But what are you trying to achieve?

Prefectionism?

I do not associate myself with perfectionism, and even if I did as I stated, I doubt I would include
this on the things I must do to keep the code 'perfect'.
Being perfectionist does not mean that you are egocentric. If you are not a egocentric perfectionist
you may relize that the set of rules that you would like to apply doesn't need to be the same set of rules
of another perfectionist.

Maintanability?

How is that code more maintanable than the other without spaces/tabs?
It is less maintanable because I have to spend more time adjusting the identation when adding a new property

Readability?

If we are aiming readability maybe we have another options, for example:

user.Properties["userprincipalname"].Add(email);
user.Properties["givenname"        ].Add(firstname);

This is a formatting issue, and all formating issues should/must be automatically
verified by a static analyzer like resharper, or rubberduck-vba, or wathever.
Most of them allow you to configure all settings once and share among all developers so the code
is written always with the same formatting.

TLDR

In the end you must confess that what you really want to write is the following:

user.Email = email;
user.FirstName = newUser.FirstName;

And you can. I'll list the steps needed to do it:

Create a class with a constructor that recieves the ldap user
Foreach property setter write to the respective ldap property Name
Foreach property getter get the value from the respective ldap property Name


First, lets eliminate the test and test2 variables, which are uneeded (we already have scaledstartx and scaledstarty). Second keep screenwidth/2 and screenheight/2 in variables to avoid recalculating it over and over (the compiler will already do this, but doing manually the code will become clearer). Third, to increase the readability a bit, lets avoid doing calculations in the parameters.

So, this is your code now:

public void render(Graphics g) {

    int halfScreenWidth = screenwidth / 2;
    int halfScreenHeight = screenheight / 2;
    int scaledStartX = halfScreenWidth - (halfScreenWidth / scale);
    int scaledStartY = halfScreenHeight - (halfScreenHeight / scale);

    int scaledWidth = screenwidth - scaledStartX;
    int scaledHeight = screenheight - scaledStartY;
    int locationX = wherex + halfpwidth - halfScreenWidth;
    int locationY = wherey + halfpheight - halfScreenHeight;

    int spriteStartX = scaledStartX + locationX;
    int spriteStartY = scaledStartY + locationY;
    int spriteEndX = scaledWidth + locationX;
    int spriteEndY = scaledHeight + locationY;
    g.drawImage(DrawnLevel, 0, 0, screenwidth, screenheight, spriteStartX,
            spriteStartY, spriteEndX, spriteEndY, null);
 }

We can improve it by observing that the terms in the spriteblabla variables are decomposed in terms that have halfScreenWidth and halfScreenHeight both adding and subtracting. So, we can achieve a simpler expression. To do so, lets replace the variables in the assignment to the spriteblabla variables:

public void render(Graphics g) {

    int halfScreenWidth = screenwidth / 2;
    int halfScreenHeight = screenheight / 2;

    int spriteStartX = halfScreenWidth - (halfScreenWidth / scale) + wherex + halfpwidth - halfScreenWidth;
    int spriteStartY = halfScreenHeight - (halfScreenHeight / scale) + wherey + halfpheight - halfScreenHeight;
    int spriteEndX = screenwidth - (halfScreenWidth - (halfScreenWidth / scale)) + wherex + halfpwidth - halfScreenWidth;
    int spriteEndY = screenheight - (halfScreenHeight - (halfScreenHeight / scale)) + wherey + halfpheight - halfScreenHeight;

    g.drawImage(DrawnLevel, 0, 0, screenwidth, screenheight, spriteStartX,
            spriteStartY, spriteEndX, spriteEndY, null);
 }

Now, lets simplify that, since (halfScreenWidth - halfScreenWidth) and (screenwidth - halfScreenWidth - halfScreenWidth) are zero:

public void render(Graphics g) {

    int halfScreenWidth = screenwidth / 2;
    int halfScreenHeight = screenheight / 2;

    int spriteStartX = -(halfScreenWidth / scale) + wherex + halfpwidth;
    int spriteStartY = -(halfScreenHeight / scale) + wherey + halfpheight;
    int spriteEndX = (halfScreenWidth / scale) + wherex + halfpwidth;
    int spriteEndY = (halfScreenHeight / scale) + wherey + halfpheight;

    g.drawImage(DrawnLevel, 0, 0, screenwidth, screenheight, spriteStartX,
            spriteStartY, spriteEndX, spriteEndY, null);
 }

Now, moving some common subexpressions into variables:

public void render(Graphics g) {

    int halfScaledWidth = screenwidth / 2 / scale;
    int halfScaledHeight = screenheight / 2 / scale;
    int spriteCenterX = wherex + halfpwidth;
    int spriteCenterY = wherey + halfpheight;

    int spriteStartX = spriteCenterX - halfScaledWidth;
    int spriteStartY = spriteCenterY - halfScaledHeight;
    int spriteEndX = spriteCenterX + halfScaledWidth;
    int spriteEndY = spriteCenterY + halfScaledHeight;

    g.drawImage(DrawnLevel, 0, 0, screenwidth, screenheight, spriteStartX,
            spriteStartY, spriteEndX, spriteEndY, null);
 }


synchronized(ai){
            if(ai.incrementAndGet() != runEvery) return false;
            ai.set(0);
        }

You should either use AtomicInteger or use synchronized.  Using both together is certainly overkill.

Consider

    private static int count = 0;
    private static final Object lock = new Object();

and later

        synchronized (lock) {
            if (++count != runEvery) {
                return false;
            }

            count = 0;
        }

Then you don't need the AtomicInteger at all.

I prefer a descriptive name like count to an abbreviated type name like ai.  This is especially so in this case, as my natural expansion of AI is Artificial Intelligence.

You use AtomicInteger when you don't want to use a synchronized block.  Perhaps

        int current = ai.incrementAndGet();
        if (current % runEvery != 0) {
            return false;
        }

        int next = 0;
        do {
            if (ai.compareAndSet(current, next) {
                task.run();
                return true;
            }
            current = ai.get();
            next = current - runEvery;
        } while (next >= 0);

Obviously this is more complicated than the synchronized version.  But this is how one uses an AtomicInteger.

The modulus is more reliable in case of high contention that keeps compareAndSet from returning true.

If we aren't worried that the count will overflow the bounds of integer, we can get rid of the reset.  Without the reset, this makes more sense:

        if (ai.incrementAndGet() % runEvery != 0) {
            return false;
        }

That's how an AtomicInteger is supposed to work.  Even if two threads call this code at the same time, only one will get past the check.  Because the update happens atomically.  The problem with the original code is that there are actually two updates and you need to synchronize them.

Of course, if the range for ai is not constrained, then it will overflow eventually.  The synchronized block is more reliable in that case.  This usage fits synchronized better than atomic types because there's no atomic increment, compare, and reset operation.

You could also use an explicit Lock here, but you don't seem to need it.  The blocking behavior of synchronized better matches what you are doing.  The lock would be better if it were OK to only sometimes update (when you can get the lock) and sometimes not (when you can't get the lock).  But that's not what you are doing here.

It would be possible to create a new class with the necessary method (countCompareReset), but it may be simpler just to use the lock variable with the synchronization block.


Is my code for a forum page vulnerable for sql injections?

Yes, it is.
For some reason you put everything upside-down: where you don't need a prepared statement (for a constant query) you are using it, but where a prepared statement is mandatory - for a query that uses variables - you don't.
But I would say, it is not the main problem of this code. The main problem is this code being a total mess. There are two blocks of code that do absolutely nothing useful, one of them even fails, but you don't notice it.
I would review only a database interaction part
1. Useless code
The following block of code does absolutely nothing
            $sql2 = "SELECT * FROM gallery;";
            $stmt = mysqli_stmt_init($conn);
            if (!mysqli_stmt_prepare($stmt, $sql2)) {
                echo "SQL statement failed!";
            } else {
                mysqli_stmt_execute($stmt);
                $result2 = mysqli_stmt_get_result($stmt);
                $rowCount = mysqli_num_rows($result2);

it takes you $rowCount which is nowhere used. You can safely take this code away.
Another block,
                if (!mysqli_stmt_prepare($stmt, $sql2)) {
                    echo "SQL statement failed!";
                } else {
                    mysqli_stmt_bind_param($stmt, "sssssssssss", $cid, $new_topic_id, $creator, $title, $content, $imageNamn, $imageMail, $imageNummer, $imagePris, $imagestad, $imageFullName);

is also doing nothing useful (as you are already executed this query), and even fails on the bind_param part, because of the flawed
2. Error reporting
There are two things you are doing wrong in regard of error reporting

using procedural interface that silently fails on errors
checking the function results manually

To fix these issues, you have to use OOP syntax and add a specific command to your mysqli connection code,
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

(just for reference, here is a canonical example for mysqli connect I wrote).
After that, all MySQL errors will pop up automatically, therefore you won't have to check every function's result manually.
3. SQL injection.
Finally to the SQL injection. The rules are simple:

if your query doesn't accept any variables, then you don't have to run it using a prepared statement. Use a regular query() instead.
if your query accepts any variables, then it must be executed using prepared statement

Now you can see that if SELECT * FROM gallery had any meaning, you would have run it using query(), not a prepared statement. But as it is just useless, we won't run this query at all.
All other queries must be run using prepared statements:
$sql = "INSERT INTO topics (category_id, topic_title, topic_creator, topic_date, topic_reply_date, imgFullNameGallery, topic_pris)
        VALUES (?,?,?,now(), now(),?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssss", $cid, $title, $creator, $imageFullName, $imagePris);
$stmt->execute();
$new_topic_id = mysqli_insert_id($conn);

$sql = "INSERT INTO gallery (category_id, topic_id, post_creator, titleGallery, descGallery, namnGallery, emailGallery, nummerGallery, prisGallery, stad, post_date, imgFullNameGallery)
         VALUES (?,?,?,?,?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssssssss", $cid, $new_topic_id, $creator, $title, $content, $imageNamn, $imageMail, $imageNummer, $imagePris, $imagestad, $imageFullName);
$stmt->execute();

$sql = "UPDATE categories SET last_post_date=now(), last_user_posted=? WHERE id=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $creator, $cid);
$stmt->execute();

move_uploaded_file($fileTempName, $fileDestination);
header("location: view_topic.php?cid=".$cid."&tid=".$new_topic_id);


In this statement:

for (int i = from; i <= to; i++)
    {
        sb.Append(tokens[i - 1] + ((char)delimiter));
    }

The way that you have it written, I don't think that i will ever hit to.

Also, I would change some variable names to make it more readable. from and to got confusing, I had to keep telling myself that those are variables.  I recommend doing something like:

int intFrom;
int intTo;

at the very least, so that you automatically know that those are integer variables.

Also you have an int for a delimiter? Why not just pass a char as a delimiter?

Other than that I think the code looks good.


Some general tips

functions

split the work in functions, so you can verify each part individually, each doing a specific job which can be individually tested

PEP-8

Try to follow the guidelines

My algorithm

If your pandas version is >= 0.20, you can use pandas.merge_asof If you have a series with the end and start of the work week

dummy data

np.random.seed(1)
gap_max, run_in = 3, 2
indices = [0, 1, 2, 3, 7, 8, 9, 13, 15, 16, 17, 18]
values = np.random.random(size = len(indices))
data = pd.DataFrame({'time': time, 'values': values})

     time  values
0     0   0.417022004702574
1     1   0.7203244934421581
2     2   0.00011437481734488664
3     3   0.30233257263183977
4     7   0.14675589081711304
5     8   0.0923385947687978
6     9   0.1862602113776709
7     13  0.34556072704304774
8     15  0.39676747423066994
9     16  0.538816734003357
10    17  0.4191945144032948
11    18  0.6852195003967595

so for this data, we expect the values of 1, 2, 3, 7, 8, 9, 13, 15 dropped

Finding the gaps

The gap can be found by using DataFrame.shift.

def find_weekend(times, gap_max):
    gap = times - times.shift(1) > gap_max
    week_start = times[gap]
    weekend_start = times[gap.shift(-1).fillna(False)]
    return weekend_start, week_start
find_weekend(data['time'], gap_max)

 3    3
 6    9
 Name: index, dtype: int64,
 4     7
 7    13
 Name: index, dtype: int64

Marking the start of the data as the beginning of a week can be done by adding gap.iloc[0] = True as 2nd line. Marking the end of the data as also an end of the week can be done by changing to .fillna(True)

merging with the data

Since merge_asof expects DataFrames, we first need to do some transformation

def drop_irregular_gaps(data, gap_max, run_in):
    weekend_start, week_start = find_weekend(data[time_label], gap_max)
    df_week_end = weekend_start.to_frame(name=time_label).assign(run_out=True)
    df_week_start = week_start.to_frame(name=time_label).assign(run_in=True)
    df_data = data[[time_label]]

Then we can use 2 merges, one forward to mark the end of the week, one backward to mark the beginning of the week

    before_weekend = pd.merge_asof(
        df_data, df_week_end,
        on=time_label, direction='forward', tolerance=run_in,
    ).set_index(time_label)['run_out'].fillna(False).values
    after_weekend = pd.merge_asof(
        df_data, df_week_start,
        on=time_label, direction='backward', tolerance=run_in,
    ).set_index(time_label)['run_in'].fillna(False).values

These are 2 array with True as value if they are in a run_in or run_out period

array([False,  True,  True,  True,  True,  True,  True, False, False,
        False, False, False], dtype=bool),
 array([False, False, False, False,  True,  True,  True,  True,  True,
        False, False, False], dtype=bool)

Next we just us an or and not for the boolean indexing

    to_drop = before_weekend | after_weekend
    return data[~to_drop]

drop_irregular_gaps(data, gap_max, run_in)

      time    values
0     0       0.417022004702574
9     16      0.538816734003357
10    17      0.4191945144032948
11    18      0.6852195003967595

This can be easily adapted to 2 separate values for the run_in

Datetime data

The algorithm should be agnostic about whether the time_label data is numeric or datetime. I verified this algorithm also works with this dummy data

data_start = pd.Timestamp('20180101')
time = data_start + pd.to_timedelta([0, 1, 2, 3, 7, 8, 9, 13, 15, 16, 17, 18], unit='day')
gap_max, run_in = pd.to_timedelta(3, unit='day'), pd.to_timedelta(2, unit='day')
values = np.random.random(size = len(indices))
data = pd.DataFrame({'time': time, 'values': values})
drop_irregular_gaps(data, gap_max, run_in)

      time        values
0     2018-01-01  0.417022004702574
9     2018-01-17  0.538816734003357
10    2018-01-18  0.4191945144032948
11    2018-01-19  0.6852195003967595

alternative without merge_asof

Since apparently merge_asof doesn't work as good with duplicate data, here a variant with a loop. If there are a lot of weekends, this might be slower, but I reckon it will still be faster than the original code

def mark_runin(time, week_endpoints, run_in, direction='backward'):
    mask = np.zeros_like(time, dtype=bool)
    for point in week_endpoints:
        interval = (point, point + run_in) if direction == 'forward' else (point - run_in, point)
        mask |= time.between(*interval).values
    return mask
mark_runin(time, weekend_start, run_in)

array([False,  True,  True,  True,  True,  True,  True, False, False, False, False, False], dtype=bool)

def drop_irregular_gaps2(data, gap_max, run_in, time_label = 'time'):
    times = data[time_label]
    weekend_start, week_start = find_weekend(times, gap_max)
    before_weekend = mark_runin(times, weekend_start, run_in, direction = 'backward')
    after_weekend = mark_runin(times, week_start, run_in, direction = 'forward')
    to_drop = before_weekend | after_weekend
    return data[~to_drop]
drop_irregular_gaps2(data, gap_max, run_in)

  time        values
0 2018-01-01  0.417022004702574
9 2018-01-17  0.538816734003357
10    2018-01-18  0.4191945144032948
11    2018-01-19  0.6852195003967595


Using attributes with properties in asp.net MVC

I hope it's not too short for an answer but:

VALIDATION attributes MUST NOT manipulate and change the property they decorate.

Do it in the property logic or use some other kind of attribute for that (with your own logic) but do not misuse validation.

Working with generated code isn't easy in this case. It depends on how much freedom you have to instruct generator (for example using a template for setter you may easily achieve desired result). EF (in case you're using it) lets you customize .tt file (but that's usually a pain, I find easier to move to a code-first approach). If you don't have usable extension points you then you may give a chance to an AOP.

About your code, ignoring attribute usage, you should not catch Exception. In this case you don't know what may happen but at least you should ignore critical exceptions like OutOfMemoryException and similar.

try
{
}
catch (Exception e) when (IsNotCriticalException(e))
{
}

Where IsNotCriticalException() is a method you write to determine if exception can be ignored or it must escalate.

If value might be null, in this case you're throwing a NullReferenceException. Handle the case instead of throwing.

[UpperCaseAttribute] may simply be [UpperCase] or, better, [TransformToUpperCase] because it communicates what it will do.


How can I improve this code, without to return async Task?

Doing this doesn't make much sense. If the whole method is going to be synchronous, then you're not gaining much by using asynchronous methods in it, because the synchronous method still needs to block a thread.

Though there might be a way to make async-await work with ASMX.

Task.WhenAll(authTask, tokenTimestampTask);

This doesn't do anything at all. WhenAll() returns a Task that represents the two Tasks combined, so that you can await them. But you're not doing anything with that Task.

You could instead use WaitAll(), but I don't see any reason for that, using Result makes sure that the Task is already completed before returning the value (it does this by blocking the thread if the Task is not completed yet, just like Wait() and WaitAll()).

Task.WhenAll(_mapTokenService.MapAsync(token));

I can see three things wrong with this line:

The WhenAll() issue mentioned above.
You have only a single Task, so you don't need WhenAll() or WaitAll().
You're calling MapAsync() for the second time unnecessarily.

if (authResult.Status == ResultStatus.OK)
{
   …
}
return _serializer.Serizalize(authResult);

It's often best to deal with the failure state immediately by inverting the if:

if (authResult.Status != ResultStatus.OK)
{
    return _serializer.Serizalize(authResult);
}

…

This way reduces the level of nesting for the main part of the code and also improves its flow (you're dealing with the failure in a single place).


Needs code review for class implementation

A couple of issues I found or suggestions I have:

avoid unnecessary or redundant comments (like # initialize values within initialize)
use symbols for your commands and facings
don't use upper case letters in your variable names (pos_x or just x instead of pos_X)
no need to check for != nil, you can simply do params[0] && params[1] &&params[2]
I'd convert simple ifs to use the ternary operator instead: is_valid_position ? @robot = @r : Game.new
find a better name for @r
I'm not sure why you're using instance_variable_get instead of just @robot.pos_X

Try to refactor your longer methods. Take setup as example, personally, I'd like it to look somewhat like this:

def setup(command)
  begin
    params = get_params(command)
  rescue ParamsInvalidError
    restart
  end

  new_robot(params)
  restart unless is_valid_position?
end


General

Run clippy. It will automatically tell you such things as:

equality checks against true are unnecessary

  --> src/main.rs:20:57
   |
20 |             return Some(candidates.iter().position(|&x| x == true).unwrap() as u8 + 1);
   |                                                         ^^^^^^^^^

it is more idiomatic to loop over references to containers instead of using explicit iteration methods

  --> src/main.rs:26:18
   |
26 |         for i in row.iter() {
   |                  ^^^^^^^^^^ help: to write this more concisely, try: `&row`

redundant pattern matching, consider using is_none()

  --> src/main.rs:97:16
   |
97 |         if let None = grid.next() {
   |         -------^^^^-------------- help: try this: `if grid.next().is_none()`

Cell is a name of a type in the standard library, so I was a bit confused to start with. Not sure of a better name.

main

Use while or while let instead of a loop.
The continue is not useful, it's at the end of the block. Switch to an if let instead.
Why isn't the return value of your iterator used? Why don't you use that instead of getting grid.current?
Why is grid.current even part of the grid in the first place?

Grid

If you want to document a function, use ///, not //.
Don't cast booleans as a number. I'm honestly surprised this even compiles. Instead, count the true values
Memorize all the available Iterator methods. In this case, any and all are valuable.

Grid::check_square

There's no need to specify the type of square.
I don't think it's useful to cram the square data into a tuple. Instead, whip up a little closure to perform the same work.
I like Itertools. Here, I use its cartesian_product.

extern crate itertools;

use itertools::Itertools;

type Cell = (usize, usize);

struct Grid {
    data: [[u8; 9]; 9],
    current: Cell,
}

impl Grid {
    /// Search possible candidates for a given cell.
    /// If one candidate exists, return it.
    fn check(&mut self, cell: Cell) -> Option<u8> {
        let mut candidates = [true; 9];
        for i in 1..10 {
            candidates[i - 1] &= self.check_row(cell, i as u8);
            candidates[i - 1] &= self.check_column(cell, i as u8);
            candidates[i - 1] &= self.check_square(cell, i as u8);
        }

        if candidates.iter().filter(|&&x| x).count() == 1 {
            return Some(candidates.iter().position(|&x| x).unwrap() as u8 + 1);
        }
        None
    }

    fn check_row(&self, cell: Cell, num: u8) -> bool {
        self.data[cell.0].iter().all(|&i| i != num)
    }

    fn check_column(&self, cell: Cell, num: u8) -> bool {
        self.data.iter().all(|row| row[cell.1] != num)
    }

    fn check_square(&self, cell: Cell, num: u8) -> bool {
        let truncated_range_of_3 = |x| {
            let start = (x / 3) * 3;
            start..start + 3
        };

        let rows = truncated_range_of_3(cell.0);
        let cols = truncated_range_of_3(cell.1);

        rows.cartesian_product(cols).all(|(row, col)| self.data[row][col] != num)
    }
}

/// Iterate through empty cells.
impl Iterator for Grid {
    type Item = Cell;

    fn next(&mut self) -> Option<Self::Item> {
        let starting_point = (self.current.0, self.current.1);
        loop {
            self.current.0 = (self.current.0 + 1) % 9;
            if self.current.0 == 0 {
                self.current.1 = (self.current.1 + 1) % 9;
            }
            if (self.current.0, self.current.1) == starting_point {
                return None;
            }
            if self.data[self.current.0][self.current.1] == 0 {
                break;
            }
        }
        Some(self.current)
    }
}

fn main() {
    let mut grid = Grid {
        data: [
            [1, 6, 4, 0, 0, 0, 0, 0, 2],
            [2, 0, 0, 4, 0, 3, 9, 1, 0],
            [0, 0, 5, 0, 8, 0, 4, 0, 7],
            [0, 9, 0, 0, 0, 6, 5, 0, 0],
            [5, 0, 0, 1, 0, 2, 0, 0, 8],
            [0, 0, 8, 9, 0, 0, 0, 3, 0],
            [8, 0, 9, 0, 4, 0, 2, 0, 0],
            [0, 7, 3, 5, 0, 9, 0, 0, 1],
            [4, 0, 0, 0, 0, 0, 6, 7, 9],
        ],
        current: (0, 0),
    };

    while let Some(_) = grid.next() {
        let empty_cell = grid.current;

        if let Some(i) = grid.check(empty_cell) {
            grid.data[empty_cell.0][empty_cell.1] = i;
        }
    }

    for row in &grid.data {
        println!("{:?}", row);
    }
}

That unwrap bothers me, but I'm not sure that this is really clearer:

let mut x = candidates.iter().enumerate().filter_map(|(pos, &check)| {
    if check { Some(pos as u8 + 1) } else { None }
}).fuse();

match (x.next(), x.next()) {
    (Some(pos), None) => Some(pos),
    _ => None,
}

It can be made much nicer by abandoning the array at all. This saves (a tiny bit of) stack space but also probably speeds up the program (by a tiny amount) — the function exits as soon as a second possibility is found:

fn check(&mut self, cell: Cell) -> Option<u8> {
    let mut possibilities = (1..10)
        .filter(|&i| self.check_row(cell, i))
        .filter(|&i| self.check_column(cell, i))
        .filter(|&i| self.check_square(cell, i))
        .fuse();

    match (possibilities.next(), possibilities.next()) {
        (Some(pos), None) => Some(pos),
        _ => None,
    }
}

Good news! My version of the code passes every single test case you provided!


Calculate elapsed time from input times without using conditional statements

You may want to read Why is using namespace std bad practice?

#include<math.h>
void main(void)

Use whitespace to separate logical blocks of code:

#include<math.h>

int main(void)

Now you have an includes block and a code block.  This makes it easier to see where the function starts.

I also changed void main to int main.  While many compilers will accept void main, it is technically wrong.  The C++ standards specify that main returns an int.  Note that compilers will automatically return 0; for you.

int ih,im,fh,fm,e,a,b;

Try to avoid undescriptive names for variables.  Abbreviations make it easier to write code, but they slow down reading code.  You'll find that you spend more of your time reading code (including your own) than you do writing it.

int initial_hour, initial_minute, final_hour, final_minute;

I prefer to separate words in variable names with underscores.  Another common notation is camelCase, which capitalizes words after the first.

I don't see the a and b intermediate variables as necessary.  I moved my version of e lower.  More on that later.

std::cout << "Enter initial hour and minute separated by a space:";
std::cin >> initial_hour >> initial_minute;

If you're willing to use a space rather than a colon as the delimiter, you can read both on the same line in a relatively straightforward fashion.  There are methods that can handle a colon but they tend to require conditionals or more advanced data structures.  E.g. strptime returns a struct as a result.

I also added additional whitespace around all the tokens.  The compiler won't care, but it makes it easier for human readers to recognize the separate parts of the code.

a=ih*60+im;
b=fh*60+fm;

I'd write this

const int MINUTES_IN_AN_HOUR = 60;
initial_minute = initial_hour * MINUTES_IN_AN_HOUR + initial_minute;
final_minute = final_hour * MINUTES_IN_AN_HOUR + final_minute;

or actually

const int MINUTES_IN_AN_HOUR = 60;
initial_minute += initial_hour * MINUTES_IN_AN_HOUR;
final_minute += final_hour * MINUTES_IN_AN_HOUR;

But maybe you haven't covered the shorthand assignment operators yet.

I also declared a constant (which you may not have met yet) to hold the "magic value" 60.  See how it makes it more obvious what 60 represents?  If you don't want to use a constant yet, just leave off the const keyword.  It will work fine.  It's just that the compiler won't keep someone from modifying the value after you set it.

The constant would also make it easier to change things if we switched to hundred minute hours.  That seems unlikely in this case, but there are many other situations where that is valuable.  Note that we'd only have to change 60 to 100 in one place with the constant.  Without it, we'd have to switch in two places.  It's even more valuable when there are many uses scattered throughout the code.

Note that this way, you don't need the temporary variables a and b.

Does this work?

e=abs(((780+a)/(781+b))*720-abs(a-b));

It's not clear why you are doing the ((780+a)/(781+b))*720 part.  What's 780?  781?  720?  Why pick those numbers?  What are you trying to accomplish?  This is where comments come in helpful, as they can explain what you are doing to the reader.  Will you remember why you picked 780 and 781 in six months?

Did you perhaps mean to say something like

// add twelve hours to the elapsed time
// then take the time modulus twelve hours to mask out the extra twelve hours
// so 3 - 9 becomes 15 - 9 = 6 which stays 6
// while 9 - 3 becomes 21 - 3 = 18 which becomes 18 % 12 = 6
const int MINUTES_IN_TWELVE_HOURS = 720;
int minutes_elapsed = (MINUTES_IN_TWELVE_HOURS + final_minute - initial_minute) % MINUTES_IN_TWELVE_HOURS;

That would allow you to subtract 9 AM from 3 PM without having to specify AM/PM.  Note that it won't support an elapsed time of twelve hours or more.  It does this with only your existing operators.

Also notice that I declared minutes_elapsed (my replacement for your e variable) at the location it was used.  Now I don't have to go back to find out what type it is.  I can see it right there.

See how I used a comment to explain why I was doing this weird thing?  Now I don't have to figure it out again every time I read the code.

More Advanced

You probably haven't gotten here yet, since many classes don't bother to maintain good form, but most of your code should really be in a separate function.  Code in main is not reusable without copy and paste, but the concept of reading two times and subtracting them is.  So it would be better to put the code in another function or possibly two (one for input and one for calculations).


Best Regular Expression for a one or two values optionally divided by a certain character

This is a somewhat difficult one because regular expressions inherently lack memory, so you can't tell on the back whether the front existed, so I don't think one can get better than the one you wrote for that particular set.  If you wanted to allow some sort of variant, you could potentially find a better one.


Encrypt data before sending it to server in a way that makes it unreadable to anyone except the user who sent it

a few comments, from high to low-level:

Usability

users are generally pretty terrible with passwords!  having them "lose" all their data if they forget their password often isn't something they expect.  i.e. they just want to do a "password reset" and get access to everything again.  I know this is at odds with what you (and lots of similar designs) are trying to do, but thought it useful to point out

Separate authentication from encryption

I'd be tempted to use a more conventional protocol for authentication, probably also separating out passwords used for authentication and encryption.  This would let you, e.g., incrementally increase the Argon2 complexity without invalidating their login (this is something you really need to allow for).  It would also let you use some sort of federated authentication system which might be nice

Crypto usage

CBC doesn't provide any authenticity.  i.e. you won't know if the right password has been used / some attacker is trying to decieve you.  I'd suggest using another block mode, or maybe a stream cipher like chacha20-poly1305
I'd probably just use the hash of the email as the salt, using password as well doesn't seem to help much.
your use of Argon2 in encrypt_payload seems to misunderstand its purpose as a general KDF.  You should just request the amount of output you want, e.g., 48 bytes of keying material from Argon2 and use 32 bytes of that as key and 16 bytes as IV.  that means you just need a single 128bit "key" per file rather than a "salt" and an "IV".  your usage isn't any more secure, 128bits is a big enough state space to stop a brute force attack while access to your storage server would give them the header anyway

API usage

argon2::hash_encoded is mostly designed for hashing passwords for authentication.  you almost certainly want to be using hash_raw to just get the keying material out
it might be useful if your design allowed the Config parameters over time to increase computation complexity.  you really want to record the parameter values used somewhere so the right ones can be used


Elegantly check for null before method call

You can do this:

var title = document.querySelector('title') || {text:''};

then just use title.text in-line.

Alternatively, you could use this one-liner:

var title = (document.querySelector('title') || {text:''}).text;


Tidy up your math

cumulative = cumulative + (sum(predictions.iloc[x, 1:i]) - sum(obsvec[1:i])) ** 2

can be

cumulative += (sum(predictions.iloc[x, 1:i]) - sum(obsvec[1:i])) ** 2

and

RPS[x] = (1/(ncat-1)) * cumulative

should be

RPS[x] = cumulative / (ncat-1)

Make a main method

This is a very small script, but still benefits from pulling your global code into a main.

PEP8

By convention, method names (i.e. RPS) should be lowercase.

That's all I see for now.


The most confusing thing in your code is names of arguments and variables and their types.

DeviceContext context2D

Why not deviceContext?

PolygonType polygon

It's not polygon (which is collection of points as I expect), it's polygon type, so name it polygonType

float numberOfPoints = (float)polygon;

Why are you casting to float? Number of points can be non-integer? Also in my opinion it's not good to give another meanings to enum values except what they mean by their names. Your enum defines polygons types, not numbers of points. I recommend to create dictionary:

private static readonly Dictionary<PolygonType, int> NumberOfPoints =
    new Dictionary<PolygonType, int>
    {
        [PolygonType.Trigon] = 3,
        // ...
    };

and use it:

var numberOfPoints = NumberOfPoints[polygonType];

Why are you using for polygon types such strange names and not Triangle and Square?

If it's public API method, add arguments checking using appropriate exceptions (ArgumentOutOfRangeException, InvalidEnumArgumentException and so on). All possible exceptions should be documented via <exception> tags.


Custom C++ exception class with stack trace generation

Exception( const char *cmessage ) :

I strongly recommend making this constructor explicit, so that you don't permit the user to accidentally write

void some_function(const Exception&);
...
some_function("hello world");

My impression is that most C++ experts recommend explicit on one-argument constructors; I personally hold the minority opinion that explicit should be present on all constructors by default (i.e., if you don't have a specific immediate need for implicit conversion, you should just put explicit automatically, and sort out the consequences later if necessary).

catch ( std::exception &ex )

My current employer's codebase actually does catch by non-const reference, but if you're starting from scratch, I strongly recommend catching by const reference by default. Accidentally mutating the current exception object can cause race conditions.

Also, in the Exception constructor, your catch (std::exception&) should almost certainly be catch (...), right?

As for the high-level point of what you're doing, I believe I have an outline of this sort of thing under "Mix-Ins" somewhere near the end of Template Normal Programming. (Sorry, I'm rushed right now, but I can come back and give you a real link later.) (LATER: I elided that part of the talk, but the two slides on mixins are visible very briefly here.)

The first improvement is to make your thing a template inheriting from T instead of from std::runtime_error specifically. Second, I'd make a function my::throw_with_stacktrace(T&& ex) that simply does throw Exception<std::remove_reference_t<T>>(std::forward<T>(ex));.

Gotta run, but I hope this helps a bit.