Method to return a collection of objects, filtered by a string

I'll ignore your naming conventions/etc as I know that's not what you're asking about.

Since the VehicleCollection object already inherits from IEnumerable through the List<> inheritence, you can query the collection as a list through the 'this' keyword.

That means you could write up your search method like:

public VehicleCollection GetVehicles(string searchTerm = "")
{
    // Null and white-space check for sanity
    if(string.IsNullOrWhiteSpace(searchTerm))
    // We're assuming if the search term is bad, we return everything.
    // This isn't standard practice - usually we return nothing
        return this;

    var matches = new VehicleCollection();
    matches.AddRange(
        this.Where(v=>v.ID.Equals(searchTerm) ||
                    v.Make.Equals(searchTerm) ||
                    v.Model.Equals(searchTerm)
    // I personally prefer to be explicit in what I'm selecting, but it's your choice
        ).Select(v=>v));

    // inline IF because I'm lazy
    // again, we're returning everything if there are no matches,
    // which isn't standard practice.
    return matches.Any()? matches: this;
}

Hope that helps!


Welcome to Code Review,

I do not know how to solve your problem, however, your code could use polishing.

Magical constants; your code is littered with them, use constants instead
Undocumented magical constants, I can guess what 365 or 12 is used for, other constants like 32083 could use a comment or could show the calculation of how you got there
Naming; todDay, todMonth and todYear are terrible names
Naming; at, ty and mt are even worse
Casing; be consistent, you mix underscores with casing and even your casing is not consistent ( calc_julianToday <> calc_juliandate )
Indenting! Your indenting is all over the place and distracts the reader
Repeating / DRY;

I do not write C++ but can you not write calc_julianToday() as

int julian::calc_julianToday()
{
  time_t t = time(0);
  struct tm *now = localtime( &t );
  return julToday =  calc_juliandate( now->tm_mday, now->tm_mon+1, now->tm_year+1900 ) ;
}


Project Euler, Problem 273: finding perfect-square partitions

The code

The formatting has a number of PEP8 violations.

It's not obvious from the name what candidate_range does. It seems to be a wheel for the sieve. Normally that would be inlined in the sieve; even if you prefer not to do that, you could place the function inside sieve to make its scope clear.

I don't find sieve_list a very helpful name. In general for sieving I prefer is_composite, inverting the booleans from the way you've done it. Similarly for each_number: it reads well on the first line which uses it, but very oddly on the others.

goodprimes = []
for prime in primes:
    if prime%(4)==1:
        goodprimes.append(prime)

It's more Pythonic to use comprehensions:

goodprimes = [p for p in primes if p % 4 == 1]

#get a number that works

What does this mean? It looks more like noise than a useful comment to me.

for L in range(1, len(goodprimes)+1):
    sumf=0
    for subset in itertools.combinations(goodprimes, L):

I don't know why itertools doesn't have a function to give all subsets, but it seems like the kind of thing which is worth pulling out as a separate function, both for reuse and for readability.

        max=2**L/2

What does this do?

        n=1
        for x in subset:
            n*=x

Consider as an alternative

from functools import reduce
import operator

    n = reduce(operator.mul, subset, 1)

        for b in range(math.floor(math.sqrt(n/2)), math.floor(math.sqrt(n)+1)):
            a=math.sqrt(n-b*b)
            if a.is_integer() and b>=a:

Why floors rather than ceils?

Are you certain that math.sqrt on an integer is never out by 1ULP?

