Non blocking high performance message processor

I think that there is a certain amount of fuzziness to the question but I'll make a couple of suggestions and perhaps they will help.

First of all, I would recommend giving serious consideration to using Akka actors (http://akka.io/). Actors are a very straightforward way to handle multi-threaded processing without locks.

Just to be clear, I think that you are saying that the program receives messages that have an order but does not necessarily receive them IN order and so it needs to restore the correct order before they can be processed.

If this is true, then I would recommend using TWO actors. The first actor would get the messages from wherever they are coming from and dealing with putting them into the correct order. I assume that it would be ok to cache out-of-order messages until it finds the next message to be processed, perhaps on a priority heap.

Once the first actor finds the next message to be processed, it would send it on to the second actor who would then handle the actual processing (by calling processBusinessStuff in your example).


This works really well and is very easy to read! Here are some suggestions.

Don't Reinvent the Wheel

There are plenty of ways to convert a string to a number in C. There's no need to write your own. You could instead use atoi(), strtol() or sscanf().

Use the Right Comparison

You made max be an unsigned int, but then you compare it against -1 and -2. Those values are not unsigned. I would make some named constants for those comparisons. Something like:

static const unsigned int ERROR_NO_NUMBERS = UINT_MAX;
static const unsigned int ERROR_MAX_BAD_VALUE = ERROR_NO_NUMBERS - 1;

Note that the value for ERROR_NO_NUMBERS depends on the size of an int on your platform. I assumed it was 32 bits.

Prefer const to #define

Preprocessor macros created with #define are problematic. They can lead to very hard to understand code with surprising effects. For defining a constant it's not a huge deal, but it's good to get into the habit of using const for constants and inline functions for calculations when possible instead of macros because of the problems they have.

Performance

Aside from using a different algorithm, I don't see a lot of ways to improve the speed of this. One minor improvement might come from filling the array with alternating true/false values at the start so you iterate over fewer values. Something like this:

// Skip the first 4 values
list [ 0 ] = true;
list [ 1 ] = true;
list [ 2 ] = true;
list [ 3 ] = true;
// This value represents 4 bools in order false, true, false, true
const bool FALSE_TRUE_FALSE_TRUE[] = {false, true, false, true};
// Set all even values over 3 to false since we know they're divisible by 2
memset_pattern4(&list [ 4 ], FALSE_TRUE_FALSE_TRUE, max - 4);

You can then skip checking for 2 and start at 3:

for (int i = 3; i <= max_sqrt; i++) {
    if (list[i])
        for (int j = i*i; j <= max; j += i)
            list[j] = false;
}

Unused Variables

The iteration variable doesn't appear to be used anywhere. It should be removed.

Error Handling

I find your error handling a little odd. (Although it's great that you have it! It's often missed. Nice work.) You check to see if there's no number, and if so, output an error and exit. But if there is a number but it's out of range, you use the maximum allowed value and continue on. I'd make them both do the same thing. Either both exit or both use the maximum and continue on. (Personally, I think stopping is smarter.)


Creating a lightweight strongly-typed parameter infrastructure

Stop. This way madness lies.

It's great that you want to strongly type these things. They should be! The problem is in your approach. This isn't what generics/interfaces are for. This is what Structures and conversion operators are for.

Public Structure EmailAddress
    Private email As String

    Public Sub New(ByVal s As String)
        ' validation code here

        email = s
    End Sub

    Public Shared Narrowing Operator CType(ByVal s As String) As EmailAddress
        Return New EmailAddress(s)
    End Operator

    Public OverRides Function ToString() As String
        Return email
    End Function
End Structure

Which lets you use it as a strongly typed object, without much fuss and using VB.Net idioms that any VB dev will be familiar with.

Dim email = new EmailAddress("JohnDoe@domain.net")

email = CType("JohnDoe@domain.net", EmailAddress)

Dim value As String = email.ToString()


Python program to find the substring with concatenation of all words

As I told in another answers, your code is very C/C++ styled, it is not Pythonic. Try to avoid manual iteration with indices as much as possible. Python has an enormous standard library that contains many useful modules. I already recommended you an itertools module. It contains pair of dozens generic functions to work with iterators. One of them - permutations - do 90% of your work:

Return successive r length permutations of elements in the iterable.
permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
permutations(range(3)) --> 012 021 102 120 201 210

For list L, it returns all possible permutations iterator. If we will join each permutation, we will get the needed search substring.
But next we will have a problem. Python has no built-in function or easy method to find indices of all found substrings in the string (it is strange, I hope they will add it to future Python versions). So you have to do it manually. You can run string.find(substring) in the loop and, after each found substring, to shorten the search range.
Here is the code for my solution:
from itertools import permutations

class Solution(object):
    """
    Leetcode-XXXXX solution
    """

    def find_chained_substrings(self, S, L):
        result = []
        for perm in permutations(L):
            chained_string = ''.join(perm)
            i = S.find(chained_string)
            while i != -1:
                result.append((i, perm))
                i = S[i+len(chained_string):].find(chained_string)
        return result

waka = 'foobarwakatttpingpong-ongpingpt'
lst = ['foo', 'bar', 'waka']
lst2 = ['t', 'pingp', 'ong']
S = Solution()
S.find_chained_substrings(waka, lst2)

It will return:
[(12, ('t', 'pingp', 'ong')), (22, ('ong', 'pingp', 't'))]
Note, that your Leetcode task needs only indices. I construct index-substring tuple for readability and simplier testing. If you want to make a Leetcode solution, replace this string:
result.append((i, perm))
with this:
result.append(i)

P.S. I strongly recommend you to read the Python Standard Library documentation. It will greatly improve your Python programming skill and will shift you from the C/C++ish style to Pythonic style.


The Visitor Pattern

The main purpose of the Visitor pattern is to define extra elements of functionality for a number of classes in a single place. Your PersonVisitor and AnimalVisitor don't really demonstrate this at all - the name indicates that each visitor corresponds to a target type, not a piece of functionality. Better would be a single PrintIsGoodVisitor (probably with a better name). And given that your Visitor will be visiting IElement instances, IVisitor should probably be renamed IElementVisitor too.

interface IElementVisitor
{
    void Visit(IElement element);
}

class PrintIsGoodVisitor : IElementVisitor
{
    public void Visit(IElement element)
    {
        if (element is Person)
        {
            Creature creature = element as Person;
            Console.WriteLine("{0} is a good {1}", creature.Name, "Person");
        }

        if (element is Animal)
        {
            Creature creature = element as Animal;
            Console.WriteLine("{0} is a good {1}", creature.Name, "Animal");
        }
    }
}

You've now got a nasty code smell - passing in an IElement and checking: "Is it a Person? Do this", "Is it an Animal? Do that". The conventional way of implementing a Visitor is to call a virtual method on the visitee to determine its runtime type before the visitee tells the visitor to come and visit (that could have been less confusing...). This involves making Creature.Accept abstract and overriding it in the concrete subclasses.

abstract class Creature : IElement
{
    public string Name { get; set; }

    public abstract void Accept(IElementVisitor visitor);
}

class Person : Creature
{
    public override void Accept(IElementVisitor visitor)
    {
        visitor.Visit(this);
    }
}

class Animal : Creature
{
    public override void Accept(IElementVisitor visitor)
    {
        visitor.Visit(this);
    }
}

This may look like a bit of a waste of time -- every Creature was calling visitor.Visit(this) before, and they're all doing the same now -- but there is a difference. If we change IElementVisitor to have a Visit method for every concrete type that derives from IElement, then each of those concrete types knows which of those Visit methods it can call based on its own type:

interface IElementVisitor
{
    void Visit(Person person);
    void Visit(Animal animal);
}

class PrintIsGoodVisitor : IElementVisitor
{
    public void Visit(Person person)
    {
        Console.WriteLine("{0} is a good {1}", person.Name, "Person");
    }

    public void Visit(Animal animal)
    {
        Console.WriteLine("{0} is a good {1}", animal.Name, "Animal");
    }
}

So when a Person says visitor.Visit(this), it can only be the first version, because this is a Person, and when an Animal says it, it can only be the second.

With these changes, we arrive at a program which is functionally identical to your original, but without a cast in sight - dynamic dispatch has taken their place.

With the Visitor side of things looked at, some points on the rest of the code:

Initializing Lists

In Main, you're creating a list specifically so you can add its elements to a second list. You can just use the second list directly. Additionally, when using a parameterless constructor and an initializer list, you can omit the constructor brackets:

List<Creature> creatures = new List<Creature>
{
    new Person { Name = "Frank" },
    new Person { Name = "Tony" },
    new Person { Name = "Amy" },
    new Animal { Name = "Bubbles" },
    new Animal { Name = "Max" }
};

var

It's considered good practice by many to use var where you can (at the very least for non built-in types) - it's a form of DRY to not repeat the type name twice:

var creatures = new List<Creature>
{
    new Person { Name = "Frank" },
    new Person { Name = "Tony" },
    new Person { Name = "Amy" },
    new Animal { Name = "Bubbles" },
    new Animal { Name = "Max" }
};

Principle of Least Privilege

This principle says that you should use the most general argument types you can for your methods. What is your CreatureProcessor going to do with its visitors and creatures lists? Enumerate their contents. So maybe IEnumerable<T> is a good fit here?

However, it's bad practice to iterate over an IEnumerable<T> more than once (it could be generating data from database calls for all we know!), and not only is Process potentially iterating over creatures multiple times, but there's nothing to stop Process from being called repeatly either. I'd suggest the next most general type that implies the data is safe to iterate repeatedly - IReadOnlyCollection<T>.

Using a more general type means that it can be used with collections other than List<T>, and signals to the user that you're not going to modify the collection you've been given (which List<T> can imply). (See this question for more discussion).

class CreatureProcessor
{
    private readonly IReadOnlyCollection<IVisitor> visitors;
    private readonly IReadOnlyCollection<Creature> creatures;

    public CreatureProcessor(IReadOnlyCollection<Creature> creatures, IReadOnlyCollection<IVisitor> visitors)
    {
        this.creatures = creatures;
        this.visitors = visitors;
    }

    ...
}

Unnecessary Complexity

The CreatureProcessor type seems redundant - you pass two collections into its constructor which it stores, then you call a single method on it. Until you need something more complicated (see YAGNI), a single method alongside Main would suffice here. Even inlining it in Main is a possibility, but it feels sufficiently like a single responsibility that it deserves its own method.

class Program
{
    ...

    private static void VisitAllCreatures(IReadOnlyCollection<IElementVisitor> visitors, IReadOnlyCollection<Creature> creatures)
    {
        foreach (var visitor in visitors)
        {
            foreach (var creature in creatures)
            {
                creature.Accept(visitor);
            }
        }
    }
}

Also, on a similar theme, IElement isn't really doing a lot for you. It's directly implemented once and never used anywhere that Creature wouldn't be valid. It can be omitted (renaming IElementVisitor to ICreatureVisitor too).

Little Things

I believe it's a good idea to be explicit about access modifiers (Stack Overflow question). I've gone with whatever the default value is, leaving the visibility unchanged from your original.
Creature.Name is only ever set at construction and read thereafter, so could be changed to a readonly property set through a constructor - less mutability is less scope for bugs. You can add named parameters during construction if there could otherwise be confusion over what "Frank" represents. The new Creature constructor should be protected because the class is abstract and can't be instantiated.
I'm also a believer of Josh Bloch's "Design and document for inheritance or else prohibit it". If you don't intend to have a class inherited from, mark it sealed so if someone does decide they want to do that, they know they may need to tweak the base class to make it work correctly.

The Final Code

internal abstract class Creature
{
    protected Creature(string name)
    {
        Name = name;
    }

    public string Name { get; }

    public abstract void Accept(ICreatureVisitor visitor);
}

internal sealed class Person : Creature
{
    public Person(string name)
        : base(name)
    {
    }

    public override void Accept(ICreatureVisitor visitor)
    {
        visitor.Visit(this);
    }
}

internal sealed class Animal : Creature
{
    public Animal(string name)
        : base(name)
    {
    }

    public override void Accept(ICreatureVisitor visitor)
    {
        visitor.Visit(this);
    }
}

internal interface ICreatureVisitor
{
    void Visit(Person person);
    void Visit(Animal animal);
}

internal sealed class PrintIsGoodVisitor : ICreatureVisitor
{
    public void Visit(Person person)
    {
        Console.WriteLine("{0} is a good {1}", person.Name, "Person");
    }

    public void Visit(Animal animal)
    {
        Console.WriteLine("{0} is a good {1}", animal.Name, "Animal");
    }
}

internal sealed class Program
{
    public static void Main(string[] args)
    {
        var visitors = new List<ICreatureVisitor>
        {
            new PrintIsGoodVisitor()
        };

        var creatures = new List<Creature>
        {
            new Person(name: "Frank"),
            new Person(name: "Tony"),
            new Person(name: "Amy"),
            new Animal(name: "Bubbles"),
            new Animal(name: "Max")
        };

        VisitAllCreatures(visitors, creatures);

        Console.ReadKey();
    }

    private static void VisitAllCreatures(IReadOnlyCollection<ICreatureVisitor> visitors, IReadOnlyCollection<Creature> creatures)
    {
        foreach (var visitor in visitors)
        {
            foreach (var creature in creatures)
            {
                creature.Accept(visitor);
            }
        }
    }
}


Everything I'm going to talk about is in the merge_sort function

General

i = 0
j = 0
k = 0

Can be defined as

i = j = k = 0

You should always leave spaces between operators as per PEP 8 rules

i<len(left_half) should be i < len(left_half)

Use x += y instead of x = x + y

In my opinion, I think using short and concise names such as mid or middle instead of middle_index would be better. If you don't wish to, you can leave it as it!

Use type hints

Add docstrings

Bug

Your function only takes into account the left_half of the array, and ignores what's left in the right_half

For example, if nums array was [3, 9, 0], The array would be [0, 3, 0]

This would happen as

merge_sort([3]) which won't change the left_half
merge_sort([9, 0]) which would make the right_half as [0, 9]

Then,

left_half = [3]
right_half = [0, 9]

nums = [3, 9, 0]

i = 0
j = 0
k = 0

First, the else statement would be called as 3 > 0.

i = 0
j = 1
k = 1

nums = [0, 9, 0]

Next, the if statement would be called as 3 < 9

i = 1
j = 1
k = 2

nums = [0, 3, 0]

Now, the while loop will terminate as i = len(left_side)

Then, while i < len(left_side) would immediately terminate as i = len(left_side)

Did you notice? right_side still has one element 9 waiting to be traversed, but it never will be.

To fix that, add the following to the end of the function

while j < len(right_half):
    nums[k] = right_half[j]
    j += 1
    k += 1

Improvement

Now, instead of using a while loop at all, you can just use a[k:] = left_half[i:] + right_half[j:] to replace both the loops! This is true because one half must be empty and the other half must have the length of n - k.

Performance

If you are using this function in real time with an array of a really large size, this won't work efficiently.

len takes quite a bit of time. To make it even faster, use a parameter length which would be the length of the array

The final implementation of the function:

from typing import List, Any

def merge_sort(nums: List[Any], length: int) -> None:
    """ Uses Merge Sort to sort an array """

    # Base case
    if length == 1:
        return

    mid = length // 2

    left, right = mid, length - mid

    left_half, right_half = nums[:mid], nums[mid:]

    merge_sort(left_half, left)
    merge_sort(right_half, right)

    i = j = k = 0

    while i < left and j < right:
        if left_half[i] < right_half[j]:
            nums[k] = left_half[i]
            i += 1
        else:
            nums[k] = right_half[j]
            j += 1

        k += 1

    nums[k:] = left_half[i:] + right_half[j:]

Note: Any in typing means any datatype is allowed. The function can sort any datatype that is comparable with another element of the same datatype.


Don't repeat yourself

The step of drawing the hour, minute, second hands are all very similar.
It would be good to use a helper function:

public void Draw(SpriteBatch spriteBatch, Texture2D hand, int value, Vector2 vector2, float coef)
{
    spriteBatch.Draw(hand, center, null, null, vector2,
        value * Math.PI * coef,
        null, Color.White, SpriteEffects.None, 0);
}

Visibility

Since the hour, minutes, seconds should not be visible outside the class,
it would be good to make them explicitly private.
(Thanks @Maxim for the clarification that the default access modifier is actually private.)


How to reduce code from different alert-dialogue?

I also like to keep classes short, but I don't think it should influence your design.  You can put the alert building code in another class file if you really want to.

I would not try to coerce the geolocation alert with onJsAlert/onJsConfirm since it is quite different.  But you could do something if you really wanted to reuse some code for those two (onJsAlert/onJsConfirm).  The positive OnClickListener could be defined outside and shared for onJsAlert/onJsConfirm.  You could instead write a common method for building those two alert dialogs, with an if-statement that checks if a negative button should be added or not.


Scraping content from yellowpage and write them to a csv file

Your description and your code don't seem to match. In the code I don't see anything related to phone numbers. I also don't understand what "The scraper has the ability to collect all the links connected to all the names." means. With that said, I'm not sure if any of my critique is valid, but here I go any way.

To answer your question about writing to csv, I think you are doing it right. In fact, you are doing it exactly as shown in documentation, so no issues here.

Now I'd like to get into details.

Minor issues

Format your code

Run autopep8 and isort on your code before submitting it. Makes it easier to quickly scan through it.
Use consistent string quoting

It doesn't matter whether you use single or double quotes. What matters is that you pick one and stick with it.
Get rid of useless comments

Consider:

writer.writerow([name, website])  # writing data in a csv file

This comment is virtually useless, because the code right beside it says the same thing. Comments like this explain nothing  and should be deleted.
Variable naming

Spare extra characters to rename res to response
Avoid generic names (e.g. rename item to something like search_result)
Use underscore to separate individual words in variable name (e.g. nextpage →next_page)

Good variable names often eliminate the need for comments. Effort spent on coming up with concise and descriptive names goes a long way towards improving readability.

More substantial issues

This line is way too long.

 website = soup.select_one("#main-header a.website-link").get("href") if soup.select_one("#main-header a.website-link") else ""

Consider rewriting it as an ordinary if statement. Save the result of soup.select_one(...) into a variable to avoid repeated function call.
Use of recursion in get_links is confusing. Consider rewriting it using a while loop.

Some things I might have misunderstood

There doesn't seem be any need to use requests.Session and on top of that reset headers before every call to get. If you really need a persistent session, it'd be a good idea to leave a comment explaining why.
In your code you seem to be only grabbing name and website for each search result. If that's the case, loading the details page for each result is redundant as all desired information is present in the search results themselves.


Separate roles into modular parts that are interdependent

In Python 2.x, when creating classes, you need to explicitly have them inherit from object, like this: class MyClass(object):. If you're using Python 3.x, then you can write them like this: class MyClass:

Secondly, the general style for naming in Python is snake_case for functions and variables, and PascalCase for classes. If you have a constant variable, then it should be in UPPER_SNAKE_CASE.

The following line of code in your role.reload function can simply be changed to return 0:

else:
    return 0

This also applies to your role.check function. else: return "" can be changed to return "".

Also, I noticed that you're returning either 1 or 0 in your role.reload function. Do you mean to be returning True or False? This also applies to your role.init function as well.

Finally, in your role.check function, the below block of code can be changed to this: return self.funcToCall(*self.args) if self.moduleName else self.checkFunc(*self.args).

if self.moduleName:
    results = self.funcToCall(*self.args)
else:
    results = self.checkFunc(*self.args)
return results


Bugs:

privateEmail.substring(0, 2) needs to change to privateEmail.substring(0, 3) in the else, since end index is exclusive and we want to include 3 characters, not 2.

Method assumes that privateEmail contains a "@", and does not check if atSignIndex results in -1, resulting in a StringIndexOutOfBoundsException if there is no "@". Return privateEmail (with no hiding applied) early if you expect this method be handed any generic string which could potentially be an email, or throw an IllegalArgumentException if privateEmail is always expected to be an email. I consider the latter to be better design. Note that both these situations handle empty strings as well.

Improvements:

Use var for type inference where the type is obvious from the right side, like new StringBuilder(...), or String#substring. This is as of Java 10.

1 < emailName.length() is redundant because length of 0 and 1 are handled by earlier cases.

StringUtils.repeat can be replaced with String#repeat as of Java 11. Rids of need for external dependency here.

Instantiating a new StringBuilder in the else can be replaced with mutating the current one, namely with the delete and insert instance methods.

Move stringBuilder declaration lower, to only when it is needed.

Replace "*" with a static final variable, such that we could change it to "-" or "_" down the road and remain consistent across all the ifs and the else. This, despite being a character, will have to be a String to remain type-compatible with String#repeat and StringBuilder#replace.
Final code:

private static final String HIDE_CHAR = "*";

public static String asHiddenEmail(String privateEmail) {
    int atSignIndex = privateEmail.indexOf("@");

    if (atSignIndex == -1) {
        throw new IllegalArgumentException("`privateEmail` must be an email.");
    }

    var stringBuilder = new StringBuilder(privateEmail);
    var emailName = privateEmail.substring(0, atSignIndex);

    if (emailName.length() == 1) {
        return stringBuilder.replace(0, emailName.length(), HIDE_CHAR).toString();
    }
    if (emailName.length() < 4) {
        var hiddenNameEnd = HIDE_CHAR.repeat(emailName.length() - 1);
        return stringBuilder.replace(1, atSignIndex, hiddenNameEnd).toString();
    }
    else {
        stringBuilder.delete(3, atSignIndex);
        stringBuilder.insert(3, HIDE_CHAR.repeat(4));
        return stringBuilder.toString();
    }
}


The code looks fine. However, there are a few things you can do to improve it:

first, avoid using Capital letters for variable. In Python, they should be named in snake_case;
use snake_case for setters (e.g., set_name) and getters as well, or use properties instead. See https://www.python-course.eu/python3_properties.php for more information.
You can avoid instantiating the variable in the __init__.
If you are using Python 3.X, consider specifying the parameters types and return types.

Here is how I would refactor your code:
class Employee:

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, name: str):
        self.__name = name

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, age: int):
        self.__age = age

    @property
    def company(self):
        return self.__company

    @company.setter
    def company(self, company: str):
        self.__company = company

    @property
    def xp(self):
        return self.__xp

    @xp.setter
    def xp(self, lvlup: float):
        self.__xp = lvlup