Why is b>=a necessary? (Obviously b==a is impossible, and isn't the point of the range chosen to force b > a?)

                sum.append(a)

Is this for debugging? I can't see why you wouldn't just add a to a total.

NB sum is aliasing the builtin function for adding up the values in a list.

                    #q+=1

??? I can't see any other mention of q.

The algorithm

There are a few Project Euler problems which fall to brute force, but in general you need to find the right mathematical insight. Given the way this question is structured, you probably need to figure out how to find \$S(n)\$ given the prime factorisation of \$n\$.


Grabbing SQL records: Nullable bool to bool

// as long as we found a result, we're happy
if(result != null)
{
    return (bool)result;
}

This could be written as simply:

if (result.HasValue)
{
    return result.Value;
}

bool? is shorthand for Nullable<bool>, a generic value type with reference type semantics. Basically Nullable<T>.Value is a T, so there's no need to cast anything.

Also, being a value type, initializing it is redundant.

bool? result;

Is entirely sufficient.

Avoid cluttering your code with comments that don't bring anything to the table:

// as long as we found a result, we're happy

Good comments should say why the code does what it does - don't bother commenting just to state the obvious, or to rephrase what the code is already saying.

If this needs a comment every time it's used:

// log and email error
ErrorContinue(recordID, strMessage);

...then perhaps the ErrorContinue method needs a better, more descriptive name?

You're catching a System.Exception here:

    try
    {
        // Query our existing list of StateConfig objects for a match, then return the value of RoundMinutes.
        result = (from x in listStateConfig
                       where x.State == stateAbbrev
                       select x.RoundMinutes).First();

    }
    catch (Exception e)
    {
        //...
    }

But it looks like you're only handling the InvalidOperationException that .First() would throw when there aren't any items matching the where criteria.

If the query is meant to return only 1 record, use .Single(), not .First(). And if the query can return no records, use .SingleOrDefault().

The problem is that you're projecting the result and Selecting .RoundMinutes, which is a value type and can't be null, so SingleOrDefault() would return false for an bool value, because default(int) == 0.

You could instead select the actual StateConfig object, and boil the code down to this:

public bool StateRoundsToQuarterHour(int recordId, string stateAbbrev)
{
    var config = _stateConfig.SingleOrDefault(x => x.State == stateAbbrev);
    if (config != null)
    {
        return config.RoundMinutes;
    }
    else
    {
        var message = string.Format("State '{0}' does not exist in table, but RecordId {1} belongs to that state.", stateAbbrev, recordId);
        _logger.Warn(message);
        return false;
    }
}

Notice Id vs. ID, _logger.Warn vs ErrorContinue, message vs. strMessage, and _stateConfig vs listStateConfig. Don't try to encode the type of a variable into its identifier name, that's bad Hungarian notation, and it's not the type that's useful but what the variable it actually used for.

I'm prefixing private fields (I assumed listStateConfig was a private field here) with an underscore, but you could alternatively qualify them with the this keyword - that's personal preference.


Counting the occurrences of bank account numbers for SPOJ challenge

One area of inefficiency is here:

for (i = 0; i < n; ++i) {
  std::getline(std::cin, accounts[i]);
}
std::cout << "\n";
std::map<std::string, int> count;
for (i = 0; i < accounts.size(); ++i) {
  auto map_it(count.find(accounts[i]));
  if (map_it != count.end()) {
    map_it->second++;
  } else {
    count[accounts[i]] = 1;
  }
}

You're reading each account number, storing them then going back through the data to get the counts.  The map class allows for a key that doesn't exist to create an entry on the fly.  Using this will eliminate the second loop:

std::string temp = "";
std::map<std::string, int> count;
for (i = 0; i < n; ++i) {
  std::getline(std::cin, temp);
  count[temp]++;
}
std::cout << "\n";


You can use NSPredicate:

NSArray* productsToDelete = [allLocal filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT (productId IN %@)", allRemoteIds]];
for(Product* product in productsToDelete) {
    [product delete];
}

This will for sure improve readability of your code. I'm not sure about performance, but I would assume that Apple's implementation of filteredArrayUsingPredicate should be fast enough. If you really want to know it, do some profiling.

You can also read great article about performance of collections in Objective-C:

http://www.objc.io/issue-7/collections.html


Count number of pairs of strings which on joining contain all vowels

Your Code:

Don't use <bits/stdc++.h>, it's unportable and inefficient. See "Why should I not #include <bits/stdc++.h>?" for the details.
Don't use using namespace std;, that namespace just isn't designed for it. See "Why is “using namespace std” considered bad practice?" for more background.
Invest in some better names. Being too parsimonious there hurts, even though brevity is a virtue.
Format your code consistentently.

Sometimes you have space around binary operators (other than comma, which only should be followed by a space), sometimes you forget.
Add a space after ; when it isn't followed by the next line, meaning a loop's head.
Also add a space after #include, for, if, and while.
You don't have to use a block for single statements, but please don't put them on the same line, at the least separate them with a space.

C++ does not have VLAs. Just use a std::vector instead.
While in general, keeping the scope of a variable minimal is a good idea, there are exceptions. One of them is efficiency. Always spinning up a new std::string means being unable to re-use the buffer. Not that you really need the whole string at once, anyway.
One reason you should minimise a variables scope, is that it allows you to initialise it to the proper value, instead of leaving it uninitialised or, horrors of horrors, adding a spurious dummy-initialisation.
That also allows you to avoid writing the type (Almost Always auto), and making it const or even constexpr.
There are compound-assignment-operators for most binary operators. Like a |= b for a = a | b. Using them leads to shorter, more readable code.
When you want to output a single character, why not use a character-literal? It's potentially even slightly more efficient.
return 0; is implicit for main(). Take it or leave it, but be aware.

The Algorithm:

Your algorithm uses \$O(\#characters+\#words^2)\$ time and \$O(max\_word\_length + \#words)\$ space.

An optimal algorithm only needs \$O(\#characters+2^{\#vowels})\$ time and \$O(2^{\#vowels})\$ space:

For every word:

Set the bits for all the vowels contained.
Increment the count on the indicated bin.

For every vowel:

Iterate the bins containing words with that vowel.
Add the count to the respective bin without that vowel.

For all bins:
Multiply the count in the bin with the count in the complementary bin, and add that.
Subtract twice the count in the bin for words containing all vowels. Those account for all self-pairings.
The answer is half the calculated number, as we counted double.

Exercise for the attentive reader: Save half the multiplications this algorithm uses.


Navigation bar React component, with a "back" and a "close" variant

Without knowing the context of how this navigation bar is used in your app its hard to say which one would be more preferable. Does the navigation type dictate only the styling of the navigation bar or also some type of action too? Is the navigation type only tied to some sort of button within the navigation bar that displays differently and points to a different direction? Maybe doing something like this would work for that:

<NavigationBar>
    <NavigationBar.ActionButton type='back' />
</NavigationBar>

All the variants you provided seem like good solutions, I think you are in best judgement here to decide what fits your apps needs.


Where to protect DB data against XSS injections?

One might forget HTML encoding, but how about doing it automatically:

class HtmlEncode {
    private $obj;

    public __construct($obj) {
        $thos->obj = $obj;
    }

    public __call($method, $args) {
       $ret = call_user_func_array($this->obj, $args);
       if(is_scalar($ret)) return Reform::HtmlEncode($ret);
       return new HtmlEncode($ret);
    }

    public __get($name) {
       if(is_scalar($obj->$name)) return Reform::HtmlEncode($obj->$name);
       return new HtmlEncode($obj->$name);
    }
}

Create $data = new HtmlEncode($this) and now you can safely use:

<?php echo $data->myData; ?>

<?php echo $this->myMethod()->name; ?>

You always get either html encoded string or object wrapped in HtmlEncode class.

I wrote it out of my head, so it's untested, it should check if the method or variable is defined, handle arrays, but it's left up to you ;)


Find the uncommon elements from two sets

Is this a method?  You can't just plop code anywhere in Java.

The name of the operation is symmetric difference, so you should probably call it that.

Here's a more compact implementation.

private Set<T> symmetricDifference(Set<T> a, Set<T> b) {
    Set<T> result = new HashSet<T>(a);
    for (T element : b) {
        // .add() returns false if element already exists
        if (!result.add(element)) {
            result.remove(element);
        }
    }
    return result;
}


Bash - Passing arguments with "$@" to either 'sudo su' or 'sh'

The only simpler way to do this I've come up with is just to sudo every time and not worry about whether you're already the right user or not.  But overall it seems pretty straight forward and it should work fine as-is.  Some other suggestions:

Indent your code with the function.  Leaving the heredoc alone is ok.
Use [[ for conditionals.  See https://unix.stackexchange.com/a/306115/79839 for more context.
It is more modern to use $() for subcommands instead of backticks (``).  Parenthesis () are also used for creating subshells so the $() is just substituting the result of a subshell.


Using a for-loop or sleeping to wait for short intervals of time

The biggest problem with using a for-loop to do this is that you are wasting CPU power.

When using sleep, the CPU can, in a sense, take a break (hence the name "sleep") from executing your program. This means that the CPU will be able to run other programs that have meaningful work to do while your program waits.

But in the for-loop the CPU continuously have to do work to increase a variable. For what purpose? Nothing. But the CPU doesn't know that. It's told to increase the variable, so that's what it will do. Meanwhile, other programs aren't given as much time to do their work because your program is taking up time.

Please don't waste CPU power, use the sleep approach.

As stated in a comment, additionally, the compiler may optimize out an empty loop, and the attempt to pause may be lost. So either you will waste CPU power, or you will not pause at all.


They're right. While "</Whatever>" is hard to read itself (YMMV), the constants make it even worse.

Magical constants in a code are bad and should usually be extracted as you did. But if there are many of them and each gets used just once, it's counterproductive.

The best solution would be something like

new XmlBuilder(body)
    .start("ProductId").append(product.getId()).end()
    .start("Size").append(product.getSize()).end();

or some of the million existing XML tools. If the constants get used multiple times, then something like

new XmlBuilder(body)
    .start(WSConstants.WS_PRODUCT_ID).append(product.getId()).end()
    .start(WSConstants.WS_SIZE).append(product.getSize()).end();

makes more sense. Then you may consider using static imports to keep it shorter.

The whole XmlBuilder is rather trivial, it mostly delegates to the StringBuilder and remembers the opened tags using a stack. As stated by  aetheria, it should also escape the appended values when needed.

For redundancy lovers, something like

new XmlBuilder(body)
    .start(WS_PRODUCT_ID).append(product.getId()).end(WS_PRODUCT_ID)
    .start(WS_SIZE).append(product.getSize()).end(WS_SIZE);

may be more "cool". Anyway, it's more XML-like (just don't ask me what's good for).

Note the inconsistency of "PRODUCT_ID" vs. "SIZE_TEXT", where the former means indeed "productId" while the latter means just "size". This should be fixed (like I did in my snippets).


Utilize loop or other efficient way to find string and copy offset columns to certain cells

Option Explicit is missing from your code. From the menu at the top under Tools>Options>Editor tab>Code Settings group>Require Variable Declaration <-- toggle that check box on. It will thereafter add the Option Explicit statement to all modules. You'll have to add this manually to any currently existing modules. This mandates you have Dim foo as Range to declare your variables before usage. Not having this leads to avoidable errors. Turn it on and leave it on. Future-you will thank you for doing so.

Your Sub statement is implicitly Public since it is missing the access modifier. Writing Public Sub FindString() makes in known that you intentionally made it publicly viewable.

Indentation. Indenting your code by a tab helps identify where a Sub begins and ends. Same goes for blocks of code such as If...End IF.

Variable names are typically Camel Case. This means the first word is lower cased and the first letter of subsequent words is upper cased. If you had a variable worksheetContainingWordsToFind that would be an example of came Camel Case. Your Sub name FindString is in Pascal Case where the first letter of every word is upper cased. Subs/Function are Pascal Case while variables are Camel Case.

Your variable MasterSheet is misleading. It's actually a Workbook. Have your variables be what they say they are. Dim MasterSheet As Worksheet is an improvement to match up with what it says it is. Even better for it to be sourceSheet. That way you can have

Dim sourceBook as Workbook
Set sourceBook as Workbooks.Open("\\mypath\text.xlsx")

Dim sourceWorksheet as Worksheet
set sourceWorksheet = sourceBook.Worksheets("sheet1")

Dim foundTransferString as Range
Set foundTransferString = sourceWorksheet.Cells.Find(What:="Transfer <= 30 minutes")

Dim foundEMPString as Range
Set foundEMPString = sourceWorksheet.Cells.Find(What:="End of Month Performance (EMP)"

which has your code self documenting.

The above code also eliminates a wall of declarations at the start. I'm of the opinion that declaring a variable just before you use it helps aid in refactoring and eliminating unused variables. Rather than needing to right click on the variable to display the context menu>Definition to find where it's declared you have it right above the first use.

The code ThisWorkbook.Worksheets("WSLHD") can use the object (Excel Worksheet) directly. In the Project Explorer, found in the menu at the top under View>Project Explorer (Hotkey: Ctrl+R). Double click the sheet under Microsoft Excel Object to display the code behind pane for that Worksheet object. Under View>Properties Window (Hotkey: F4) display the properties window. At the very top where it says (Name) you can rename the worksheet CodeName to a more descriptive name. I kept WSLHD as I don't know what that means, another reason to have self describing names. Thereafter you can use that object directly with WSLHD.Cells.Find instead of in the roundabout way of assigning a worksheet variable with ThisWorkbook.Worksheets("WSLHD"). The latter is prone to breaking if the tab is renamed.

Your comment "... there are many more strings" is a sign-post indicating you want a function. This function has 2 input variables that you provide as arguments. It searches the sheet you indicate looking for the string value. If it finds the result it sets the last variable outFoundCell which is passed ByRef so the assignment applies is reflected in the calling procedure. If the string was found the TryFind = Not outFoundCell Is Nothing assigns True to the function, otherwise it assigns False.

Private Function TryFind(ByVal searchForValue As String, ByVal sourceSheet As Worksheet, ByRef outFoundCell As Range) As Boolean
    Set outFoundCell = sourceSheet.Cells.Find(What:=searchForValue)
    TryFind = Not outFoundCell Is Nothing
End Function

You couple that with a method to populate the cells

Private Sub PopulateCellsWithOffsetResults(ByVal foundCell As Range, ByVal populationSheet As Worksheet, ByVal populationRow As Long)
    populationSheet.Cells(populationRow, "B").Value2 = foundCell.Offset(0, 1).Value2
    populationSheet.Cells(populationRow, "C").Value2 = foundCell.Offset(0, 2).Value2
    populationSheet.Cells(populationRow, "F").Value2 = foundCell.Offset(0, 3).Value2
End Sub

And you can then invoke the function in the following manner. You first search for the string. If it's found it then enters the true part of the If...Then...Else Statement and populates the information.

If TryFind("Transfer <= 30 minutes", sourceWorksheet, foundCell) Then
    PopulateCellsWithOffsetResults foundCell, WSLHD, 8
End If

Doing all that you end up with the code below. There is more that can be done because the population rows 8, and 9 are static numbers. You probably want a dynamic row that changes as things are populated.

Option Explicit

Public Sub SearchForStringsAndPopulatedOffsetValuesOnAnotherWorksheet()
    Dim sourceBook As Workbook
    Set sourceBook = Workbooks.Open("\\mypath\test.xlsx") 'Master sheet where data is coming from
    Dim sourceWorksheet As Worksheet
    Set sourceWorksheet = sourceBook.Sheets("sheet1")

    Dim foundTransferCell As Range
    If TryFind("Transfer <= 30 minutes", sourceWorksheet, foundTransferCell) Then
        PopulateCellsWithOffsetResults foundTransferCell, WSLHD, 8
    End If

    Dim foundEndOfMonthPerformanceCell As Range
    If TryFind("End of Month Performance (EMP)", sourceWorksheet, foundEndOfMonthPerformanceCell) Then
        PopulateCellsWithOffsetResults foundEndOfMonthPerformanceCell, WSLHD, 9
    End If

    sourceBook.Close
End Sub

Private Sub PopulateCellsWithOffsetResults(ByVal foundCell As Range, ByVal populationSheet As Worksheet, ByVal populationRow As Long)
    populationSheet.Cells(populationRow, "B").Value2 = foundCell.Offset(0, 1).Value2
    populationSheet.Cells(populationRow, "C").Value2 = foundCell.Offset(0, 2).Value2
    populationSheet.Cells(populationRow, "F").Value2 = foundCell.Offset(0, 3).Value2
End Sub

Private Function TryFind(ByVal searchForValue As String, ByVal sourceSheet As Worksheet, ByRef outFoundCell As Range) As Boolean
    Set outFoundCell = sourceSheet.Cells.Find(What:=searchForValue)
    TryFind = Not outFoundCell Is Nothing
End Function

The Sub PopulateCellsWithOffsetResults and Function TryFind are Private and thereby not visible outside of the module because they are an implementation detail. You aren't concerned with how they work, rather that they do work as evidenced when you run SearchForStringsAndPopulatedOffsetValuesOnAnotherWorksheet which should have a better more descriptive name. That's just what I came up with since I really don't know everything that you're populating.


Program to accept numbers, then calculate the mean, median, and range

On top of Thomas Ward answer, here is a short and important comment:

More beautiful functions

Your functions are performing some mathematical computations and handling the formatting to show the result to the 2 users. These correspond to 2 concerns that could be separated.

Also, your functions rely on the list_one global variable. It would be clearer to have this provided to the functions using an argument.

You'd have something like:

def mean(lst):
    return sum(lst) / len(lst)

def range_(lst):
    return lst[-1] - lst[0]

def median(lst):
    length = len(lst)
    if length % 2 == 0:
        return sum(lst[length//2-1:length//2+1]) / 2
    else:
        return lst[length//2]

...
            print('Mean: ' + str(mean(list_one)))
            print('Median: ' + str(median(list_one)))
            print('Range: ' + str(range_(list_one)))

These are easier to understand and to reason about. They are also easier to test. This is an interesting exercise that you can try to practice.

Small improvements in median

The expression length//2 is used in multiple places which makes the code tedious to read and less efficient than it could be.
Using a temporary variable makes things clearer:

def median(lst):
    length = len(lst)
    mid = length//2
    if length % 2 == 0:
        return sum(lst[mid-1:mid+1]) / 2
    else:
        return lst[mid]

From here, I think it's pretty good already. Let's see what can be still be done for the sake of learning new techniques.

When you want to compute both the quotient and the remainder of the division, you can use "/" and "%" just like you did. Another option is to use the divmod builtin which returns both directly:

def median(lst):
    length = len(lst)
    mid, rem = divmod(length, 2)
    if rem == 0:
        return sum(lst[mid-1:mid+1]) / 2
    else:
        return lst[mid]

The operation sum(lst[mid-1:mid+1]) / 2 looks a lot like things we've just somewhere else: we compute the sum of a list and we divide by the number of elements which is happens to be 2.

We could reuse our mean function here.

def median(lst):
    length = len(lst)
    mid, rem = divmod(length, 2)
    if rem == 0:
        return mean(lst[mid-1:mid+1])
    else:
        return lst[mid]

To go further, we could use the ternary operator to have a single return value.
We could also use the fact that in a boolean context, non-zero integers are equivalent to True and zero is equivalent to false.
This would lead to the following code which is, from my point of view, not really better:

def median(lst):
    length = len(lst)
    mid, rem = divmod(length, 2)
    return lst[mid] if rem else mean(lst[mid-1:mid+1])


Making a semi-random order of an array, based on a string

Random numbers, hashes and precision.

Good hasher.

The hash function you use is very poor with it only producing unique hash values for the first 8 characters of a string.

The following words all produce the same hash

"characters","charactesr","charactezz" = 8246171808294230000

The reason is that numbers when used in computers have a limited precision. Once you go over that precision you can no longer add numbers that are smaller.

For example adding 100 to the hash number does nothing the num+100 === num returns true.

var num = 8246171808294230000
console.log(num + 100 === num); // >> true

To generate a good hash you need to limit the size of the hash number. This can easily be done by just using integer math and bitwise manipulation.

An improvement (not perfect) hasher

function stringTo32BitHash(str){
     const a = 14827;  // Use a prime
     var v = 0;
     for(var i = 0; i < str.length; i += 1){
         v = ((v*a) + str.charCodeAt(i))%0xFFFFFFFF;
     }
     return v;
}

Pseudo random shuffle.

Next your shuffle is not working very well. You are not providing enough variance in the selection of which array items to reorder. With very different hashes producing the very same shuffle.

For hash 8.97895922819539e+21 the result is 4,1,0,2,8,9,3,6,5,7
For hash 8.978959228225448e+21 the result is 4,1,0,2,8,9,3,6,5,7

The best way to use a hash to scramble a list is to use the hash as a seed for a pseudo random number generator. The seed ensures that the sequence of random numbers will be the same for the same seed. Unfortunately javascript does not provide a seed value that we can access for it's Math.random() function so we have to create our own.

The most basic pseudo random number generator is seed = (A * seed + B) % M where A,B,M are large integers. Each time the function is called a new seed is generated and return as a random value. The seed is also used as the seed for the next value.

Once you have a good sequence of random values you can use them to create a better shuffle.

Putting it all together.

Thus a rewrite of your code with a random number generator to do the shuffling and an improved string to hash function.

// creates a random number generator function.
function createRandomGenerator(seed){
     const a = 5486230734;  // some big numbers
     const b = 6908969830;
     const m = 9853205067;
     var x = seed;
     // returns a random value 0 <= num < 1
     return function(seed = x){  // seed is optional. If supplied sets a new seed
         x = (seed  * a + b) % m;
         return x / m;
     }
}
// function creates a 32bit hash of a string
function stringTo32BitHash(str){
     var v = 0;
     for(var i = 0; i < str.length; i += 1){
        v += str.charCodeAt(i) << (i % 24);
     }
     return v % 0xFFFFFFFF;
}
// shuffle array using the str as a key.
function shuffleArray(str,arr){
    var rArr = [];
    var random = createRandomGenerator(stringTo32BitHash(str));
    while(arr.length > 1){
        rArr.push(arr.splice(Math.floor(random() * arr.length), 1)[0]);
    }
    rArr.push(arr[0]);
    return rArr;
 }

The need to test.

At this point I am 60% happy but by just looking at the code you can not tell how reliable it is. You need to test the function over a large set of values.

I have created two test.

Testing the random number generator.

This is a simple test, and rather than test it for standard deviation I do a visual test by graphing the distribution of the random numbers generated. I compare them to the inbuilt random function. It can give a good indication of the randomness. Why? because it's more fun...

var createImage=function(w,h){var i=document.createElement("canvas");i.width=w;i.height=h;i.ctx=i.getContext("2d");return i;}
var canvas = createImage(512,200);
document.body.appendChild(canvas);
var ctx = canvas.ctx;
// creates a random number generator function.
function createRandomGenerator(seed){
     const a = 54862307348;  // some big numbers
     const b = 69089698305;
     const m = 98532050673;
     var x = seed;
     // returns a random value 0 <= num < 1
     return function(seed = x){  // seed is optional. If supplied sets a new seed
         x = (seed  * a + b) % m;
         return x / m;
     }
}

ctx.font="18px arial"
var rand = createRandomGenerator(10394);
var values = new Array(canvas.width);
var valuesR = new Array(canvas.width);
for(var i = 0; i < canvas.width; i ++){
    values[i]=0;
    valuesR[i]=0;
}
function testRandom(){
    for(var i = 0; i < 1000; i ++){
        var r = Math.floor(rand()*canvas.width);
        var r1 = Math.floor(Math.random()*canvas.width);
        values[r] += 1;
        valuesR[r1] += 1;
    }
    var max = 0;
    for(var i = 0; i < canvas.width; i ++){
        max = Math.max(max,values[i],valuesR[i]);
    }

    ctx.clearRect(0,0,512,200)
    ctx.strokeStyle = "blue"
    ctx.beginPath();
    ctx.moveTo(0,canvas.height - (values[0]/max)*canvas.height);
    for(var i = 1; i < canvas.width; i ++){
        ctx.lineTo(i,canvas.height - (values[i]/max)*canvas.height);
    }
    ctx.stroke();
    ctx.strokeStyle = "red"
    ctx.beginPath();
    ctx.moveTo(0,canvas.height - (valuesR[0]/max)*canvas.height);
    for(var i = 1; i < canvas.width; i ++){
        ctx.lineTo(i,canvas.height - (valuesR[i]/max)*canvas.height);
    }
    ctx.stroke();
    ctx.fillStyle = "red";
    ctx.fillText("Red builtin Math.random()",10,canvas.height - 40)
    ctx.fillStyle = "Blue";
    ctx.fillText("Blue custom random function",10,canvas.height - 20)

    setTimeout(testRandom,100);

}
testRandom()

  note You would need to do a proper test if you were to use this function in an enterprise situation. It looks good does not cut it in the real world.

Test the shuffle and hash

Next I test the number of repeated shuffled array results for unique words, and also test the hash function to see how often it repeats a hash. There is no perfect solution but the aim it to keep the number of matches as low as possible.

Note that if the test was left to run indefinitely the number of matches as a fraction of unique words would start to approch one. This is normal. The test counts how many unique words are required to end up with 200 matched shuffled arrays then displays the score as number of words. The greater the value the better the shuffle. For a perfect result and 10 array items you would expect a score of about 38141.

// creates a random number generator function.
function createRandomGenerator(seed){
     const a = 5486230734;  // some big numbers
     const b = 6908969830;
     const m = 9853205067;
     var x = seed;
     // returns a random value 0 <= num < 1
     return function(seed = x){  // seed is optional. If supplied sets a new seed
         x = (seed  * a + b) % m;
         return x / m;
     }
}
// function creates a 32bit hash of a string
function stringTo32BitHash(str){
     var v = 0;
     for(var i = 0; i < str.length; i += 1){
        v += str.charCodeAt(i) << (i % 24);
     }
     return v % 0xFFFFFFFF;
}
// shuffle array using the str as a key.
function shuffleString(str,arr){
    var rArr = [];
    var random = createRandomGenerator(stringTo32BitHash(str));
    while(arr.length > 1){
        rArr.push(arr.splice(Math.floor(random() * arr.length), 1)[0]);
    }
    rArr.push(arr[0]);
    return rArr;
 }

var resultsEl = document.createElement("div");
document.body.appendChild(resultsEl);
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const array = [0,1,2,3,4,5,6,7,8,9];
// for an array of ten unquie values
function randomWord(maxLen){
    var wLen = Math.floor(Math.random() * (maxLen-7)) + 7;
    var str = "";
    while(wLen-- >0){
        str += chars[Math.floor(Math.random()*chars.length)];
    }
    return str;
}
var count = 0;
const resultSet = new Set();
const wordSet = new Set();
const hashSet = new Set();
var matches = 0;
var hashMatches = 0;
function testASet(){
    var c =0;
    while(c++ < 1000){
        var word = randomWord(10);
        if(!wordSet.has(word)){
            wordSet.add(word);
            var hash = stringTo32BitHash(word)
            if(hashSet.has(hash)){
                hashMatches += 1;
            }else{
                hashSet.add(hash);
            }
            var r = shuffleString(word,[...array]).join("");
            if(resultSet.has(r)){
                matches += 1;
                if(matches === 200){
                    break;
                }
            }else{
                resultSet.add(r);
            }
            count++;
        }
    }

    resultsEl.innerHTML = "Matches : " + matches + "
Hash matches : " + hashMatches+"
 Unique words : " + count;
    if(matches === 200){
        resultsEl.innerHTML += "
Test complete. Score : "+ count + " higher is better ";
        resultsEl.innerHTML += "
"+((count / 38141)*100).toFixed(0) + "% of ideal score.";
    }else{
        setTimeout(testASet,350);
    }
}
testASet()

The results of the test indicate that the function shuffle string is only 9% of the ideal situation. But if you look at the numbers you will see that there is a high rate of hash clashes. Finding a better hash function will improve the score, also I used words from 7 -10 characters long, which puts the function at a slight disadvantage.

If you are wondering how I got the ideal score, I did it with the following test that simulated the ideal shuffle.

var resultsEl = document.createElement("div");
document.body.appendChild(resultsEl);
var v = 3628800; // 10! (10 factorial)
var topV = 0;
var match = 0;
var count = 0;
var total = 0;
function test(){
    for(var i = 0; i < 40000; i++){
        var r  = Math.floor(Math.random()*v);
        if(r < topV){
            match += 1;
            if(match === 200){
                break;
            }
        }
        topV += 1;
    }
    resultsEl.textContent = "Test # : " + (count+1) + " score " +topV;
    if(match !== 200){
        setTimeout(test,100)
    }else{
        total += topV;
        count += 1;
        if(count === 100){
            resultsEl.textContent = "Mean score is : " + (total/count).toFixed(0);
        }else{
            topV = 0;
            match = 0;
            setTimeout(test,100);
        }

    }
}

test();

Improvements.

In the end the weak point is the hash generator. Using a 64bit hash will improve the result. But that will not get much more. Using the characters of the word  as an integer will give a perfect hash, but then you will have numbers with bit counts as long as the string * 8, and the random number generator would have to be able to accommodate these large integers as seeds. It leaves the question, how many bits long does the number type have to be for  the fnction to get within 99% of ideal?


Simple carbon emissions from fuel and fire calculations

Define a constant for greenhouse gases GHG to avoid hard-coding them in separate functions:

GHG = ('co2', 'ch4', 'n2o')  # greenhouse gases

get_fuel_emission_factor function.
The for loop with accumulation is concisely replaced with builtin sum function on generator expression:

def get_fuel_emission_factor(fuel):
    """Get fuel total CO2 emission factor."""
    factors = FUEL_FACTORS[fuel]
    return sum(factors['energy_factor'] * factors[f'{gas}_emission_factor'] / 1000
               for gas in GHG)

fuel_to_co2 function.
Inline variable technique can be applied:

def fuel_to_co2(fuel, quantity):
    """Get total tCO2 emission by kL of fuel."""
    return get_fuel_emission_factor(fuel) * quantity


Initializing the edge values of 2D array in Java

Could it be that you make too many assumptions? Probably you should really create a new array and not "write the fence" in an existing one.

I guess this would simplify the code by just creating an all zero arrays for the first and last element of the outer array and an array with only the zero at start and the end for all other rows.

Given your assumptions are correct. Using a function to fill the array would simplify your solution significant. In Java this is done with Array.fill.

private static int[][] initGrid(final int[][] grid) {
    assert grid.length >= 2;
    final int fence = 0;
    Arrays.fill(grid[0], fence);
    for(int[] row : grid) {
       row[0] = row[row.length -1] = fence;
    }
    Arrays.fill(grid[grid.length - 1], fence);
    return grids;
}


Using extension methods in the decorator pattern

public static GetValueOrException(this Func<string> method)
{
    try{ return method(); }
    catch(Exception ex){ return "Error: " + ex.ToString(); }
}
public Func<string> GetDescription()
{
    return ()=> { return Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\LanmanServer\\Parameters", "srvcomment", "").ToString(); };
}
bar.GetDescription().ValueOrException();

Why is this a horrible idea?

Because you just successfully eliminated the function the exceptions had originally: Error handling.

The premise when using LINQ like notations, is that you have a valid set of data in a fixed formate at each step of execution.

By intercepting the exception too early, and mangling it into the same format as a valid output, you are breaking with that premise. Instead of the valid input, you are now passing the error message down to subsequent operations.

With no way to distinguish the error case from a valid result.

But this mistake isn't just new to your addition - it was already present on your original code:

public string GetDescription()
{
    try
    {
        Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\LanmanServer\\Parameters", "srvcomment", "").ToString();
    }
    catch(Exception ex)
    {
        return "ERROR" + ex.ToString()
    }
}

That return "ERROR" + ex.ToString() is a problem. Because that is not how to properly handle an error case. You literally can't distinguish at all whether this supposed error message was generated by this function, or if it was actually read from the registry.

Whenever you encounter an Exception, there are only 3 valid approaches:

Swallow the exception, and continue with a fail safe default.
Capture and encapsulate the exception in a more generic exception.
Translate the exception into a different, dedicated and distinguishable channel for error reporting. (E.g. encoding function success status in an enum return value, while the actual results are returned by reference.)
(optionally) Report the error to a logging component, before continuing with one of the 3 options above.

What you did was neither. You mixed the error state into the run time state of your application, tainting it and making the behavior of all subsequent functions depending on that value undefined.

Even if you expect that the result of the command chain eventually shows up on screen in text form, just because your application happens to be that simple, and these functions are not used in any other scope, it's still not safe to do it.

One more problem with your approach: It only "works" at all for string type functions. What with more complex datatypes, e.g. collections and alike?

For these, you can't trivially encode the error case in the return value. Simply because there isn't a solution with potentially different semantics, inevitably leading to undefined behavior later on.

How to capture exceptions correctly?

You only capture and swallow an exception ever, if you know that you can safely recover.

That means e.g. in the case of operations chained in LINQ style, you wrap no less than the whole chain into a try clause. The exception is supposed to interrupt the execution of the chain, to avoid undefined behavior.

And if the behavior of the surrounding scope still isn't in and can't be brought into a defined state in case of an exception, you let it bubble. As long until you can restore a sound state.

The completely broken error handling aside, decorating your functions to get a stream like semantic is perfectly legit.

Just be wary that this breaks with the coding style given by the .Net run time and most libraries. So the maintainability when enforcing such fundamentally different patterns is going to suffer. For one because that style is unexpected (-> principle of least surprise). For the other part because you can't trivially interface with 3rd party code, but you would always need either a wrapper, or break your own patterns.

You should try to stick to the patterns and interfaces already present in your run time, if possible.


Initialize bunch of variables in constructor by extracting value from dictionary

You can simplify that portion of code. First, you'll need to create an array that will holds the header keys such as PROC_HEADER ..etc. then you can go from there.

Here is an example (NOTE, keys are just placeholders in this example, so you know which const needs to be replaced).

public Tester(IDictionary<string, StringValues> headers)
 {
    // these will be overwritten if their customer global are not null.
    DbId = GenerateDbId();
    ProcId = GenerateProcId();
    ThetaId = GenerateThetaId();

    if (headers == null) { return; }

    var headerKeys = new[]{
        "PROC_HEADER",
        "DB_HEADER",
        "TEXT_HEADER",
        "ALPHA_HEADER",
        "TIMEOUT_HEADER",
        "FILTER_HEADER",
        "PREVIEW_HEADER",
        "ANT_HEADER",
        "APP_HEADER",
        "PAGE_HEADER",
        "LOCAL_HEADER",
        "CONTEXT_HEADER",
        "CHANNEL_HEADER"
    };

    foreach(var key in headerKeys)
    {
        headers.TryGetValue(key, out var headerValue);

        if (headerValue.Count > 0)
        {
            switch(key)
            {
                case "PROC_HEADER":
                    SetHeaderValue(headerValue[0], "ProcIdHeader", "ProcId");
                    break;
                case "DB_HEADER":
                    SetHeaderValue(headerValue[0], "DbIdHeader",  "DbId");
                    break;
                case "TEXT_HEADER":
                     int.TryParse(headerValue[0],  var textId);
                     TextIdValue = textId;
                     TextId = textId;
                    break;
                case "ALPHA_HEADER":
                    SetHeaderValue(headerValue[0],  "AlphaHeader",  "AlphaContent");
                    break;
                case "TIMEOUT_HEADER":
                    SetHeaderValue(headerValue[0],   "TimeIdHeader",  "TimeId");
                    break;
                case "FILTER_HEADER":
                    SetHeaderValue(headerValue[0],   "FilterHeader",  "FilterId");
                    break;
                case "PREVIEW_HEADER":
                    SetHeaderValue(headerValue[0],   "PreviewHeader",  "PreviewId");
                    break;
                case "ANT_HEADER":
                    SetHeaderValue(headerValue[0],   "AntHeader",  "AntId");
                    break;
                case "APP_HEADER":
                    SetHeaderValue(headerValue[0],   "AppHeader",  "AppId");
                    break;
                case "PAGE_HEADER":
                    SetHeaderValue(headerValue[0],   "PageHeader",  "PageStr");
                    break;
                case "CHANNEL_HEADER":
                    ChannelId = headerValue[0];
                    break;
                case "LOCAL_HEADER":
                    LocalHeader = headerValue[0];
                    LocalStr = DeserializeHeader<LocalStr>(LocalHeader);
                    break;
                case "CONTEXT_HEADER":
                    ContextHeader = headerValue[0];
                    ContextStr = DeserializeHeader<ContextStr>(ContextHeader);
                    break;
            }
        }
    }
}

private T DeserializeHeader<T>(string str) where T : new()
{
    if(!string.IsNullOrEmpty(str))
    {
        try
        {
            return JsonSerializer.Deserialize<T>(str);
        }
        catch (Exception e)
        {
            return new T();
        }
    }

    return default;
}

public void SetHeaderValue(string headerValue, string customerPropertyName, string serverPropertyName)
{
    var custProperty = this.GetType().GetProperty(customerPropertyName);

    if(custProperty != null) { custProperty.SetValue(this, headerValue); }

    if(!string.IsNullOrWhiteSpace(headerValue))
    {
        var serverProperty = this.GetType().GetProperty(serverPropertyName);

        if(serverProperty != null) { serverProperty.SetValue(this, headerValue); }
    }

}

I've decided to use switch to group them up, as it would be more readable, and also it has an a performance advantage over if/else blocks as it would be compiled into jump table which would be faster than if/else blocks.


Correctness? Unanticipated cases?

module Heapify where

data Tree a = Leaf a | Node (Tree a) a (Tree a)
   deriving Show

I think this can't host an even number of elements. fromList [1,2] seems impossible.

ourTree = Node (Node (Leaf 8) 2 (Leaf 4))  3  (Node (Leaf 1) 7 (Leaf 9))

an example data.

atTop :: Tree a -> a
atTop (Leaf a) = a
atTop (Node _ a _) = a

ok.

replaceTop :: Ord a => Tree a -> a -> Tree a
replaceTop (Leaf _) a = Leaf a
replaceTop (Node l _ r) a = heapify (Node l a r)

produces a heap. doesn't know what data was put on top, must re-heapify. Does not use the knowledge whether l/r are in fact heaps already or not. If was called on a heap,  both must have been heaps already. The usual flow would be for heapify to be called on arbitrary trees, but replaceAtTop to be called on heaps only. This might have an impact on performance.

adjustLeft :: Ord a => Tree a -> Tree a
adjustLeft (Leaf a) = Leaf a   -- But we shouldn't ask to do this.
adjustLeft  node@(Node l a r)
     | topL <= a = node
     | otherwise = Node (replaceTop l a) topL r
         where topL = atTop l

assumes l was already a heap. If not, l might harbor some number yet bigger than topL and the otherwise clause could produce a non-heap (replaceTop fully heapifies its argument so its biggest number will get floated to its top).

adjustRight :: Ord a => Tree a -> Tree a
adjustRight (Leaf a) = Leaf a   -- But we shouldn't ask to do this.
adjustRight  node@(Node l a r)
     | topR <= a = node
     | otherwise = Node l topR (replaceTop r a)
         where topR = atTop r

similarly to the above, assumes r was a heap. Both functions assume both l and r were heaps actually, because r (corr., l) is kept unchanged. So both assume that only the top element can be out of place before the call, and produce a heap under that assumption. If the assumption does not hold, the produced value will not be a heap.

doTop :: Ord a => Tree a -> Tree a
doTop (Leaf a) = Leaf a
doTop node@(Node l a r)
    | atTop l > atTop r = adjustLeft node
    | otherwise         = adjustRight node

assuming both l and r were heaps before call, produce a heap.

heapify :: Ord a => Tree a -> Tree a
heapify (Leaf a) = Leaf a
heapify (Node l a r) = doTop (Node (heapify l) a (heapify r))

assuming heapify fulfills its promise, OK. Base case (Leaf a): OK.

So, OK (except for the data definition deficiency).

Call graph

 heapify                             (does not assume l/r were heaps)
    |
    |_____  heapify
    |
    |_____  doTop
            |
            |____ adjustLeft / adjustRight    (assume l/r were heaps)
                  |
                  |____ replaceTop   (does not assume l/r were heaps)
                        |
                        |_____ heapify

Performance?

So, heapify essentially is

heapify (Leaf a) = Leaf a
heapify (Node l a r)
   | a >= top    = Node lh a rh
   | ltop > rtop = Node (replaceTop lh a) ltop rh                 -- lh is a heap!
   | otherwise   = Node lh                rtop (replaceTop rh a)  -- rh is a heap!
  where
    lh   = heapify l    ----- superfluous, == id when called from (1)    -- (2)
    rh   = heapify r    ----- superfluous, == id when called from (1)    -- (2)
    ltop = atTop lh
    rtop = atTop rh
    top  = max ltop rtop
    replaceTop (Leaf _)     a = Leaf a
    replaceTop (Node l _ r) a = heapify (Node l a r)   ------- (1)

Looks a very heavy recursion.

One way to fix this is to assume that heapify will be called only on heaps, not on arbitrary trees. Then the fix is simply to eliminate the two (2) calls. Then it  becomes logarithmic.

Heaps would need to be created from lists. The usual way is fold/insertElem.
The data type definition needs to be adjusted to allow insertion of one element into a heap tree. The definitions will have to be readjusted. Probably easier done with small snippets, like in OP code. atTop would have to produce a Maybe value, as now empty heaps become a possibility (say, one of the children of a fromList [1,2] heap tree - now both subtrees are heaps, and one is empty).
The whole balance/depth issue is untouched here.

It's probably simpler to re-write replaceTop to essentially duplicate the above code, without the calls to heapify. It will now assume it's operating on heaps only, not on arbitrary trees. This will make replaceTop logarithmic. Leaves all the other problems unaddressed.

replaceTop (Leaf _)       a = Leaf a      -- operates on heaps!
replaceTop (Node lh _ rh) a               -- lh, rh are heaps!
   | a >= top       = Node lh a rh
   | ltop > rtop    = Node (replaceTop lh a) ltop rh
   | otherwise      = Node lh                rtop (replaceTop rh a)
  where
    ltop = atTop lh
    rtop = atTop rh
    top  = max ltop rtop

According to master theorem for 2T(n/2) + O(log(n)) case, heapify will be O(n) then, assuming a balanced tree. A balanced tree can be built from a list in O(n) time.

removeTop will most probably be O(log(n)).


Find positive integer with a minimum number of binary 1's such that its bitwise AND with all array elements is not 0

Is there a way to improve the time complexity of this solution without
  exceeding the space limitation?

Yes, there's a way. We don't actually need any additional array of numbers because we can check all numbers from 1 to the maximum possible mask for given elements of the array. Then, we will perform AND of the current number candidate with all array elements only if its 1's count lower than that of the current best candidate. Please check the code for more details.

  Should a completely different approach be used here?

I've come up with a similar brute force approach that requires only additional O(1) space. It's quite simple and also passes all the tests.

Remove duplicates from the original array

We can safely do it because duplicate elements do not influence the final answer. It also helps us to reduce the size of the array and thus improve the time complexity of the algorithm.

Sort the array by 1's count

By doing so, we won't perform a bitwise AND for most of best mask candidates with ALL array elements and thus save a lot of execution time.

Perform AND only for candidate numbers having fewer 1's

That's another important optimisation. Before checking a candidate against the array elements make sure it has fewer 1's than the current best candidate.

Code

#include <vector>
#include <iostream>
#include <algorithm>
#include <bitset>

uint8_t popCount(const uint32_t& number) {
    std::bitset<26> bitSet(number);

    return bitSet.count();
}

uint32_t solve(std::vector<uint32_t>& array) {
    // exclude duplicates from the array to reduce its size
    std::sort(array.begin(), array.end());
    array.erase(unique(array.begin(), array.end()), array.end());

    // sort array elements based on their 1's count in ascending order
    std::sort(array.begin(), array.end(), [](const auto& a, const auto& b) {
        uint8_t count1 = popCount(a);
        uint8_t count2 = popCount(b);

        if (count1 == count2) {
            return a < b;
        }
        return count1 < count2;
    });

    // Initially, bestMask is the maximum possible mask
    uint32_t maxPossibleMask = 0;
    for (const auto& element : array) {
        maxPossibleMask |= element;
    }

    uint32_t bestMask = maxPossibleMask;
    for (uint32_t bestMaskCandidate = 1; bestMaskCandidate < maxPossibleMask; bestMaskCandidate++) {
        if (popCount(bestMaskCandidate) < popCount(bestMask)) {

            bool candidateFound = true;
            for (uint32_t index = 0; index < array.size(); index++) {
                if (!(bestMaskCandidate & array[index])) {
                    candidateFound = false;
                    break;
                }
            }

            if (candidateFound) {
                bestMask = bestMaskCandidate;
            }
        }
    }

    return bestMask;
}

int main() {
    //read an array size
    uint32_t size;
    std::cin >> size;

    //save each value into the corresponding array position
    std::vector<uint32_t> array(size);
    for (auto& element : array) {
        std::cin >> element;
    }

    uint32_t bestMask = solve(array);
    std::cout << bestMask << "\n";

    return 0;
}


Checking if there are tags or categories in the database

Parameters should be camelCased, so Tags should be tags. As far as I can tell though only one tag is passed in, so it should be the singular tag.
x isn't a very good variable name. It looks like you used it as a generic name because you were copy/pasting. The two loops are slightly different, but not by a whole lot. Consider how you could possibly pass the string and repository into a method instead.


Possible issues and best practices for this piece of code

You may want to add some additional validation around how many arguments you're expecting (since you know via MinArgs and MaxArgs). You can also eliminate having to create an object array explicitly in the caller by using the params keyword (make sure you do it in the declaration in FunctionInfo as well). Lastly, if this class is intended to be non-inheritable (unlike FunctionInfo), mark it as sealed:

public sealed class NANDFunction : FunctionInfo
{
    public override string Name { get { return "NAND"; } }
    public override int MinArgs { get { return 2; } }
    public override int MaxArgs { get { return 2; } }

    public override object Evaluate(params object[] args)
    {
        if ((args.Length < this.MinArgs) || (args.Length > this.MaxArgs))
        {
            throw new ArgumentException("An insufficient number of arguments were passed.");
        }

        bool arg0 = CalcConvert.ToBool(args[0]);
        bool arg1 = CalcConvert.ToBool(args[1]);
        return (arg0 != arg1) || (!arg0 && !arg1);
    }
}


Short Answer:
Having a call to MessageBox.Show() in any DAL code is A Bad Thing (TM).

Longer Answer:
In an ideal world, your DAL would not know anything about your presentation layer - not even that it is a Windows/Winforms application.  It really should know very little (if anything) about any code that invokes it.

I would have the above routine return nothing and simply let any exception propagate back up the call stack to the point where is can be dealt with.

If this is in the code that directly called it, then wrapped the call in a try/catch. There should be no need to check a return value on this function.

//...
try {
    InsertAccount(ba);
    // continue with rest of processing
}
catch (Exception ex){
    // deal with exception
}

Even Longer Answer:

A Matter Of Personal Preference (AMOPP), having MessageBox.Show() any where in one's code except for a service dedicated to showing messages is bad.  Any code that needs to show a message should invoke a service to show the message.

This means that

We can more easily unit test the code.  A request to show a message can be mocked and tested. Actually showing a MessageBox blocks the test.
We can manage how the messages should be shown in a single place. Say that we want all the messages to show as toast notifications instead of message boxes; we need only change in one place.


I think your condition for putting the '+' isn't right: it should be beatTime-noteId > 0 instead of beatTime > 0.

For the given example there will be no difference in the output, but test it with  e.g. 4 4 1.125 as command line arguments: 1.125 matches a full 16th but your code prints 1.125 2.1.3+ instead of 1.125 2.1.3.


Is this an appropriate approach and layout for conditionally continuing execution in bash?

Firstly, this will most likely do a wrong thing if the first argument is empty:

if [ "$1" = "--help" ] || [ -z $1 ] || [ "$2" ];

You should probably use something like this instead (note added quotes):

if [ "$1" = "--help" ] || [ -z "$1" ] || [ $# -gt 1 ];

In general you should quote all variables which are not guaranteed to be set, to be non-empty and to only contain alphanumeric characters.

Secondly, I would not call myself a seasoned bash hacker, but parenthesis are imo more common if you need to run a small command in another directory, e.g.

(cd -P "$anotherdir"; make fun)

When it comes to longer code pieces you can either use a function or simply pushd and popd, e.g.

pushd .
cd "$anotherdir"
# do something else
popd

As for formatting, I also use four-space indentation but prefer more dense code and therefore put then on the same line as if. Additionally, I usually write following code if I need several commands to run in sequence only if everything worked out fine:

stderr() {
    cat - 1>&2
}

fail() {
    printf "%s\n" "$@" | stderr
    return 1
}

commandA "$arg1" "$arg2" || fail "ERROR: something went wrong"
commandB "$arg1" "$arg2" || fail "ERROR: something else went wrong"

UPDATE: Incorporate rolfl's suggestion to use a fail() function.


Transmitting/Sending big packet safely using TcpClient/Socket

Instead of using the ToArray() method of the MemoryStream you could use GetBuffer() instead because this isn't creating a new array.

Edit based on @Iridium's comment

But this is only good if you use one of the constructor that creates a not resizable MemoryStream which isn't the case for the default constructor.

Calling Dispose() on the MemoryStream closes the stream too.

If you enclose the stream inside inside a using block the disposing of the stream will be handled automatically.

public byte[] ToBytesWithLengthPrefix()
{
    using (var stream = new MemoryStream())
    {
        Serializer.SerializeWithLengthPrefix(stream, this, PrefixStyle.Fixed32);
        return stream.ToArray();
    }
}

I needed to look twice at var data = (byte[])odata; which is a clear sign that you should make the method argument odata easier to distinguish from data, so objectData or dataToSend would be better.

int buf isn't well named either. One shouldn't use abbreviations to name variables. A much better name would be for instance dataSize or just size to indicate that it is the amount of data being sent.


Nested dictionary creation with setdefault

Use a defaultdict like so:
from collections import defaultdict

resource_dict = lambda: defaultdict(list)
service_dict = lambda: defaultdict(resource_dict)
region_dict = lambda: defaultdict(service_dict)
execution_log = defaultdict(region_dict)

execution_log['AWS']['region']['service']['resource'].append({
                "id": 'resource_id',
                "action": 'resource_action',
                "timestamp": "%Y-%m-%d %H:%M:%S",
            })

execution_log

output:
defaultdict(<function __main__.<lambda>()>,
            {'AWS': defaultdict(<function __main__.<lambda>()>,
                         {'region': defaultdict(<function __main__.<lambda>()>,
                                      {'service': defaultdict(list,
                                                   {'resource': [{'id': 'resource_id',
                                                      'action': 'resource_action',
                                                      'timestamp': '%Y-%m-%d %H:%M:%S'}]})})})})


I think your implementation is fine. I might write it like this, because I find it more idiomatic in F# to avoid guards (when clauses) in pattern matching where a guard free implementation is equally concise.

let fizzbuzz x =
    match (x % 5, x % 3) with
    | (0, 0) -> "FizzBuzz"
    | (0, _) -> "Buzz"
    | (_, 0) -> "Fizz"
    | _ -> string x

[1..100] |> List.map fizzbuzz |> List.iter (printfn "%s")

There are ways you can make this more elaborate / extensible but while that can be an interesting exercise I don't think they're really an improvement over a simple straightforward implementation like this.


Load [incr] into a register instead, for example eax, and increment the register.

Instead of cmp [incr], 1000000000 and jne, try loading 1000000 into the ecx register and using the loop opcode.

The advice above to use loop is probably obsolete. Instead it may be faster to do load 1000000 into a register like ebx, and do a dec ebx and jnz loop.

Intel's Branch and Loop Reorganization to Prevent Mispredicts seems to recommend you code a loop like this ...

loop_top:
... do work inside the loop here ...
cmp ebx,1000000
jz loop_end ; happens rarely
inc ebx
jmp loop_top ; happens often
loop_end:

... in order to optimize the branch prediction.

Unrolling the loop might make it faster. In fact given how dumb the algorithm is, the best optimization is to immediately 1000000 to [incr] without looping.


From an object-oriented point of view there is a better way you can handle this scenario.
Feature Envy
Currently the code snipped has a Code Smell that is called Feature Envy:

The whole point of objects is that they are a technique to package data with the processes used on that data. A classic [code] smell is a method that seems more interested in a class other than the one it is in. The most common focus of the envy is the data.
— Martin Fowler, Refactoring: Improving the Design of Existing Code, Chap. 3, p. 80

The class CredentialsValidator only interacts with data from ValidationCredentialsRequest by accessing it via all the getters:

nonNull(credentials.getUsername())
&& !credentials.getHostname().isEmpty()
/* ... */

Instead, this logic could be in ValidationCredentialsRequest, and CredentialsValidator only interacts with the validation methods instead of the getters:

public boolean validateCredentialsRequest(ValidationCredentialsRequest credentialsRequest) {
   switch (credentialsRequest.getCredentialType()) {
       case TYPEA:
           return credentialsRequest.isTypeAValid();
       case TYPEB:
           return credentialsRequest.isTypeBValid();
       case TYPEC:
           return credentialsRequest.isTypeCValid();
   }
   return true;
}

class ValidationCredentialsRequest {
   /* ... */

   public boolean isTypeAValid() {/* ... */ }

   public boolean isTypeBValid() {/* ... */ }

   public boolean isTypeCValid() {
       if (newCredential) {
           return nonNull(username)
               && !username().isEmpty()
               && nonNull(password)
               && !password.isEmpty();
       }
       return nonNull(credentialsId);
   }

}

Polymorphism
Polymorphism is a concept where one thing can be something else at the same time: for example, a Shape can be a Rectangle at the same time.
With Polymorphism we can achieve that we no longer need the switch case. This would have the advantage that we don't have to change the CredentialsValidator class when adding new validation logic:
class CredentialsValidator {

    public boolean validateCredentialsRequest(ValidationCredentialsRequest credentialsRequest) {
        return credentialsRequest.isValid();
    }

}

From here all different "shapes" of ValidationCredentialsRequest need to share the same interface - all need the isValid method:
abstract class ValidationCredentialsRequest {
    /* ... */
    abstract boolen isValid();
}

class TypeARequest extends ValidationCredentialsRequest {
    /* ... */
    public boolean isValid() { /* ... */ }
}

class TypeBRequest extends ValidationCredentialsRequest {
    /* ... */
    public boolean isValid() { /* ... */ }
}

class TypeCRequest extends ValidationCredentialsRequest {
    /* ... */
    public boolean isValid() {
        if (newCredential) {
            return nonNull(username)
                && !username().isEmpty()
                && nonNull(password)
                && !password.isEmpty();
        }
        return nonNull(credentialsId);
    }
}

Now when a new kind of ValidationCredentialsRequest is needed, we just have to create a new "form" of it, and it works without changing the CredentialsValidator.
Edit
Use in Main
In the code for the main you provided nothing needs to be changed.
But if you would like to add the Polymorphism to your code, you need to change it where you create the ValidationCredentialsRequest objects. There you would create the different "shapes" of ValidationCredentialsRequest instead of ValidationCredentialsRequest itself.


Cropping and combining two images on server

Expanding on my comment above, I'd also follow Microsoft's naming guidelines and have the method names be PascalCased. Plus, I'm not a huge fan of mutable structs, preferring to initialize them via provided constructors. So I came up with the following:

public static class ImageCombiner
{
    private static readonly EncoderParameters encoderParameters = new EncoderParameters(1);

    private static readonly RectangleF sizeLocation1 = new RectangleF(0.0F, 0.0F, 400.0F, 400.0F);

    private static readonly RectangleF sizeLocation2 = new RectangleF(400.0F, 0.0F, 400.0F, 400.0F);

    private static readonly ImageCodecInfo jpgDecoder = ImageCodecInfo.GetImageDecoders().Single(codec => codec.FormatID == ImageFormat.Jpeg.Guid);

    private static readonly byte[] emptyImage = new byte[0];

    static ImageCombiner()
    {
        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 90L);
    }

    // Crops two squares out of two separate images
    // And then combines them into single image that's returned as byte[]
    public static byte[] CombineImages(IList<HttpPostedFileBase> itemPayload)
    {
        try
        {
            using (var ms = new MemoryStream())
            using (var bitmap = new Bitmap(800, 400, PixelFormat.Format24bppRgb))
            using (var img1 = Image.FromStream(itemPayload[0].InputStream))
            using (var img2 = Image.FromStream(itemPayload[1].InputStream))
            using (var g = Graphics.FromImage(bitmap))
            {
                g.DrawImage(img1, sizeLocation1, GetCropParams(img1), GraphicsUnit.Pixel);
                g.DrawImage(img2, sizeLocation2, GetCropParams(img2), GraphicsUnit.Pixel);
                bitmap.Save(ms, jpgDecoder, encoderParameters);
                return ms.ToArray();
            }
        }
        catch
        {
            return emptyImage;
        }
    }

    private static RectangleF GetCropParams(Image img)
    {
        return img.Width > img.Height
            ? new RectangleF(
                    (img.Width / 2) - (img.Height / 2),
                    0.0F,
                    2 * (img.Height / 2),
                    img.Height)
            : new RectangleF(
                    0.0F,
                    (img.Height / 2) - (img.Width / 2),
                    img.Width,
                    2 * (img.Width / 2));
    }
}


Optimize mass import of XML to SQLServer in Ruby

As for performance, I definitely think you want to use SQL's Bulk Insert from XML functionality. I don't know how to use it from Ruby, so I'll leave that to another reviewer.

I do want to point out something else though. I had to scroll down two pages to find the end of the loop that this opens up. doc.elements.each('products') { |product|. In fact, the entirety of the code is inside of this loop. Blocks of code should fit on the screen in their  entirety. I call it the "Single Page Principle".

So, the refactoring step that should be taken is to define a method that takes product as a parameter and put all of the logic necessary to handle a single doc.element inside of it.

def update_product!(product)
    #ALL THE CODEZ
end

# loop through products in XML file
doc.elements.each('products') { |product| update_product!(product) }

The next step would be to break down the steps inside of the new update_product method into smaller methods as well. A good start would be to take the code between the comments and place them inside of a method with a good name. This replaces your comment and breaks the code down into logical chunks.

For example:

Instead of this:

# update prices
price = Price.find(:first, :conditions => { :item_id => itemid })
# create new price if price not found
    if price.nil?
      price = Price.new
      price.item_id = itemid
    end
    price.price = product.elements['price'].text.to_i
    price.save

    # find + update item stock data
    product.elements.each('stocks/location') { |location|
      item_stock_location_id = location.attributes['location_code']
      item_stock_location = ItemStockLocationCount.find(:first,
                                                    :conditions => {
                                                        :item_stock_location_id => item_stock_location_id,
                                                        :item_id => itemid.to_s
                                                    })

Define this:

def update_price
    # update prices
    price = Price.find(:first, :conditions => { :item_id => itemid })
    # create new price if price not found
    if price.nil?
      price = Price.new
      price.item_id = itemid
    end
    price.price = product.elements['price'].text.to_i
    price.save

    # find + update item stock data
    product.elements.each('stocks/location') { |location|
      item_stock_location_id = location.attributes['location_code']
      item_stock_location = ItemStockLocationCount.find(:first,
                                                    :conditions => {
                                                        :item_stock_location_id => item_stock_location_id,
                                                        :item_id => itemid.to_s
                                                    })
end

And call it from update_product!. Continuing doing this until each method has exactly one responsibility. You should end up with code that looks something like this psuedocode.

def update_product(product)
    update_price
    update_item_stock_data
    update_stock_site
    update_price_lock

    count += 1
    # progress bar
    if count%100 == 0
      printf '.'
    end
end

 # counters for statistics
  count = 0
  skips = 0

  # load + parse XML
  file = File.read(XML_PATH)
  doc = REXML::Document.new file

  # loop through products in XML file
  doc.elements.each('products') { |product| update_product!(product) }

  puts 'Item Count: ' + count.to_s
  puts 'Items skipped: ' + skips.to_s


There is no need to use matchers for this check. A logical expression would be enough:

def checkpermutation2(a:String, b:String): Boolean = {
  def sorted(s: String) = s.sorted.mkString
  (a == b) || (a.length == b.length && sorted(a) == sorted(b))
}


This is a very interesting problem!

Firstly, you have correctly identified the 3 possible states:

both tree1 and tree2 are null
tree1 or tree2 is null
both tree1 and tree2 are not null

That being said, I would recommend a couple of things:

Break up the problem into 4 possible states (i.e., don't handle the case when tree1 or tree2 is null in one conditional statement.
if passing in the merged tree tree3 to doMerge in order to modify it in the method, you should utilize C#'s out parameter.
Why do you need the Direction enum? It seems to make the code harder to understand.

Here is my implementation of doMerge:

public TreeNode MergeTrees(TreeNode t1, TreeNode t2)
{
    if (t1 == null && t2 == null) return null;
    if (t1 != null && t2 == null) return t1;
    if (t1 == null && t2 != null) return t2;
    TreeNode merged = new TreeNode(t1.val + t2.val);
    merged.left = MergeTrees(t1.left, t2.left);
    merged.right = MergeTrees(t1.right, t2.right);
    return merged;
}


Sorting an array of numbers by descending frequency

I see a couple occurrences of:

do
{
    hasSorted = 0;
    ...other things...
    if(hasSorted == 0)
    {
        break;
    }
}while(hasSorted == 0);

Did you mean if(hasSorted == 1) in those? If not, then you might want to just get rid of the whole if statement and replace the while condition with while(hasSorted != 0).

Also, comments that describe the whole function could look better on a separate line right before the function, so that the line doesn't get too long.


To formalize my comments above as an answer (even though it will be an incomplete one as to possible optimizations):

You can check other "significant" parts of the files before hashing the whole thing. For example, as you've done, not only the first 10 characters but then the final 10 (even a middle 10 afterwards in case they also share identical closing headers).
To do the above, and as a bonus to optimize the I/O aspect, you can avoid re-opening each file, which is quite slow. Instead, keep them open and read as necessary, or even read a large chunk and then close, but don't reopen.
For style commentary, since you requested it in version 1 of this thread:

Add a little whitespace between functions and for loop blocks, and generally between any self-contained block of 3-4 lines or more.
You presumably named the variable files because you'd already used filenames, but files actually refers to groups of filenames. What's more, the variable name doesn't indicate what's special about those "files". One suggestion might be collision_set.

Speaking of sets, for a minor improvement, you could store the values in sets instead of appending to lists.


Make huge view in C# readable and maintanable

I would use a Partial View for this code.
Anytime I have a menu for a page I put it in a partial view even though it may not be used on another page.

@Html.Partial("_Actions")

@Html.Partial("_OrderStatus")

@Html.Partial("_OrderDetails")

@Html.Partial("_OrderDate")

inside the Partial view placed in Views/Shared

@model ActionsViewModel
Column 1
Column 2
Column 3
Column 4
Column 5

etc...
Good Luck!


Is it still necessary to check for a front camera?

According to the iOS Device Compatibility Reference, the iPhone 3GS was the only iOS 6-capable device to lack a front camera.

The same document states that your application can declare the requirement for a front-facing camera by setting the UIRequiredDeviceCapabilities key such that front-facing-camera is true.  That way, you can safely strip out the camera-checking code while having your application self-document the assumption that the front camera exists.


Count the number of biggest numbers on the board

The second solution

If the input array is empty, the program will crash with an exception.

It's recommended to specify the radix to parseInt calls:

let smallColA = parseInt(sArr[0], 10);

The if(sArr.length > 1){ condition is unnecessary,
the loop condition naturally takes care of that.

Even better, no need to treat the first element specially,
you can initialize smallColA and smallColB to Infinity.
Not only it will be simpler,
but in it will work even when the input array is empty.

The first (naive) solution

You could write this simpler:

if(board[i][j] !== undefined){
    board[i][j]++;
}
else{
    board[i][j] = 1;
}

... using a technique you already used in your other recent question:

board[i][j] = (board[i][j] || 0) + 1;


This doesn't strike me as particularly readable, although it is definitely succinct. Here are a few of the things I noticed that I think could be improved:

The name Min() for a method that determines if someone has filled a row is very confusing.

WinFor() should be a method on IBoard rather than a static method that takes an IBoard.

The variable names in MetaBoard.Write()are also confusing and something like outerRow and innerColumn would be more informative that rr and c.

The quadruple foreach loop in the MetaBoard.Write() scares me. I realize what it is doing, but that many nested loops is a code smell. You might want to create a method on IBoard that prints out board contents line-by-line so that you can append them to each other and control when you insert padding and newlines.

If you're going to do that, you may consider extracting out a BoardPrinter class or something similar to encapsulate that behavior.

The size of the board is hard-coded and although it isn't a requirement, redesigning this to support different-sized boards will make a more flexible design. (I got this idea in a review for my Ultimate Tic-Tac-Toe entry and am happy I re-worked it).
This will require removing Lines and calculating them manually. As a side note, indices for diagonals can be calculated by consecutively adding the (board width + 1) for downward-right and the (board width - 1) for downward-left diagonals. It took me a while to figure that out.

The use of Board[] as the type for the MetaBoard.Boards property indicates to me that the IBoard interface is not as useful as it should be (since MetaBoard is tightly coupled to Board). If you pull out the printing so that it can be done line-by-line as I suggested earlier, you could go back to using IBoard. If done carefully, you could nest MetaBoards within MetaBoards (for the Ultimate in Ultimate Tic-Tac-Toe).

I don't see where you restrict players from selecting an already completed board.

I know I'm basically ruining the brevity if you implement my comments, but I am impressed with how you managed to keep it so short. It was fun to review, thanks for sharing!


Search for data and order by priority efficiently

The .reverse() function sorts the priorities alphabetically, not numerically

This is because Object.keys returns an array of strings.

  If 2 findings have the same amount of matchpoints, the findings-entry gets overwritten. So the result isn't even valid.

Right, you want to push matches onto the array and sort it afterwards.

var findings = [];
for (var element in hugeObject) {
    var points = getMatchPoints(inputToSearchFor, hugeObject[element]);
    if (points) {
        // It matched. At least a bit.
        findings.push({ points: points, element: element });
    }
}
findings.sort(function(a, b) { return b.points - a.points; });

Here I'm creating a new object with the number of match points stored in points and the found object stored in element, but you could store the point count directly in the found object if it makes more sense.


Calculate the movement required to get from one angle to another angle on a compass

The other reviews give some good formatting advice so I'll concentrate solely on the function itself.  I would probably write this instead:

def dir_diff(dir1, dir2):
    diff = (dir2 - dir1) % 360
    return diff if diff <= 180 else diff - 360

The way Python's % operator works, it assures that we always have a positive number from 0 to 360 for diff in the first line.  Then we only need to adjust if the value is greater than 180.  Note also that unlike all of the other versions (including the original), this version will also continue to work properly even if we pass in values such as 900, -92 or 725, 9900.

Better yet, use AJNeufeld's comment or twalberg's equivalent:

return 180 - (dir1 - dir2 + 180) % 360

In another comment, the OP said:

  Later I will use this function to interpolate missing data. So, if dir_1 is lower than dir_2 like it is with (0, 180) then the answer should be positive because 90 (90 b/c +180/2) would be the middle value and not -90. Hope that helps.

This requirement doesn't make sense to me because interpolation between two diametrically opposite points on a circle can legitimately be interpreted as either midpoint.  However, if it's really a requirement, we can combine like so:

def Edward2(dir1, dir2):
    diff = (dir2 - dir1 + 180) % 360 - 180
    return -diff if diff == -180 and dir1 < dir2 else diff

If anyone cares, here is the test code I used:

import csv

def orig(dir_1, dir_2):
    diff = dir_2 - dir_1

    if diff > 180:
        diff = 360 - diff

    elif diff < -180:
        diff = 360 + diff

    if dir_2 > dir_1 and (dir_2 - dir_1 > 180):
        diff = -diff

    return diff

def Edward1(dir1, dir2):
    diff = (dir2 - dir1) % 360
    return diff if diff <= 180 else diff - 360

def twalberg(dir1, dir2):
    return 180 - (dir1 - dir2 + 180) % 360

def AJneufeld(dir1, dir2):
    return (dir2 - dir1 + 180) % 360 - 180

def Edward2(dir1, dir2):
    diff = (dir2 - dir1 + 180) % 360 - 180
    return -diff if diff == -180 and dir1 < dir2 else diff

if __name__=="__main__":
    green = "\x1b[32m"
    red = "\x1b[91m"
    white = "\x1b[37m"
    algo = [orig, Edward1, twalberg, AJneufeld, Edward2]

    def testAll(d1, d2, desired):
        print('{:-6} {:-6} {:-6}'.format(d1, d2, desired), end='')
        for fn in algo:
            calc = fn(int(d1),int(d2))
            color = [green, red][calc != desired]
            print('{}{:>10}{}'.format(color, calc, white), end='')
        print()

    print('  dir1   dir2 desired', end='')
    for fn in algo:
        print(f'{fn.__name__:>10}', end='')
    print()
    with open('input.csv') as csvfile:
        rowreader = csv.reader(csvfile)
        for row in rowreader:
            testAll(int(row[0]), int(row[1]), int(row[2]))

Here is the test data I used, with the format dir1,dir2,desired.

input.csv

120,30,-90
340,20,40
20,340,-40
310,10,60
10,310,-60
0,300,-60
300,0,60
190,180,-10
180,190,10
200,220,20
220,200,-20
10,190,180
360,0,0
0,360,0
340,20,40
350,0,10
350,360,10
40,360,-40
180,0,-180
0,180,180
1,181,180
359,179,-180
180,0,-180
181,1,-180
179,359,180
90,270,180
270,90,-180
-90,-270,-180
-270,-90,180
0,360,0
360,0,0
180,-180,0
-180,-180,0
-180,180,0
180,180,0
900,-92,88
725,9900,175
725,9905,180
9905,725,-180

Results

With the test cases shown, only the Edward2 function gets all results correct. I'm using Python 3.7.5.


Serialize and deserialize n dimensional int array

1. writing an int to an OutputStream instance

Instead of splitting your int to bytes and putting them in a byte array, directly consume your bytes like this:

out.write((n >>> 24) & 0xFF);
out.write((n >>> 16) & 0xFF);
out.write((n >>>  8) & 0xFF);
out.write((n >>>  0) & 0xFF);

This is taken from the source code of FileOutputStream, which offers methods to write primitives to a stream.

This offers higher performance compared to packing your int in a byte array. Internally, the OutputStream.write(byte[] b) method is iterating over your byte array and calling out.write(int b) anyways. The same goes for the reading part as well I guess.

2. public helper methods

I would make readInt and writeInt private/protected. There is no need to expose them. If you plan to call them from other classes, a class called "IntArraySerializer" doesn't seem to be the correct place for them. Instead you should put them in a new class with a more expressive name like "StreamUtilities".

3. argument checking

You might want to check each argument of your public methods for null and throw an IllegalArgumentException if it is null, specifying which argument is null. This makes future debugging easier: You or other programmers won't have to look at the source code in order to debug a NullPointerException...

Throw and IllegalArgumentException in writeIntArr if the object is not an array.


JavaScript Good Patterns - Is this a good example?

Lets look at a couple of improvements:

new is creating an object that you aren't using. read edit for clarification

new window.APP_NAME.moduleName.functionInsideModule1({
    name: 'Mary'
});

The function functionInsideModule1 doesn't return an object and doesn't assign anything to this. So there is no need for the new.
You're referencing the whole namespace window.APP_NAME.moduleName every time. Instead try putting it in a variable. Or maybe on the inside of the module  refer to this instead.

(function () {

    var moduleName = window.APP_NAME.moduleName;

    moduleName.functionInsideModule1 = function (options) {
        /* snip ... */

        moduleName.globalVariableAvailableForEveryModuleFunctions += 1;
        // OR
        this.globalVariableAvailableForEveryModuleFunctions += 1;
    };

    moduleName.functionInsideModule1({
         name: 'Mary'
    });

}());

Edit:-

To create a new instance of moduleName you need to do this:

(function () {
    // private variables go here
    var globalPrivateCount = 0;

    var moduleName = window.APP_NAME.moduleName = window.APP_NAME.moduleName || function moduleName(initialval) {
        globalPrivateCount ++;

        this.globallyAccessible = 'unique for each instance';

        this.functionInsideModule1 = function (options) { ... };
        this.functionInsideModule2 = function (options) { ... };

        var instancePrivateVariable = initialVal;

        this.incr = function () { instancePrivateVariable++; };

        return this;
    };
    moduleName.nonUniqueGloballyAccessible = 0;
}());

and the usage is something like:

var moduleName = window.APP_NAME.moduleName;
var firstInstance = new moduleName(10);
// OR
var anotherInstance = new window.APP_NAME.moduleName(20);


Most functions are ugly in SQL Server. When there is something that needs to be done that is ugly, it's what they are used for IMHO. With that being said, here is a non-looping way. You'd have to run it in your environment to see which is faster, your method or one similar to this. I'd suspect this one to start being a lot faster as the size of the string grew. In that case, you may want to use the table version below.

Note, in your OP you stated "without special consideration to case". This method, since it uses ASCII conversions, is respective to case. However... this can be altered by using UPPER or LOWER to the entire string to maintain consistency.

DECLARE @PLAIN_TEXT nvarchar(MAX) = N'HelloWorld'

--split your string into a column, and compute the decimal value (N)
if object_id('tempdb..#staging') is not null drop table #staging
select
    substring(a.b, v.number+1, 1) as Val
    ,ascii(substring(a.b, v.number+1, 1)) as N
    --,row_number() over (order by (select null)) as RN
into #staging
from (select @PLAIN_TEXT b) a
    inner join
         master..spt_values v on v.number < len(a.b)
where v.type = 'P'

--select * from #staging

--create a fast tally table of numbers to be used to build the ROT-47 table.

;WITH
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
    E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
    cteTally(N) AS
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
    )

----uncomment this out to see the encrypted mapping...
--select
--  s.Val
--  ,s.N
--  ,e.ENCRYPTED_TEXT
--from #staging s
--left join(
--  select
--  N as DECIMAL_VALUE
--  ,char(N) as ASCII_VALUE
--  ,case
--      when 47 + N <= 126 then char(47 + N)
--      when 47 + N > 126 then char(N-47)
--  end as ENCRYPTED_TEXT
--  from cteTally
--  where N between 33 and 126) e on e.DECIMAL_VALUE = s.N

--Here we put it all together with stuff and FOR XML
select
    PLAIN_TEXT = @PLAIN_TEXT
    ,ENCRYPTED_TEXT =
        stuff((
        select
            --s.Val
            --,s.N
            e.ENCRYPTED_TEXT
        from #staging s
        left join(
        select
            N as DECIMAL_VALUE
            ,char(N) as ASCII_VALUE
            ,case
                when 47 + N <= 126 then char(47 + N)
                when 47 + N > 126 then char(N-47)
            end as ENCRYPTED_TEXT
        from cteTally
        where N between 33 and 126) e on e.DECIMAL_VALUE = s.N
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 0, '')

drop table #staging

USING A TABLE OF VALUES TO CIPHER

declare @table table (ID int, PLAIN_TEXT nvarchar(4000))
insert into @table
values
(1,N'HelloWorld'),
(2,N'AnotherWord'),
(3,N'SomeNewWord')

--split your string into a column, and compute the decimal value (N)
if object_id('tempdb..#staging') is not null drop table #staging
select
    substring(a.b, v.number+1, 1) as Val
    ,ascii(substring(a.b, v.number+1, 1)) as N
    --,dense_rank() over (order by b) as RN
    ,a.ID
into #staging
from (select PLAIN_TEXT b, ID FROM @table) a
    inner join
         master..spt_values v on v.number < len(a.b)
where v.type = 'P'

--select * from #staging

--create a fast tally table of numbers to be used to build the ROT-47 table.

;WITH
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
    E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
    cteTally(N) AS
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
    )

--Here we put it all together with stuff and FOR XML
select
    PLAIN_TEXT
    ,ENCRYPTED_TEXT =
        stuff((
        select
            --s.Val
            --,s.N
            e.ENCRYPTED_TEXT
        from #staging s
        left join(
        select
            N as DECIMAL_VALUE
            ,char(N) as ASCII_VALUE
            ,case
                when 47 + N <= 126 then char(47 + N)
                when 47 + N > 126 then char(N-47)
            end as ENCRYPTED_TEXT
        from cteTally
        where N between 33 and 126) e on e.DECIMAL_VALUE = s.N
        where s.ID = t.ID
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 0, '')
    from @table t


Find value that occurs in odd number of elements

The solution with an O(N) time complexity with O(1) space is a little bit hacky. The solution is to xor each number together. some important properties of xor are:

xor of two identical numbers is zero.
xor of any number and zero is the number.
xor is commutative.
xor is associative.

example:

A = [9, 3, 9, 3, 9, 7, 9]

the solution to this example is:

  (((((9^3)^9)^3)^9)^7)^9
= 9^3^9^3^9^7^9              (4)
= 9^9^9^9^3^3^7              (3)
= (9^9)^(9^9)^(3^3)^7        (3)
= 0^0^0^7                    (1)
= 7                          (2)


Extension Method to append a list of parameters to existing Uri as query

You should validate both your arguments for null and throw an ArgumentNullException accordingly.

if (uri == null)
{
    throw new ArgumentNullException(nameof(uri));
}

You could add an early return if the parameters collection is empty as there's no work to actually do.

I'd also use the UriBuilder class like this:

var builder = new UriBuilder(uri);
builder.Query = uri.Query != null && uri.Query.Length > 1
    ? $"{uri.Query.Substring(1)}&{query}"
    : builder.Query = query;

return builder.Uri;

It's basically the same, but it looks a little clearer to me. If you don't want to use the builder, you can at least fully interpolate your strings:

uri.OriginalString + $"?{query}"

Could be

$"{uri.OriginalString}?{query}"

Update

  Can you explain why uri.Query != null && uri.Query.Length > 1 is better than !string.IsNullOrEmpty(uri.Query)

The reason is that uri.Query may return just a question mark e.g. in this example:

new Uri("http://www.google.com?").Query
// returns "?"

If we just checked null or string.Empty then we could end up with a uri like https://www.google.com/?&foo=bar. By checking if the length is greater than 1, we can be sure we won't output a URI with "?&" in it. Although it is valid, it's a bit ugly.


Can't speak to how it'll scale, but for your 2nd question: Yes, the code above is asynchronous.

When you call db.query() or server.get() you pass a callback as the 2nd argument. That's the asynchronous stuff, as you don't know when that callback will be invoked.

You basically just say "call me when it's done" and continue about your business (i.e. in the case of db.query() the evaluation will proceed to return next(); without "waiting" for the query to finish).

If it were synchronous, it'd be something like result = db.query(params); where everything would wait for the query to return something to assign to result.

By the way (so this is actually a review and not just an explanation)

fix your indentation
in JS it's better to not use the brace-on-new-line style
you're missing some semi-colons
you don't need to quote all those property names in the params object
beware of using undefined, since that isn't actually a keyword. Some runtimes let you say undefined = 23 in which case undefined is then just another (defined) variable. Use null instead


correctGuess() and incorrectGuess() functions for a quiz

i did not test or execute this code

just put it in an object?

var Guess = {

    score : 0,
    questions_count : 0,

    text : null,

    correct : function () {
        this.score+= 1;
        this.questions_count += 1;
        this.text = 'Correct!';
    },

    incorrect : function () {
        this.score-=1;
        this.questions_count += 1;
        this.text = 'Wrong!';
    },

    update : function () {
        var updatePage = ['
' +
        '
' + text + '
' +
        '
Total Score: ' + this.score + '

'
        ];

        mainContent[html](updatePage);

        $('#answerDiv')[fadeIn]("slow");
        $('#answerDiv').append('<button id="nextButton">Next Question</button>');

        $('#nextButton').on('click', function() {
            if (this.questions_count == allQuestions.length && totalScore <= 4) {
                results();
            } else {
                question(this.questions_count);
            }

        });
    }
};

chaining

key to chaining calls is to return the right thing. Simple example:

function test() {
    var x = {
        correct : function () {
            console.log('correct');
        },
        incorrect : function() {
            console.log('incorrect');
        }
    };

return x;
}

test().correct();


Project Euler 348: Sum of a square and a cube

@Kevin Brown is correct, your programme runs in 18 seconds on my PC, if I write:

def is_palindrome(n):
    return str(n) == str(n)[::-1]

it takes only 16 seconds.


Pros

dedicated classes for the ActionListener
calls JFramw.setVisible() from outside any constructor

cons

Naming conventions: class names always start with upper case letter
Inheritance: never extend a class unless you want to change behavior, you only configure JFrame, so no need to extend it.
comments: comments in code should explain why the code is like it is and only if it is somewhat unusual or unexpected. Your comments only repeat what the code expresses already.
System.exit(0);: This kills the JVM. There will be no change to i.e. close database connections correctly. Use it only in a catch block inside main.


Adding rows to LinearLayouts which serve as lists

Your problems in code seem to be a manifestation of problematic design. If I were you I would think about improving my design first.
Currently you're displaying a list of lists of variable lengths to your user. From a UX point of view that seems like a bad decision.
There's a reason why you can't use lists in a ScrollView ;)
Have you considered for example splitting up the lists to different fragments and putting them in a view pager so you have a separate tab for each list? Then you can use ListView or, probably even better, RecyclerView to display your items.
Again a lot of times when you have to write awkward, messy code to implement your design it is worth revisiting your design and improving it. Usually that clears up convoluted code as well.


The complexity of your void traverse () method is O(n^2).

The question is how many times if you have n-elements will currSum += original[j]; be performed.

To calculate that in this case you simply check how many times each loop will be executed.

The outer loop is n-times. Based on the length. Now the inner loop depends both directly and indirectly on the outer loop. As it will be performed n times based on the outer loop and (n/2)-1 times based on its condition.

So the total time is (n^2)/2-1 which is written O(n^2).

If this wasn't your question you should update it to make it more clear.

This is not a complete answer. If this satisifies as an answer then it should be moved to Stack Overflow. As it does not have anything to do with reviewing of code.

Some nitpick as well.

    if(max <= currSum) {
        max = currSum;
    }

Logically you would write it as

    if(currSum > max) {
        max = currSum;
    }

There is no real need to compare if they are equal and then give a new value (which will be equal to the old) if they are equal.

Now for the algorithm itself. If the problem is to find the maximum subarray I suggest you have a read over at Kadane's Algorithm, as it solves this in O(n) instead.

public int maxSubArray (int[] a) {
    int max = 0;
    int cur = 0;
    for (int i : a) {
        max = Math.max (i, max + i);
        cur = Math.max (cur, max);
    }
    return max;
}


Your basic approach looks good.  However I noticed a few things:

You're not checking for strings with 0 characters.

The ternary statement adjusting for odd or even length is unnecessary.  Simply dividing by 2 and adding 1 will work for both odd or even lengths.

Inside the loop, you're calling toLower() twice on each iteration.  This is quite inefficient.  Storing the word converted to lower case in a variable and using that instead of the passed string would be much more efficient.

When testing for inequality it is usually better to use the inequality operator(!=) instead of not(!) and equals(==).  It's more concise and easier to read.