However, you should use setters if you need to perform some checks before assigning the value to the variable (e.g., you want to check that the passed age  > 18 or that the title is at least "a bachelor degree", and so forth.
If you do not need those checks, you can simply call the variable, for example:
class Employee:

    def __init__(self):
        self.name = ''
        self.id = 0
        self.age = 0
        self.company = 0
        self.title = ''
        self.level = 0
        self.xp = 0.0
        self.tasks = []
        self.projects = []

employee = Empolyee()
employee.name = 'Foo Bar'
employee.age = 30

Instead of using setters or populating the variables one by one, you can further improve the code by passing the parameters to the Employee class constructor:
class Employee:

    def __init__(self, name:str, age:int, company:int, id:int=None, title:str=None,
                 xp=float=None, task:list=None, projects:list=None):

        self.name = name
        self.id = id
        self.age = age
        self.company = company
        self.title = title
        self.level = level
        self.xp = xp
        self.tasks = tasks
        self.projects = projects

   # Properties here (getters and setters) ...

Then, read_info will become:
def read_info(self, name, age, company):
    e = Employee.Employee(name=name, age=age, company=company)
    self.employees.append(e)

Update
As highlighted by hjpotter, a more suitable approach in this case would use dataclasses.
Therefore, the class can be rewritten as:
from dataclasses import dataclass

@dataclass
class Employee:

    name: str
    age: int
    company: int
    id: int = 0
    title: str = None
    level: int = 0
    xp: float = 0.0
    tasks: list = None
    projects: list = None

The __init__ is created automatically, and a new object can be instantiated as in the previous example:
def read_info(self, name, age, company):
    e = Employee.Employee(name=name, age=age, company=company)
    self.employees.append(e)


One way you can remove duplicated code is to create a method:

public static int[] GetMaxMin (ArrayList <Integer> list)
{
    int max = list.get(0);
    int min = list.get(0);

    for (int i : list){
        if (i > max) {
            max = i;
        } else if (i < min) {
            min = i;
        }
    }
    int[] maxMin = {max, min};

    return maxMin;
}

This can then be called like this:

max = GetMaxMin(list)[0];
min = GetMaxMin(list)[1];

However, the above said, I would not recommend doing this because it has two purposes - to get the max value and the min value in the list.  What I would recommend is to implement two methods - one to get the max value and one to get the min value:

public static int GetMax (ArrayList <Integer> list)
{
    int max = list.get(0);

    for (int i : list){
        if (i > max) {
            max = i;
        }
    }

    return max;
}

GetMin would be similar.  Then, all you would need to do is this:

int max = GetMax(list1);
int min = GetMin(list1);
int max2 = GetMax(list2);
int min2 = GetMin(list2);

As you are calculating a range of values, though, you should just write a method to do that:

public static int CalculateRange (ArrayList <Integer> list)
{
    int max = list.get(0);
    int min = list.get(0);

    for (int i : list){
        if (i > max) {
            max = i;
        } else if (i < min) {
            min = i;
        }
    }

    return max - min;
}

As brought up in the comments, this will crash if there are 0 elements in the list.  To prevent this, you should probably check this before you try to get the range, like this:

if (list.size() != 0) {
    System.out.printf("List 1 Range: %d\tList 2 Range: %d\n", CalculateRange(list1), CalculateRange(list2));
} else {
    System.out.println("There are no elements in this array");
}


Since your format is relatively constant I would suggest parsing it yourself into hours and minutes and seconds and use the LocalTime.of method.  It could look something like this:

public static LocalTime getLocalTime(String inputTime){
    if (inputTime.trim().equals(""))
    {
        return null;
    }
    int hour = ((inputTime.charAt(0)-'0')*10)+(inputTime.charAt(1) - '0');
    int minutes = ((inputTime.charAt(2)-'0')*10)+(inputTime.charAt(3)-'0');
    int seconds = 0;
    if(inputTime.length() != 4){
        if(inputTime.charAt(4) == 'H'){
            seconds = 30;
        }else{
            seconds = ((inputTime.charAt(4)-'0')*10)+(inputTime.charAt(5)-'0');
        }
    }
    return LocalTime.of(hour, minutes, seconds);
}


Converting bits to decimal (integer) string is so slow

You are trying to do arithmetic with strings, that is bound to be expensive.

Here is a naive algorithm to output a BigInteger in decimal:

std::stringstream output;
BigInteger num = the_number;
while(num != 0) {
    output << static_cast<int>(num%10);
    num = num/10;
}
std::string output_str = output.str();
std::reverse(output_str.begin(), output_str.end());
return output_str;

of course you need to implement the operators %, / and cast to int first.

This can also be easily improved by chunking to the maximal power of 10 holdable in an unsigned int or unsigned long.

However this naive algortithm still has quadratic time complexity in the length of the number. I am not sure whether there is a linear time algorithm. Another quadratic, but possibly faster algorithm is Double dabble.

In the GMP documentation there is a short explanation of a subquadratic algorithm. Maybe this can give you some directions. You may want to look at its source anyway as a reference of a mature BigInteger implementation.

I am also quite confused by your function names. What is _1A63 supposed to mean? I doubt the end of the function name is the correct place for whatever it is. Is it representing the container element types? If so that should belong into a template parameter.


Cross-Database Query Without Casting to List

You can try to replace the .ToList() by an .AsEnumerable(). AsEnumerable() makes a transition from LINQ-to-EF to LINQ-to-Objects. AsEnumerable() does not enumerate the items (lazy enumeration).


Sherlock is going against the Beast with PowerShell

I'm no powershell expert but if spaces sprinkled around here and there would make the code more readable. So instead of this:

for($inputIndex=1;$inputIndex -le $inputNumbers[0];$inputIndex++){

it would read like this:

for (inputIndex = 1; $inputIndex -le $inputNumbers[0]; $inputIndex++) {

Less crammed and easier to read I'd say.
Your outer for loop could be expresses as a ForEach which would yield cleaner code:

ForEach ($N in $inputNumbers) {
    # Create a loop that runs for the number of passes in the current line of input.
    # Count down from the number until 0
    $highestNumber = $N..0 | ForEach-Object {
        # Check to see if this digit combination is a decent number.
        # If it is then we pass it thru the pipeline and stop the loop.
        If (($_ % 3) -eq 0 -and (($N - $_) % 5) -eq 0) {
            ("5" * $_).PadRight($N, "3")
            # If we get a result then this is the highest. Exit the loop.
            continue
        }
    }

    # Check the value of $highestNumber. It is possible that for this pass there
    # are no decent numbers. Nulls evaluate to false.
    if ($highestNumber) { $highestNumber } else { -1 }
}

As for the algorithm: You kind of brute force it which is usually not the intend of these programming challenges. I have outlined a slightly better algorithm in my answer to another question trying to solve the same problem.


Web scraping news articles with Beautiful Soup

It seems wasteful to re-crawl the specified websites every time your web page gets hit, particularly if the web pages you're crawling have nothing to do with the request sent to your webpage. This seems like a job that should be run as a cron job (say, every 5 or 30 minutes), stored in the database, then simply fetched from the database when your webpage gets hit.

A great framework for more advanced crawling is scrapy. It very likely might be overkill for this application, but if you're pondering more advanced scraping, it's a good utility for that purpose.

Now to actually review your code.

Your shorten function could be radically simplified using slices:

def shorten(cleaned_html, limit=50):
    """
    If the description of an article is too long, let's cut it
    to only 50 characters.
    """
    return cleaned_html[:limit] + ('...' if len(cleaned_html) > limit else '')

Also, in strip_html, you compile your regex every time, but only use it once. In Python's re module, there are shortcut functions when you're only using a regex once. You could simply do return re.sub(r"<.*?>", "", raw_html)

When doing your crawling, you create several temporary lists, each of which is a simple function that transforms the elements of the previous list, which you do using a list. In Python, there's a very efficient way (both in memory and compute time) to represent this using generator comprehensions. You also have a robust constructor for Brick; instead of creating a generic Brick and then modifying it, just make the exact Brick you want in the first place:

def extract_brick(item):
    return Brick(
        title=item.find("title").get_text(),
        link=item.find("link").get_text(),
        description=shorten(strip_html(item.find("description").get_text())) if item.find("description") is not None else "No description.",
        img_url=item.find("media:content").get("url") if item.find("media:content") is not None else "No media.",
        creator=item.find("dc:creator").get_text() if item.find("dc:creator") is not None else "No creator.",
        date=item.find("dc:date").get_text() if item.find("dc:date") is not None else "No date."
    )

def news_list(request):
    unformatted_xmls = (urllib.request.urlopen(URL) for URL in URLS)
    formatted_xmls = (BeautifulSoup(unf_xml, "xml") for unf_xml in unformatted_xmls)
    group_of_items = (form_xml.find_all("item") for form_xml in formatted_xmls)
    bricks = [extract_brick for item_group in group_of_items for item in item_group]

    return render(request, "new/list.html", {"bricks": bricks})

And lastly, you don't need semi-colons at the end of every line. It's a hard habit to break when transitioning from languages where whitespace doesn't really matter, such as C++, C, or Java, but in Python they're mostly just clutter.


In Java class names should start with an upper letter (node->Node).
Why all your methods have default visibility? You usually want to have public methods though if this intentional then just ignore this point.
You seem to be restricting your RBTree to have only ints. You could use generics instead to make it more flexible and make it useful in more cases
Your formatting is inconsistent (indentation).


The method names are a little bit misleading. They're already in the HashTable class, aren't they? If yes, then why would you add the hash word to their names (except for the one that actually computes the hash)? hashSearch and addToHash make it sound like the code looks for/adds a hash. It doesn't. It adds/searches for the value.
What does the hashSearch return? The index is the internal implementation detail. I do not see a good reason to expose it to the client. It should probably return a boolean value (and I'd call it something like contains).
You did not present the full code, so there are a lot of questions left. What is the initial number of buckets in the table? Does it grow? What happens if it gets fully loaded (the addToHash method can stuck in an infinity loop in that case)? These questions are very important, but, unfortunately, I can't comment on those as the relevant parts of your code are missing.


It needs more Using statements. For example:

Public Shared Function CheckSecurity(strUserID$, strOperation$, strAppID$) As Boolean
    Try
        Using da As New SqlDataAdapter("dbo.CheckSecurity", ConnString)
            Dim sc = da.SelectCommand, p = sc.Parameters, dt = New DataTable
            sc.CommandType = CommandType.StoredProcedure
            sc.CommandTimeout = m_iSQLTimeOut

            p.Add("@UserID", SqlDbType.VarChar, 15).Value = strUserID
            p.Add("@AppID", SqlDbType.VarChar, 50).Value = strAppID
            p.Add("@Operation", SqlDbType.VarChar, 50).Value = strOperation

            Return da.Fill(dt) > 0     ' .Fill returns the number of rows successfully added
        End Using           ' da is disposed here even if Exception occurs
    Catch ex As Exception
        Throw New ApplicationException("SECURITY ACCESS ERROR")
    End Try
    Return False
End Function

or

Public Shared Function CheckSecurity(strUserID$, strOperation$, strAppID$) As Boolean
    Try
        Using con = New SqlConnection(ConnString),
              cmd = New SqlCommand("dbo.CheckSecurity", con)

            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandTimeout = m_iSQLTimeOut

            cmd.Parameters.Add("@UserID", SqlDbType.VarChar, 15).Value = strUserID
            cmd.Parameters.Add("@AppID", SqlDbType.VarChar, 50).Value = strAppID
            cmd.Parameters.Add("@Operation", SqlDbType.VarChar, 50).Value = strOperation

            con.Open()
            Using reader = cmd.ExecuteReader
                Return reader.HasRows
            End Using
        End Using       ' con and cmd are closed and disposed here even if Exception occurs
    Catch ex As Exception
        Throw New ApplicationException("SECURITY ACCESS ERROR")
    End Try
    Return False
End Function

Some other examples https://stackoverflow.com/questions/24023575/how-to-pass-parameters-to-sqldataadapter, https://stackoverflow.com/questions/14566980/c-sharp-data-adapter-parameters


Nesting for loops to find matches in different tables

I don't know enough about the shape of testData to write great code, but you could preprocess and convert testData from an array to an object or Map of key-value pairs. By using the first element of each item in testData as the key, then you can convert your \$O(n)\$ inner "search" loop into a constant time \$O(1)\$ key lookup. This would reduce your overall complexity from something on the order of \$O(n^2)\$ to a nicer linear \$O(n)\$ algorithm.
Note: This assumes your data has unique values sitting at index 0 of each element in the main array. The difference being your code returns the first match, but the following technically return the last match as duplicate key overwrite existing value(s).
Something like:
var tabData = tabDataRange
  .getValues()
  .reduce((tabData, data) => ({ ...tabData, [data[0]]: data }), {});

Then your loop becomes
for (var i = 0; i < sheetData.length; i++) {
  var sheetName = sheetData[i];

  if (tabData[sheetName]) {
    var data = tabData[sheetName];
    var tabProps = [
      tabName = data[0],
      tabVisibility = data[3],
      tabUpdVisibility = data[4],
      tabClearData = data[5],
      tabFormat = data[6],
      tabPosition = data[7],
      tabColor = data[8]
    ];
    break; // <-- found data, break out of loop early
  }
  console.log("tabProps = ", tabProps);
  console.log("tabName = " + tabName);
}


Remove repeated words from a 2D character array

Your algorithm is \$O(n^2)\$.  You can reduce this to \$O(n)\$ by first inserting them into a closed hash table (i.e., one with bucket chains).
I'd optimise is rather than copying the whole items, just copy pointers to the original strings (unless you intend to alter their contents later on).


Identifiers containing two consecutive underscores are reserved for use by the C++ implementation for any purpose.  That means they can even be macros!  Don't use __ in your identifiers; if you want to keep them separate from user code, you can use a suitable namespace (ideally an anonymous namespace).

Another observation is that this code only keeps count of operations - a double delete could easily cancel a leak and lead your code to report "No leaks discovered".

Although you've kept using namespace std; within a sensible, small scope, I think I'd still prefer using std::cout; using std::endl or just fully-qualified names there.  Consider using std::cerr instead for this kind of information that's not part of normal program output - that may be essential when used in a pipeline.


Json.Net has support for collections built-in. You should be able to use the generic version of DeserializeObject like this:
private Dictionary<string, bool> GetWorkflowNames()
{
    var appDataFolder = ConfigurationMgr.GetAppPath("App_Data");
    var jsonFilePath = Path.Combine(appDataFolder, "WorkflowNames.json");
    var jsonString = System.IO.File.ReadAllText(jsonFilePath);
    var workflowNames = JsonConvert.DeserializeObject<List<string>>(jsonString);
    return workflowNames.ToDictionary(name => name, _ => false);
}

There are still a few things I would clean up in your code:
Add a using for System.IO and use File without the namespace. You could also use a static using like this using static System.IO.File; and access ReadAllText directly but I generally dislike this unless the class is very focussed and heavily using File.
You'll notice that I introduced a local variable jsonString as I don't like hiding the file access in the call to deserialize the json. I try to stick rigidly to one thing happening per line. Simple and clear code is best when you want to maintain it 2 years later.
I'd also recommend using .ToDictionary as it shortens the code and makes it very obvious what you're doing. Having said that, I would have this return an IEnumerable<string> instead of a dictionary. It's not clear why this returns a dictionary and GetWorkflowNames sounds like it would be perfectly reasonable to return the list.


URL
URL components should generally appear from "broadest to narrowest" left-to-right. I'm not totally convinced that this is currently the case - the weather site is probably "broader" than the latitude and longitude.
Is the city within a climbing area, or vice versa? If a climbing area is within (or smaller than) a city, their positions should be reversed.
How many of those parameters can be inferred from other parameters? If you only specify the city, could default coordinates be inferred? Try to omit as many optional parameters as possible from the path, and move them to query parameters.


Find closest greater and smaller number from a sorted array

First of all, comments would be nice. Speaking in terms of implementation rarely helps another person understand what the code is doing. Especially when the code uses very generic variable names. My general rule to comments is when the code tries to do something clever, write a comment.

You could short-circuit the logic if the array is empty. No sense having the code run if you know ahead of time it does nothing.

Also, by eliminating cases early, you can start making assumptions. This would allow you to simplify logic or make optimizations to existing logic, turning general-case logic to case-specific logic.

for (let i = 0; i < array.length; i++) {
    if (array[i] >= currentValue) {
        immediateNextIndex = i;
        break;
    }
}

Could be simplified using array.findIndex.

Here's my take on it:

const findPreviousNext = (array, currentValue) => {
  // Short-circuit the code if the array is empty.
  if(array.length === 0){
    return { next: null, prev: null }
  }

  // Find the index of the closest greater number.
  const closestIndex = array.findIndex(v => v >= currentValue)

  // A non-existent/negative index is undefined. No need for extensive checks.
  const closestNext = array[closestIndex] || null
  const closestPrev = array[closestIndex - 1] || null
  const lastValue = array[array.length - 1] || null

  // The only special case is the non-existent value (index = -1)
  const next = closestIndex === -1 ? null : closestNext
  const prev = closestIndex === -1 ? lastValue : closestPrev

  // Build the instance (a simple POJO in this case).
  return { next, prev }
}

console.log(findPreviousNext([], 3))
console.log(findPreviousNext([1], 3))
console.log(findPreviousNext([1, 2], 3))
console.log(findPreviousNext([1, 2, 3], 3))
console.log(findPreviousNext([1, 2, 3, 4], 3))


Reading a repetitive file with repetitive code

Well, you could find a "Pythonic" way to skip around a file, but that still wouldn't make it good code, in my opinion.  There are some fundamental issues with your approach that make it rather hackish:

f.seek(0) means that the file isn't being processed sequentially, and creates extra work.
You're hard-coding ano = 1977 when in fact ANO  1977 would be right there in the data file itself!  And you're deliberately skipping over that valuable information!  And then you have to hope that the file really does start with data for 1977!
This data format is human-friendly but machine-hostile.  You say that your ultimate goal is to import the data into pandas for analysis.  But PANDAS doesn't easily understand this IDEAM data format.  In fact, your output is just as difficult to parse as the original, but worse, since stripping out the year headers makes the data less self-documenting.  The work to implement a real parser seems unavoidable.  So, if you're going to transform the data, why not transform it into one of the formats that PANDAS knows how to read?
1, 10, 12, and 13 are "magic" numbers.  There is no way to understand why those numbers are there in the code.  Basically, you're blindly assuming that the input is in a certain format without any verification.  If your assumption is wrong, you could easily load data into your analysis incorrectly, and you would never know about the mistake.  You wouldn't want the wrong kind of publicity for your climate analysis, would you?

Therefore, I consider your approach to be a poor substitute for properly parsing the file.  Here, for example, would be one way to parse this data format:

import fileinput
import re

class IdeamParser:
    def __init__(self, *patterns):
        self.patterns = [(re.compile(regex), act) for regex, act in patterns]

    def parse(self, line_iter):
        for line in line_iter:
            for regex, action in self.patterns:
                matches = regex.search(line)
                if matches:
                    yield from action(self, matches)

    def start_meta(self, matches):
        self.meta = {}
        yield from []

    def read_meta(self, matches):
        self.meta.update(dict(zip(matches.groups()[::2], matches.groups()[1::2])))
        yield from []

    def months_header(self, matches):
        line = matches.group()
        self.month_cols = [m.span() for m in re.finditer(' *(\S+) *[*]', line)]
        yield from []

    def read_data(self, matches):
        day_of_month = int(matches.group(1))
        line = matches.group()
        values = [line[start:end] for start, end in self.month_cols]
        values = [float(val) if re.search(r'\d', val) else None for val in values]
        yield self.meta, day_of_month, values

parser = IdeamParser(
    (r'^\s*(\d{2})\s+(.*)', IdeamParser.read_data),
    (r'I D E A M', IdeamParser.start_meta),
    (r'(VALORES) (.*\(.*\))', IdeamParser.read_meta),
    (r'(FECHA DE PROCESO) : *(\d{4}/\d{2}/\d{2}) *'
        r'(ANO) +(\d{4}) *'
        r'(ESTACION) : *(.*?) *$', IdeamParser.read_meta),
    (r'(LATITUD) +(.*?) *'
        r'(TIPO EST) +(.*?) *'
        r'(DEPTO) +(.*?) *'
        r'(FECHA-INSTALACION) +(.*?) *$', IdeamParser.read_meta),
    …
    (r'\s*DIA +ENERO.*', IdeamParser.months_header),
)
for meta, day_of_month, values in parser.parse(fileinput.input()):
    print(meta, day_of_month, values)

Sample output:

{'DEPTO': 'ANTIOQUIA', 'FECHA DE PROCESO': '2016/09/08', 'LATITUD': '0553 N', 'FECHA-INSTALACION': '1970-JUN', 'ANO': '1986', 'TIPO EST': 'CO', 'ESTACION': '26185020  MESOPOTAMIA', 'VALORES': 'TOTALES DIARIOS DE RECORRIDO DEL VIENTO (Kms)'} 1 [144.0, 35.0, 10.0, 32.0, 52.0, 6.0, 81.0, 133.0, 44.0, 29.0, 7.0, 17.0]
…
{'DEPTO': 'ANTIOQUIA', 'FECHA DE PROCESO': '2016/09/08', 'LATITUD': '0553 N', 'FECHA-INSTALACION': '1970-JUN', 'ANO': '1986', 'TIPO EST': 'CO', 'ESTACION': '26185020  MESOPOTAMIA', 'VALORES': 'TOTALES DIARIOS DE RECORRIDO DEL VIENTO (Kms)'} 5 [35.0, None, 31.0, 18.0, 16.0, 15.0, 110.0, 160.0, 125.0, 12.0, 18.0, 56.0]

The print() statement at the end is just for demonstration.  You should replace it with code that generates a CSV file or SQL INSERT statements or something.  Or you could just load it into PANDAS directly.


Put ages within a supplied range into a HashMap

range.put(age, range.get(age) + " and " + name);

This is expensive.

Specifically, string construction that is done over and over via creating longer and longer strings. You're basically building the same string over and over and over. And strings are basically arrays of char, so that's a lot of copying.

And there's nothing you can do about it because of this rule:

  You will need to construct a map to store your results, but you may not use any other structures (arrays, lists, etc.) as auxiliary storage. (You can have as many simple variables as you like.)

If you were to ignore this one rule for a moment, what you could do is make a Map<Integer, List<String>>. And then put the names of people in the list. Then, when you're done, as per this stackoverflow answer... https://stackoverflow.com/a/22577565/540837

You can use a stream and Collectors.joining.

But you can't, because you're not allowed any other lists or arrays or whatnot.

I'd personally consider the problem unsolvable because the strings could get very long and become a larger part of the problem than the actual pairs would.

What I'd change about your code is this bit:

for (String name : namesAges.keySet()) {
    int age = namesAges.get(name);

You're first getting the keys, and then you're using the keys to get the value. Maps have .entrySet to get a set of entries, and then you can have the key and the value in one go.

Also, "Your result map's pairs should be sorted in ascending order by age (keys)." sorting already takes O(N log N) time, so basically your instructors are expecting that you'll find a way to get N log N string concatenation which doesn't exist when you're not allowed to create arrays.


In your question, you wrote:

func CharToNum(r rune) (int, error) {
    for i := 48; i <= 57; i++ {
        if int(r) == i {
            return (int(r) - 48), nil
        }
    }
    return -1, errors.New("type: rune was not int")
}

In his answer, Janos wrote:

func CharToNum(r rune) (int, error) {
    intval := int(r) - '0'
    if 0 <= intval && intval <= 9 {
        return intval, nil
    }
    return -1, errors.New("type: rune was not int")
}

Using idiomatic Go, I wrote,

var ErrRuneNotInt = errors.New("type: rune was not int")

func CharToNum(r rune) (int, error) {
    if '0' <= r && r <= '9' {
        return int(r) - '0', nil
    }
    return 0, ErrRuneNotInt
}

It's simple and direct and it's fast. Benchmarking the numbers zero through nine:

BenchmarkCharToNumTschfld    5000000    323 ns/op
BenchmarkCharToNumPeter     50000000     37.7 ns/op

Benchmarking the invalid numeric character space (' '):

BenchmarkCharToNumErrTschfld    10000000      242 ns/op       16 B/op      1 allocs/op
BenchmarkCharToNumErrPeter      2000000000      1.26 ns/op     0 B/op      0 allocs/op

The error variable ErrRuneNotInt can be used to check for a specific error, for example, if err == ErrRuneNotInt {}.

In your question, you wrote:

func ParseNum(str string) []int {
    var nums []int
    for _, val := range str {
        num, err := CharToNum(val)
        if err != nil {
            continue
        }
        nums = append(nums, num)
    }
    return nums
}

Using idiomatic Go, I wrote,

func ParseNum(s string) []int {
    nLen := 0
    for i := 0; i < len(s); i++ {
        if b := s[i]; '0' <= b && b <= '9' {
            nLen++
        }
    }
    var n = make([]int, 0, nLen)
    for i := 0; i < len(s); i++ {
        if b := s[i]; '0' <= b && b <= '9' {
            n = append(n, int(b)-'0')
        }
    }
    return n
}

It minimizes both CPU time and memory allocations; it's fast. Benchmarking the string "000123456789000":

BenchmarkParseNumTschfld     1000000    2475 ns/op     248 B/op    5 allocs/op
BenchmarkParseNumPeter       2000000     610 ns/op     128 B/op    1 allocs/op

Unicode and UTF-8 characters corresponding to the ASCII set have the same byte values as ASCII.

See Benchmarks, Package testing.


Consider using a hashmap of provider -> process. This will enable you to register new providers with relative ease.
async function githubRelease({user, repo, part = ""}) {
  let json = (await (await fetch(`https://api.github.com/repos/${user}/${repo}/releases/latest`)).json())
  if (json.message === "Not Found") throw "Invalid repository"
  if (!("assets" in json)) throw "Rate limit exceeded"
  let browser_download_urls = json.assets.map(asset => asset.browser_download_url)
  return browser_download_urls.filter(url => url.includes(part))
}

It will then be mapped inside the getRelease function as follows:
module.exports.getRelease = async ({provider, user, repo, part = ""}) => {
    if !(providerMethods[normalise(provider)]) {
        throw "Invalid provider"
    }
    return providerMethods[normalise(provider)](user, repo, part)
}

where providerMethods would be:
let providerMethods = {
    normalise("github"): githubReleases
}

This will enable users of your module to register new (or private) registry providers. They can add a new provider to the providerMethods object (gitlab etc) and don't have to wait for you to update the library first for supporting any extra providers (you can add providers if popular).
The await (await fetch()).json() can be extracted to another function. Although, I'd prefer using the promise.then(r => r.json()).catch() chain over multiple awaits, it is entirely dependent on your comfort with the language.


Simplify series of string manipulations in Ruby

You may collect the replacements in a Hash and call them on after the other.

replacements = {
  /1/ => ' one ',
  /2/ => ' two ',
  /([34])/ => ' (\1 is three or four) ',
}

test = '123'
replacements.each{|regex, repl|
  test.gsub!(regex, repl)
}
p test

The gsub-version with blocks need a little trick:

replacements = {
  /1/ => ' one ',
  /2/ => ' two ',
  /3/ => Proc.new{|m| m*2},
}

test = '123'
replacements.each{|regex, repl|
  if repl.is_a?(Proc)
    test.gsub!(regex){|m| repl.call(m)}
  else
  test.gsub!(regex, repl)
  end
}
p test

In your case you may define your replacements with:

Replacements = {
  # sub_heading
  /^(#+)\w+/                                    => Proc.new{|m|  m.gsub("#", "=")},
  /^(=+)(.+)/                                   => '\1 \2 \1',
  # sub_codeblock
  /```(.+\n)((.|\n)+)```/                       => '{{{#!text_pygments \1\2}}}',
  # sub_inlinecode
   /`(.+)`/                                     => '{{{\1}}}',
  # sub_bold
  /([^\w]|^)\*\*\w[\w\s\d\-_'"]*\*\*([^\w]|$)/  => Proc.new{|m|  m.gsub("**", "'''")},
  # sub_italic
  /([^*]|^)\*\w[\w\s\d\-_'"]*\*([^*]|$)/        => Proc.new{|m|  m.gsub("*", "''")},
  # sub_link
  /\[\[(.+)\|(.+)\]\]/                          => '[[\2|\1]]',
}

def my_replace(inputstring)
  Replacements.each{|regex, repl|
    if repl.is_a?(Proc)
      inputstring.gsub!(regex){|m| repl.call(m)}
    else
    inputstring.gsub!(regex, repl)
    end
  }
end

my_replace(inputdata)


For the first problem:

You are using more processes than strictly needed, since you

spawn a process A that
spawns a number of monitoring processes M that each
spawn a worker W and monitoring it.

If a worker fails, you spawn a new monitor 'M' and a new worker.

ex5_start(FList) ->
    spawn(fun() -> %% This is the spawn of process A
        [bring_back(F) || F <- FList] %% This is the list for B's
        end).

bring_back(FID) ->
    spawn(fun() -> %% This is the spawning of an M
        {Pid, Ref} = spawn_monitor(FID), %% This is the spawning of a W
            io:format("Pid = ~p~n",[Pid]),
            receive
                {'DOWN', Ref, process, Pid, normal} -> void;
                {'DOWN', Ref, process, Pid, _Why} ->
                    %% New M and W
                    bring_back(FID)
            after infinity -> void %% you can skip this entire line
            end
        end).

An after clause with a hardcoded infinity timeout is never going to be executed, so you can skip it.

You can think of a simpler solution, where you spawn_monitor the workers and associate their FIDs with a Pid and Ref (e.g. in a list comprehension) and then have a second phase in which whenever a DOWN message arrives you lookup the relevant worker PID and restart its FID. You don't even need a separate A process.

For the second problem:

Several things seem off:

You are using an intermediate process on which all others are linked
This intermediate process will block on this piece of code:

                                receive
                                after infinity -> true
                                end

you are not killing all processes on an error, just linking them all to die together with the intermediate process. This may not be what is needed, if e.g. some process is trapping exit signals.
If all processes exit normally, the intermediate process will remain blocked forever.

If you follow my suggestion for the previous question, it is easy to replace the second phase with a different one that does the correct thing (remember to also keep track of processes that have died normally).


Computing the square root of a 64-bit integer

Usually you can just test n < r*r instead which also has the benefit of being much cheaper than a sqrt. You do need to handle potential integer overflow for n > 264 - 2*232 + 1.

You can't hoist r*r out of the loop the way you can hoist sqrt(n) out but integer multiplication is cheap on any modern processor.


Some suggestions:

Naming is really important. string, array, i and j are not descriptive. After reading the entire function I think they could be renamed sentence, words, string_index and word_length.
There's no point in adding empty strings to the array - they aren't printed anyway.
What is the significance of 38? If it's not significant it should be removed, if it is it should be named something like max_result_length.
In Python return is a simple statement, which means its argument should not be put in parentheses.


Gathering emails, phones, URIs, and tag related to a room

There's really not much we can help you, given the low level of detail in the question.

There are somethings you have in this code snippet that are generally considered a Very Bad Idea, so I'll give what help I can in that regard.

Null Checks

There are a bunch of these types of checks in the posted code:

if(room.id != null && !room.id.isEmpty)

If you have any control at all over Room you should be using Option instead. If you have no control over Room, define these methods using an implicit. These checks should only every be made in one place, not every place that accesses the code.

Assuming that id is a String (just a guess). The signature should in Room should be:

def idOption: Option[String] = Option(this.id).filter(_.nonEmpty)

Which would drop the code in the snippet to:

room.idOption.foreach(id => query += ("_id" -> id))

Much simpler.

Premature Optimizations

If you ever have enough members in a room for the MutableList optimization to gain you anything, you'll probably be exceeding the length of the Mongodb query. This needlessly complicates your code.

Ironically, any gains are lost when you forgot to use nonEmpty rather than .size > 0, which needs to iterate through the lists you just made to avoid iterating through the lists.

It looks like the accessors for the Member attributes already return Option values, so this can be much more readably rendered like this:

val emails = for {
  member <- room.members
  email <- member.email
} yield email

val phones = for {
  member <- room.members
  phone <- member.phoneNumber
} field phone

// 'uri' is not the plural of 'url', they are not
// actually equivalent, please don't conflate them.
val forwardUrls = for {
  member <- room.members
  url <- member.forwardUrl
} yield url

if(emails.nonEmpty)
  query+=("members.user.email" -> MongoDBObject("$all" -> emails))

if(phones.nonEmpty)
  query+=("members.user.phoneNumber" -> MongoDBObject("$all" -> phones))

if(forwardUrls.nonEmpty)
  query+=("members.user.forwardUrl" -> MongoDBObject("$all" -> forwardUrls))

Redundant Code

Much of the tags block is a no-op. It condenses down to just this:

if (room.tags.nonEmpty) {
  query+=("tags" -> MongoDBObject("$in" -> room.tags))
}


Python shuffle the middle letters in all the words of a sentence

The fact that Python allows fitting things on a single line and pack in comprehensions, does not mean you need to try to squash the code to be shorter hurting readability. I would probably at least expand the code into multiple lines with descriptive variable names.

Here is, though, an alternative solution based on regular expression replacement function:

from random import shuffle
import re

RE_GARBLE = re.compile(r"\b(\w)(\w+)(\w)\b")

def garble_word(match):
    first, middle, last = match.groups()

    middle = list(middle)
    shuffle(middle)

    return first + ''.join(middle) + last

def garble(sentence):
    return RE_GARBLE.sub(garble_word, sentence)


The screen design looks very nice. It is minimalistic, yet pleasing. It almost perfectly fits on the small screen of my phone (only sometimes, I have to scroll down to see all the answer buttons). The flags are nicely big to explore the fine graphical details. To appreciate the shape of the Nepal flag, there should be no border around it, and the background color could be set to something other than white, since that is used in some of the flags.

Bug: never sort using a random comparator. Instead, shuffle the array. This has been answered often already, just search for the above terms.

When reading the code aloud, "a country is a component" doesn't make sense. A country is something having a name and a flag, so the class should better be named CountryComponent.

Most JavaScript code can be rewritten to not use the this keyword or the bind function, which leads to clearer and simpler code. See this code review for an example.

In the setTimeout call, I prefer to extract the first argument into a named function, so that the setTimeout appears closer to the 2000:

function action() {}

setTimeout(action, 2000);

There should be a space between the label "Score:" and the score number.

When I play the quiz, my total score always stays at 0, so there must be something wrong. After each click on one of the answer buttons, the page becomes green or orange for about a second and is then reloaded, which explains that the score is reset and that the screen flickers. On the other hand, the Random button works fine, so there must be something that differs between those. (Tested with Firefox on Android.)


Univariate linear regression from scratch in Python

About OOP

  I tried to exploit OOP as much as I could, instead of using a procedural approach to write the algorithm.

Although I believe that your approach was fine, using OOP for the sake of OOP is something I would rather warn against. There is a talk about this here.

Comments

def __init__(self, dataset, learning_rate, num_iterations):
    """
    Class constructor.
    """

The comment Class constructor is redundant and unecessary, I would instead explain the parameters of __init__ in the doc string.

    self.M = len(self.dataset) # 100.

Is the # 100 saying that the len(self.dataset) is always going to be 100? It might be 100 in this case, but I highly doubt you can ensure that.

Default values

Have you considered putting default values for learning_rate and num_iterations? If we want a default of 100 and 0.001 for num_iterations and learning_rate respectively, you could rewrite __init__ like:

def __init__(self, dataset, learning_rate=0.001, num_iterations=100):

Private methods

Do you really want do_gradient_step(self) to be considered public? Yes, there are no "true" private methods, but the convention is to put one underscore before the name to indicate it is private. Honestly, I would just call it _step(self).

Indentation

if __name__ == "__main__": main()

should really be:

if __name__ == "__main__":
    main()

To comply with PEP 8.


Regex to clean text in preparation for word count in PHP

Do it in two steps. First replace all the stuff you deem to be "junk" with spaces, then collapse the spaces and hyphens down to a single space. You can express this with a reduce through a series of patterns that collapse to a space.

Some output from a play in Boris.

[7] boris> function clean($input) {
[7]     *>   $patterns = array(
[7]     *>     '/[^\w\r\n -]/',
[7]     *>     '/[\r\n -]{2,}/'
[7]     *>   );
[7]     *>   return array_reduce(
[7]     *>     $patterns,
[7]     *>     function($text, $re) { return preg_replace($re, ' ', $text); },
[7]     *>     $input
[7]     *>   );
[7]     *> }
[8] boris> clean('abc def &% f');
// 'abc def f'
[9] boris> clean('abc-def &% f');
// 'abc-def f'
[10] boris> clean('abc-def-&%-f');
// 'abc-def f


Rails controller method that conditionally filters results

Creating a model just to check the parameters is overkill and not idiomatic in Rails. If you need some extra logic, use the existing model. In this case, I'd make Post#tagged_with accept a nil value which wouldn't filter anything:

def Post
  scope :tagged_with, ->(tag) { tag ? <code to filter> : all }
end

class PostsController < ApplicationController
  def index
    @posts = Post.tagged_with(params[:tag]).paginate(page: params[:page])
  end
end


Before the review, let me advise you that Project Euler problems have very little to do with programming. They are mostly about math. Your code is very ineffective because it scales (almost) linearly with the range, whereas the solution can be achieved in a (almost) constant time.

The construct

    if condition:
        return True
    else
        return False

is a long way to say

    return condition

The in range loop which modifies its loop variable, as in

for nat_num_iterator in range(range_start, range_end):
    ....
    nat_num_iterator += 1

gives me shivers. Here you increment nat_num_iterator twice per iteration. If it is an intent, use range(range_start, range_end, 2).


What is the purpose of $offset? It doesn't seem to do anything here.
What is the possible range of values of $id? Do you need to check that it is an integer, and that it is not negative?
Can $id have leading zeroes? That would naturally mess up the alignment with the 7 3 1 array, and possibly interfere with using str_split.
I would personally be very nervous about mixing around types like this, treating things as integers, then strings, then integers, then strings again.... At a minimum I would recommend being explicit about every time you do so. Otherwise it's far from clear what is going on.

  Sum is rounded to next full tenth and then from that sum is subsctracted

I would personally always prefer to use mod for this sort of thing, partly because messing with floating point numbers is confusing and partly just because the operation is inherently a mod calculation. For example something like this works as long as $sum is at least 1:

$checkDigit = 9 - (($sum - 1) % 10)


Modifying the affine transform origin in graphics2D

private int origin;
...
switch (origin) {
case ORIGIN_LEFT:
case ORIGIN_CENTER:
case ORIGIN_RIGHT:
    y -= bounds.getHeight()/2;
    break;
case ORIGIN_BOTTOM_LEFT:
case ORIGIN_BOTTOM:
case ORIGIN_BOTTOM_RIGHT:
    y -= bounds.getHeight();
    break;
}

You should turn origin into an enum for compile time type safety.

double x = -bounds.getX();
double y = -bounds.getY();

switch (origin) {
case ORIGIN_LEFT:
case ORIGIN_CENTER:
case ORIGIN_RIGHT:
    y -= bounds.getHeight()/2;
    break;
case ORIGIN_BOTTOM_LEFT:
case ORIGIN_BOTTOM:
case ORIGIN_BOTTOM_RIGHT:
    y -= bounds.getHeight();
    break;
}

switch (origin) {
case ORIGIN_TOP:
case ORIGIN_CENTER:
case ORIGIN_BOTTOM:
    x -= bounds.getWidth()/2;
    break;
case ORIGIN_TOP_RIGHT:
case ORIGIN_RIGHT:
case ORIGIN_BOTTOM_RIGHT:
    x -= bounds.getWidth();
    break;
}

This entire section of code looks like you could get rid of it if you made proper use of enums.

You could store an offset multiplier in them; Origin.LEFT would have a -0.5 multiplier to height and a 0 multiplier to width, whereas Origin.BOTTOM_RIGHT would have -1 and -1 respectively.

Then you could just write a function applyOffset, which would work like this:

public Point getOriginPoint(Rectangle2D shape){
    double x = (offsetMultiplierX * shape.getWidth()) - shape.getX();
    double y = (offsetMultiplierY * shape.getHeight()) - shape.getY();
    return new Point(x, y);
}

Although maybe it'd be better to just calculate the offset; in that case you could invert y to get the cartesian view.


Get the common values between two text files

Global variables (dataset1 and dataset2) are bad.  I'd rather see you write no function at all than a function that accepts its inputs through global variables:

with open('file1.txt') as file1, open('file2.txt') as file2:
    print((set(file1) & set(file2)) or "No common elements")

If you do write a function, then it should accept its inputs as parameters.  Name the function's parameters however you want, but avoid unnecessary reassignments like a_set = dataset1 and b_set = dataset2.

def print_common_members(a, b):
    """
    Given two sets, print the intersection, or "No common elements".
    """
    print((a & b) or "No common elements")

with open('file1.txt') as file1, open('file2.txt') as file2:
    dataset1 = set(file1)
    dataset2 = set(file2)
    print_common_members(dataset1, dataset2)


Spacing
Before anything, I would recommend fixing your spacing and tabbing. Four spaces for each level of nesting is recommended. It makes your code a lot more readable.
Bug
There is a pretty obvious bug in your code I noticed on my first pass. It's how you're checking the computers number versus the users number. For instance, take a look at this line:
if (user == 0 || 1)

To a novice, it looks like if user == 0 OR user == 1, but that is not happening here. Instead, this is only checking if user is equal to 0, OR if 1 is true. And 1 is always true. This can result in some unexpected behavior. Take a look:
if (user == 0 || 1) {
    std::cout << "Greetings!" << std::endl;
} else {
    std::cout << "Hello!" << std::endl;
}

Now, if I only enter 0, I will get the expected output of just "Greetings!". However, if I enter literally any other number, I will instead only get "Greetings!", instead of getting "Hello!".
Repetition
You have tons of repeated code. You can simplify this by first checking for if the computers input is the same as the users at the start of the program. Then you won't have to keep checking on the goat if/else chunk.
if (computer == user) {
    std::cout << "You tied! :/" << std::endl;
    return 0;
}

Then, you can just assume the user loses at the start.
std::string message = "Computer wins! :(";

Now, you only have to check for win conditions, and if any are met, you change the message variable.
if (
    (user == 1 && (computer == 3 || computer == 4)) ||
    (user == 2 && (computer == 1 || computer == 5)) ||
    (user == 3 && (computer == 2 || computer == 4)) ||
    (user == 4 && (computer == 2 || computer == 5)) ||
    (user == 5 && (computer == 1 || computer == 3))
) message = "You win! :)";

Then, you just output the message variable.
std::cout << message << std::endl;

End
All in all, with these changes made your code now looks like this:
#include <iostream>

int main() {

    srand(time(NULL));
    int computer = rand() % 5 + 1;
    int user = 0;

    std::cout << "=============================================\n";
    std::cout << "Rock    Paper    Scissors    Spock    Lizard!\n";
    std::cout << "=============================================\n";
    std::cout << "1) Rock\n";
    std::cout << "2) Paper\n";
    std::cout << "3) Scissors\n";
    std::cout << "4) Lizard\n";
    std::cout << "5) Spock\n";
    std::cout << "\n";
    std::cout << "Shoot!\n";

    std::cin >> user;
    std::cout << "Computer chose: " << computer << "\n";

    if (computer == user) {
        std::cout << "You tied! :/" << std::endl;
        return 0;
    }

    std::string message = "Computer wins! :(";

    if (
        (user == 1 && (computer == 3 || computer == 4)) ||
        (user == 2 && (computer == 1 || computer == 5)) ||
        (user == 3 && (computer == 2 || computer == 4)) ||
        (user == 4 && (computer == 2 || computer == 5)) ||
        (user == 5 && (computer == 1 || computer == 3))
    ) message = "You win! :)";

    std::cout << message << std::endl;

    return 0;
}


Of course it is unit testable.

All function/methods are.

A unit test is to flex the function to breaking point. i.e. exercise the usual conditions and the boundary points.


Notifying view controller of changes to any of five types of models

The type annotation in

if let listTableViewController: listTableViewController<ModelA> = pages[currentIndex].viewController as? listTableViewController<ModelA>

is not needed because the type is automatically inferred from the
expression on the right-hand side:

if let listTableViewController = pages[currentIndex].viewController as? listTableViewController<ModelA>

According to the Swift API Design Guidelines

  Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase.

Therefore it should be func refreshList() and ListTableViewController.

To simplify your code, define a protocol for the common methods:

protocol RefreshController {
    func didRefreshNodesList()
    // ...
}

and make ListTableViewController conform to that protocol.
Then you can reduce it to a single test

if let refreshController = pages[currentIndex].viewController as? RefreshController {
    refreshController.didRefreshNodesList()
}


First time doing a review, so bear with me.

I've been thinking about how to make any changes to your code, but had a difficult time finding things that could be optimized. Overall, I think you did a great job.

Selectors - this may be a style preference, but I tend to lump everything under one var statement (delimited by commas), rather than having to write var each time.

Methods - I chose to pass the elementId into document.getElementById rather than having to write additional if statements to check specifically for either id. You're already checking to see what event.target.id is returning, might as well use it again.

Methods - closePanel, I created a function called checkClassListAndAddClass very long, but at least you know what it's doing. This function takes the selector as an argument, checks to see if the selector contains a class, and then returns the add class. I added a variable to that function to help remove some repetitive code.

Again, this is my first stab at a code review, so I'm happy to hear your feedback as well as any other feedback from the community.

/**
* Require modules
*/
var dullBackground = require('./dullBackground');

module.exports = function () {

    'use strict';

    /**
    * Selectors
    */
    var menu = document.getElementById('nav-main'),
        overlay = document.getElementById('overlay-panel'),
        close = document.getElementById('overlay-close'),
        productsPanel = document.getElementById('page-products'),
        systemsPanel = document.getElementById('page-systems'),
        activeClass = 'active',
        hideClass = 'hide';

    /**
    * Methods
    */
    function togglePanel(event) {
        var elementId = event.target.id;

        event.preventDefault();

        if (elementId === ('page-products' || elementId === 'page-systems')) {
            dullBackground();
            overlay.classList.add(activeClass);
            document.getElementById(elementId).classList.remove(hideClass);
        }
    }

    function closePanel(event) {
        event.preventDefault();
        overlay.classList.remove(activeClass);

        checkClassListAndAddClass(productsPanel);
        checkClassListAndAddClass(systemsPanel);
    }

    function checkClassListAndAddClass(selector) {
        var selClassList = selector.classList;

        if (!selClassList.contains(hideClass)) {
            return selClassList.add(hideClass);
        }
    }

    /**
    * Events/APIs/init
    */
    menu.addEventListener('click', togglePanel, false);
    close.addEventListener('click', closePanel, false);

};


In merge(), you call malloc() twice with no corresponding calls to free().  That can't be good for your memory consumption!

When computing the average of two values, don't do q = (p+r)/2, because that is vulnerable to overflow.  Instead, write it as q = p + (r - p) / 2.


Aside from the inconsistency in the for loop.  It would make more sense to have the limit as

i > 0

Your implementations seems sound to me.

However the SingTheLine method could use some work.

First off this:

string pluralityMinusOne = ((drinksLeft + 1 != 1) ? "s" : string.Empty);

doesn't look right.  Shouldn't it be (drinksLeft - 1 != 1)?

Also the new string concatenation introduced in c#6, I believe, is much easier to understand than using string.Format.

sb.AppendLine($"{drinksLeft} bottle{plurality} of beer on the wall, {drinksLeft} bottle{plurality} of beer.");
sb.AppendLine($"Take one down and pass it around, {((drinksLeft - 1 > 1) ? (drinksLeft - 1).ToString() : "no")} bottle{pluralityMinusOne} of beer on the wall.");


Overall, the code is clean and easy to follow.  I appreciate the consistent indentation.  I would not be upset about running your code in production.  Here are some suggestions that would make it even better:

use your own variables

With the lines

# create temp file
truncate -s 1M /tmp/test_monitor

we get a temporary file, but since we name it explicitly it isn't clear that it gets used by the curl right after.  It would be easier to follow if you did:

truncate -s 1M $FILENAME

If you want to be really careful, check the exit value of truncate or see if the file is the right size (which also implies that it exists).

check before assigning

You assign your command line arguments before checking if they are even there.  I prefer to check before using so I would like to see:

# Verify the type of input and number of values
# Display an error message if the (input) is not correct
# Exit the shell script with a status of 1 using exit 1 command.
[ $# -ne 4 ] && { echo "Usage: $0 <hostname> <username> <password> <webdav_dir>"; exit 1; }

HOSTNAME=$1
USERNAME=$2
PASSWORD=$3
WEBDAVDIR=$4

for usage exit UNKNOWN rather than WARNING

If somebody runs your plugin within nagios without enough command line arguments your script will print the helpful usage and then exit 1 which we know nagios will interpret as a warning.  That's something that could get missed in a big nagios install for a while so I'd prefer to exit $STATE_UNKNOWN so that it will be obvious in nagios that something is broken with the config.

duplicate variables

From your script:

FILENAME=/tmp/test_monitor
FILE=test_monitor

I understand that you need this in different places, one without the path, and otherwise with the path.  But we can reduce duplication by doing something like

FILE=test_monitor
FILENAME=/tmp/$FILE

I would go one step further and rename the variables as

FILENAME=test_monitor
FQFN=/tmp/$FILE

now FILENAME contains the name of the file without the path and FQFN is he "Fully Qualified File Name" and is the one you will mostly use.

tips for nagios plugin writers

For writing a nagios plugin in any language I would encourage folks to:

include a sampling of command config entries
maintain your code on github so you get a free issue tracker and such
register with the icinga registry since the nagios one has been broken lately

btw

The locals don't like it if you revise your code in the same post.  So if you want another review, please start another thread.  Dropping a link to the new one in the comments here is also nice.  :-)


Script that creates an active CSS on link

Please consider that using Javascript might not be the best solution. If you use something like PHP, passing a variable to the file generating the html setting which one is active is a cleaner solution.

Anyway..

First it seems that the following variable is unused and can be removed:

var link = window.location.pathname;

Then this line:

var currentPageName = window.location.href.match(/[^\/]+$/)[0];

will trigger an error if the url is root (http://www.example.com/)
and it's the same as in these ifs, which also can be combined to one:

if (window.location.href.indexOf("R") > -1) {
    var currentPageName = window.location.href.match(/[^\/]+$/)[0];
}

if (window.location.href.indexOf("C") > -1) {
    var currentPageName = window.location.href.match(/[^\/]+$/)[0];
}

which means that one of them is redundant and can be removed.

You can also remove var in all but the first  var currentPageName

An easier way to add the active effect would be to use the attribute contains selector like this:

selector = '.main-navigation ul li a[href*="'+currentPageName+'"]"'
$(selector).css({
    'color': 'white',
    'font-weight': 'bold',
}).addClass('active');

This means that the complete code could look like this:

var match = window.location.href.match(/[^\/]+$/);
var currentPageName = '';

if (location.pathname == '/') {
    currentPageName = 'MD';
} else if (match != null) {
    currentPageName = match[0];
}

var hl = $('#ih').val();

if (hl == 'True') {
    currentPageName = 'WVD';
}

selector = '.main-navigation ul li a[href*="'+currentPageName+'"]"'
$(selector).css({
    'color': 'white',
    'font-weight': 'bold',
}).addClass('active');


The logic you're using for validating a date looks fine to me.

The code is not bad, but here are a few suggestions for improvement:

IIFE

All of the defined variables and functions leak into global scope. Put them all inside the IIFE to avoid the scope leak: (Note the trailing semicolon)

(function(){
    var _monthList = ...
    function createYears() {
        ...
    }

    ...

    createYears();
    createMonths();
    createDates();
    registerEvents();
})();

And it's better to execute this function only when the document is ready, so it works regardless of when the script is loaded:

$(function() {
    ...
});

Naming

Don't prefix your variable names with an underscore. This convention is only used for private properties of objects, which you don't have in your code.
Use day instead of date when you mean the day of the month (e.g. createDays, days, #cbDay, day), Javascript's Date#getDate method is poorly named. Then you can rename dateObj to date.
Don't prefix your elements' IDs with cb (they're not callbacks). Simply use year, month and day (element IDs don't clash with variable/function names, so they don't need to be prefixed).
lblError -> errorLabel. No need to abbreviate.
dataset -> options, to be more descriptive.

Make each function do one thing

createYears both generates the year array and manipulates the DOM. Generate the array outside the function instead: (like you did for createMonths)

var yearList = (function() {
    var years = [];
    for (var i = 2000; i<=new Date().getFullYear(); i++){
        years.push({id:i, name:i});
    }
    return years;
})();

Do the same for createDays.

validateDate both checks if the date is valid and updates #errorLabel accordingly. Use a seperate function for testing if a date is valid:

function isDateValid(day, month, year) {
    var date = new Date(year, month-1, day);
    return day == date.getDate();
}

createOptions

Every time createOptions is called, the return value is set as the HTML value of an element. It's better to pass the element to createOptions as an argument and let it manipulate the element to eliminate this repetition.

Each option passed to this function is known to have id and name properties, so you don't need to check which properties are present.

You don't need to set the IDs for the options, it's enough to set the values. This means the id property of the options in the array argument should be renamed to value (Change id to value when generating the arrays).

Finally, you can use jQuery for creating the elements:

function createOptions(select, options) {
    options.forEach(function (option) {
        select.append($('<option>', { text: option.name, value: option.value }));
    });
}

Now createYears looks like this:

function createYears() {
    createOptions($('#year'), yearList);
}

Which is so short that there is no need to make createYears, createMonths and createDays multiple functions.

Seperating logic from DOM

Put all the functions that are responsible for the logic first, and after them put code that accesses the page's DOM: (i.e. code that has strings with specific element IDs)

var dayList = ...;
var monthList = ...;
var yearList = ...;

function createOptions(select, options){
    ...
}

function isDateValid(day, month, year) {
    ...
}

createOptions($('#year'), yearList);
createOptions($('#month'), monthList);
createOptions($('#day'), dayList);

$("select").on("change", function validateDate() {
    var day = $("#day").val(); /* NOTE: No need to use additional selectors when you're already selecting by ID */
    var month = $("#month").val();
    var year = $("#year").val();
    if(year && month && day) {
        /* NOTE: I used a ternary expression to shorten the code */
        $("#errorLabel").text(isDateValid(day, month, year) ? "" : "Please select a valid date");
    }
});

This makes the code easier to understand and more reusable (e.g. it will make having multiple date forms on the same page easier).

Good luck!


One simple thing that would clean this up is to use the else if keyword. So you would do:

if indexPath.row == 0
{
    // code here
}
else if indexPath.row == 1
{
    // code for 1 here
}
else if indexPath.row == 2
{
    // code for 2 here
}
else if indexPath.row == 3
{
    ...etc.
}

This eliminates the nesting and the excessive number of closing curly braces at the end.

You could also remove the intermediate values. So one of the bodies of the "if" statement might look like this:

if indexPath.row == 2
{
    print("gender type pressed")
    navigationController?.pushViewController(GenderTypeSelector(), animated: true)
}


SmartRandom bombing strategy for Battleship game

It looks good to me. The random_device and its distribution were the only things to catch my attention.

It seems like overkill in this case. random_device produces cryptography quality number sequences, which is probably much more accuracy than you need. Since its implementation is platform-specific, it is hard to tell how much more expensive a random_device is, but I'd start with something more usual, like a Mersenne Twister seeded with one call from a random_device - That's a very common usage pattern by the way.
No apparent reason to make it a global. That makes your code unsuitable for multithreaded use. (I would expect random_device to hold some member state that is most likely not synchronized). A member instance would be cleaner and avoids threading issues.
Lastly, r is a bit of a weak name for a file-scoped global. Eventually you might want to declare loop counters and iterators named r and that could shadow the random generator... Perhaps consider a slightly longer name just to avoid this potential for shadowing.


Atomic fixed-size parallel std::vector wrapper

You haven't shown how you intend to use this thing, so it's impossible to say for sure whether it "works correctly." For example, obviously it doesn't work if you're planning to use it like this:

AtomicFixedSizeVector<int> v;
v.reserve(100);
std::thread t1([&]() {
    while (v.size() < 10) v.push_back(42);
});
std::thread t2([&]() {
    while (v.size() < 10) std::this_thread::sleep_for(1ms);
    std::cout << v.m_data[0] << "\n";  // DATA RACE!
});

Obviously it won't compile if your type T isn't default-constructible. You could address that idiomatically by adding

static_assert(std::is_default_constructible_v<T>);

to the top of the class body — thus hopefully reassuring the client-programmer that the crazy template error message they just got was intended, and not a bug.

Your reserve method can only be called once, and m_count increases monotonically. Think about whether to implement a clear() method, and what it might do. Think about whether reserve() should reset m_count to zero or not.

My kneejerk reaction is that reserve shouldn't exist at all, and that you should force the user to construct the container with the right capacity to begin with:

explicit AtomicFixedSizeVector(int capacity);

ALX23z is right that what you mean is FixedCapacity, not FixedSize.


You have been posting in CodeReview for about 1 year, so while you are still learning C# and a hobbyist, you are not a total newbie.  Therefore, you should expect the reviews to be a little more critical.  Do understand that "critical" does not mean "mean spirited" but rather more blunt while also being constructive.
What disappoints me most in your code is its structure.  You put almost everything in Main.  I would challenge you to step back and look at the big picture of what goes on:

UI Input - Ask for input values
Business Logic - manipulate or
process those input values
UI Output

So you could make your Main to look similar to those items.  This is a major principle to keep in mind: Separation of Concerns, namely your business logic and UI should be separate.  But Separation of Concerns also applies to breaking up a monster method that is doing too much into smaller methods where each call does a specific thing.
There is also the .NET guideline that you should limit the scope of a variable.  I am an old-timer who worked with VB and way back then it was common to define ALL the variables at the top of a method and then use them later.  With .NET, this is not needed.  In particular, I am referring to the variable textWriter.  You define at the very top but start to use it at the bottom.
I also do not like the name textWriter.  I personally would use a generic name of writer just in case you every change to a different implementation.  But that really doesn't matter because you don't need that variable at all.  You use 4 lines of code when only 1 is needed:
File.WriteAllLines(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"),
                   BigSorting(unsorted));

I have also observed in a history of your posts, and the same is true here, that you code to a specific implementation of array.  Your methods can have a broader reach and re-usability if you coded to a more basic implementation, such as IList or even IEnumerable.  Consider:
static IOrderedEnumerable<string> BigSorting(IEnumerable<string> items) => items.OrderBy(s => s.Length).ThenBy(s => s);

The input is no longer restricted to being an array, and I do not create an entirely new array for output.  I also changed the parameter name to items because I don't care if someone inputs a unsorted collection or one sorted in some other order.  Doesn't matter to the method.
What if you wanted to output to an array?  Then use .ToArray() when you make the call BigSorting rather than doing it inside BigSorting.
So that addresses quick and simple sorting use LINQ, which produces a 2nd array.  There is an alternative that doesn't require a 2nd array.  I haven't tested with huge number of elements or crazy long values.  I leave that to you and hopefully you will find it more performant.
I am referring to making a custom IComparer.  See this link.  Example:
public class NumericStringComparer : IComparer<string>
{
    // https://docs.microsoft.com/en-us/dotnet/api/system.array.sort?view=net-5.0#System_Array_Sort__1___0___System_Collections_Generic_IComparer___0__
    public int Compare(string x, string y)
    {
        // Compare x and y as numbers without leading zeroes.
        if (x == null)
        {
            return (y == null) ? 0 : -1;
        }
        if (y == null)
        {
            return 1;
        }
        if (x.Length < y.Length)
        {
            return -1;
        }
        if (y.Length < x.Length)
        {
            return 1;
        }
        return x.CompareTo(y);
    }
}

Now you would use it like:
Array.Sort(unsorted, new NumericStringComparer());
File.WriteAllLines(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"),
                       unsorted);

Except I now have a problem with the name "unsorted".  While the array containing inputs was initially unsorted, I later sorted in-place to that very same array, so in WriteAllLines the name choice of unsorted is misleading.  Thus, I would choose a generic name of items for the array.


Converting audio to different file formats

Overall

Design first.

Name and semantic of your class

  I have this code that converts audio to different file formats.

Not exactly, your code is a client to an Encoder, that converts audio to different file formats.
In design, it is very important to be certain about the reason and semantic of an object. So first, the name AudioEncoderDecoder is bad. It says nothing about the sematic of the object. I would call it AudioFormatConverter as it converts one audio file format to another.

Public methods

public void encodeAudio(File source, File target, String mimeType);

a) Naming encodeAudio() is not clear, convert() would be clear and consistent with the classname.

b) Parameters: source, target file seems good. But why would I pass in the mimeType? And how can I specify which target format I choose?

Expected method signature:

public void convert(File source, File target) throws AudioConversionException();

One conversion method in the public interface, source and target file, the mime type is guessed by the file extension. You could add another public method, where you take in the mimetype, as needed. But keep the interface of your class as simple, logic, consistent and understandable as possible.

I would declare an checked exception for error handling, formats not avail or whatever.

Design Patterns

If there will be more formats, codecs, mimetypes you could take a look at Chain of responsibility or Dispatcher/Command pattern.
These patterns also add flexibility to easily support more mimetypes at runtime.
Without those patterns, you may get a mid-to-big if/then/else block.

Possible Design with Command, Strategy pattern applied:

AudioFormatConverters interface is format-agnostic, this means it is possible to implement a converter, that doesn't use Files but only InputStreams or byte[] arrays.
Concrete AudioFileFormatConverter converts from and to Files, and holds a list of supported ConversionCommands
ConversionCommand encapsulates logic to convert things, a client can check via isSupported(source, target) if the source-format and target-format is supported by this command (handler would by a common name, too)
Mp3ToOggConversionCommand Every conversion is a command, one can decide that this is too much, but with that you can save state in the command, like executation duration, error states, sizes, redo, undo, execute asynchronous...
ConversionStrategy with Impl EncoderConversionStrategy encapsulates the concrete implementation of conversion, that is your duplicate code, this strategy how to convert 2 files by using the Encoder

Note that ConversionCommands should be prototypes, so that each execute happens in its own Command instance.

Now in code, you would setup the AudioFileFormatConverter and add the supported ConversionCommands to it.

Existing code

Obey the basic OO principles.

DRY - Don't repeat yourself. If you find code is duplicate, introduce
abstractions or extract methods.
Use interfaces

In your case you can easily improve the code if you generalize the mp3ToOgg and oggToMp3 methods.

So that you have only one general method for converting with the signature:

private void convert(File source, File target, String format, String codec);