Foobar Fuel Injection Perfection efficiency I was writing this code and was using the BigInteger class because it needs to work with numbers up to 309 digits long, however it takes too long to run with numbers that are too big.  I was hoping to find a way to make it more efficient and faster, but have tried everything in my power.  Any suggestions?

public static int answer (String n) {
    return helper(new BigInteger(n));
}
public static int helper (BigInteger n) {
    BigInteger one = new BigInteger("1");
    BigInteger two = new BigInteger("2");
    BigInteger zero = new BigInteger("0");
    if (n.compareTo(two) == -1) {
        return 0;
    }
    if (n.mod(two).equals(zero)) {
        return helper(n.divide(two)) + 1;
    }
    return Math.min(helper(n.add(one).divide(two)) + 2, helper(n.subtract(one).divide(two)) + 2);
}

I was going to make this a comment, but it's easier as an answer.

Your issue very likely stems from the large amount of division / modulo, those are very slow operations, and the larger the number the slower they are.

If we consider n % 2 == 0, we can replace that modulo entirely with n & 1 == 0, because the bit-pattern of 1 is 0b00000001, which means we will only be looking at the last bit of n (which happens to be the easiest way to determine even vs. odd).

Likewise, you only ever divide by 2, which can be more easily accomplished via n >> 1, which will shift the entire bit-array right one position (which is equivalent to a divide-by-two), accomplished via n.shiftRight(1). Between the two of these, you'll probably find that performance is increased ten-fold. You could run both of these formulas with the value of 5, for example, to prove it to yourself.

The advantage to both of these is the heavily reduced instruction cost. If we take a look at the instruction tables provided by this handy PDF, we can get a rough-estimate of the issue by looking for certain, specific instructions. These may not be the exact instructions the JVM is executing, but they'll give us a good feel for how division vs. shifting and modulo vs. anding perform.

For a modulo, in x86, this is accomplished by using the DIV instruction and checking the remainder register, so we know that we need that instruction for both comparisons.

For anding, in x86, this is accomplished by the AND instruction, and for right-bit-shifting, in x86, this is accomplished by the SHR instruction.

The first instruction I want to lookup is DIV, since we need it for all our comparisons. I'm going to reference the 'Skylake' values (since that is my processor chipset). The table for it is laid out below:

                     µops   µops                        Reciprocal
                     fused  unfused µops                through
Instruction Operands domain domain  each port   Latency put        Comments
DIV         r64      36     36      p0 p1 p5 p6 35-88   21-83

The first thing that stands out there is that the latency is 35-88 cycles. That means the result will be valid after that cycle-count passes. That's a lot.

Let's look at AND:

AND OR XOR  r,r/i    1      1      p0156        1       0.25

Oh boy, latency of 1 already. What about SHR:

SHR SHL SAR r,i      1      1      p06          1       0.5

Same thing, so that gives us an estimate that we should be seeing ~35x improvement on execution time just from these optimizations. In reality it'll be less, a good conservative estimate is ~20x, just because of overhead and I'm not certain this is the course the JVM is taking. (It could have optimized something.) If the JVM did a good optimization, and not one for the special case of 2, then you're likely looking at 2-10x improvement, but that's still a lot of improvement.

The names answer and helper are very non-descriptive. Consider naming the methods after the algorithm or based on what they do, as they're currently non-sensical.


Deciding whether a list of sum types is homogeneous I ran into a problem recently where I had to decide whether a set of sum types was homogeneous (all the same). In itself, this is a pretty simple problem. However, there were a few complicating factors:

There exists a type within the types (call it Id) that is ignored in the comparisons.
There exists a type (call it Mix) that immediately makes the set non-homogeneous, even if all the types are Mix.

The extension of this problem was, given a list of types, is there a single type that can be removed that will make the rest of the types homogeneous (excepting, of course, the Mix type).

For example, if we define our type as:

data Foo = Bar | Baz | Quux | Id | Mix deriving (Eq, Ord, Show)

then [Bar, Bar, Bar] is homogeneous, [Bar, Bar, Baz] would be homogeneous if Baz were removed. Further, [Bar, Bar, Id] is homogeneous, and [Mix, Mix, Mix] is not. Finally, [Bar, Bar, Mix] contains a Mix type, and hence would not be homogeneous even if this type were removed.

import Data.List as List
import Data.Map as Map

data Foo = Bar | Baz | Quux | Id | Mix deriving (Eq, Ord, Show)

-- Is a list of the above sum types homogeneous?
-- Note that Id is ignored in the comparisons, and Mix immediately
-- makes this False.
homogeneous :: [Foo] -> Bool
homogeneous [] = True
homogeneous [x] = if x == Mix then False else True
homogeneous (x:xs) = all isEqNotMix xs
    where isEqNotMix y = ((y == x || y == Id) && y /= Mix)

-- Find a type that would make the set homogeneous if it were removed.
-- Note that if we have an already homogeneous set, then removing the
-- single homoogeneous type from the list will leave it being homogenoeous.
-- The final part of the tuple returns whether it was a homogeneous list or not.
-- Note that in the case of no such type existing, the result is
-- (Mixed, Mixed, False).
homogeneousButOne :: [Foo] -> (Foo, Foo, Bool)
homogeneousButOne xs = case xs of
    [] -> (Id, Id, True)
    [x] -> (x, x, homogeneous [x])
    xs@(x:_) -> if homogeneous xs then (x, x, True)
                else (fst mixed, snd mixed, False)
        where mixed = mixedCase $ List.filter (/= Id) xs

-- Deal with the case where the list is not homogeneous in homogeneousButOne.
mixedCase :: [Foo] -> (Foo, Foo)
mixedCase xs
    | Mix `elem` keys        = (Mix, Mix)
    | Map.size fooMap == 2   = decideTwo fooMap
    | otherwise              = (Mix, Mix)
        where fooMap = List.foldl (\acc x -> Map.insertWith (+) x 1 acc) Map.empty xs
              keys = Map.keys fooMap
              single = Map.filter (== 1) fooMap
              multiple = Map.filter (> 1) fooMap
              firstKey = head . Map.keys
              secondKey = head . tail . Map.keys
               -- Only case where we may not have (Mix, Mix) is if there were
               -- only two types found, and neither of them was `Mix`.
              decideTwo mp = case Map.size single of
                               -- Both types exist > 1 times
                               0 -> (Mix, Mix)
                               -- One type exists once, it is the type that can be removed
                               1 -> (firstKey multiple , firstKey single)
                               -- Both types only exist once (e.g. [Bar, Baz])
                               2 -> (firstKey single, secondKey single)

Any improvements to this code are welcome (excepting the names of the sum types: I realise Foo, Bar, Baz and Quux aren't great, but in the original problem, the names were no more descriptive).

homogeneous could also be defined using pattern matching, though that would not necessarily be an improvement.

However, homogeneousButOne can definitely be simplified using pattern matching, with no need for Data.Map or Data.List.

data Foo = Bar | Baz | Quux | Id | Mix deriving (Eq, Ord, Show)

homogeneous :: [Foo] -> Bool
homogeneous []           = True
homogeneous (Mix : _)    = False
homogeneous (Id  : xs)   = homogeneous xs
homogeneous (x   : [])   = True
homogeneous (a:Id:rest)  = homogeneous (a:rest)
homogeneous (a:b:rest)   = (a == b) && homogeneous (b:rest)

homogeneousButOne :: [Foo] -> (Foo, Foo, Bool)
homogeneousButOne xs
  | null nonId           = (Id, Id, True)
  | x' == Mix            = (Mix, Mix, False)
  | length nonId == 3    = majority2of3 nonId
  | homogeneous nonId    = (x', x', True)
  | homogeneous xs'      = (head xs', x', False)
  | x' == predominant    = (predominant, alt, False)
  | otherwise            = (Mix, Mix, False)
  where nonId = filter (/= Id) xs
        (x':xs') = nonId
        majority2of3 (a:b:c:[]) =
          if      a == b then (a, c, a == c)
          else if a == c then (a, b, a == b)
          else if b == c then (b, a, b == a)
          else                (Mix, Mix, False)
        (predominant, alt, _) = homogeneousButOne xs'


Parse output of Google Cloud command into PHP associative array This is my idea on how to turn Shell exec output in PHP to array output. I just want to share it and get feedback in case there is any better way.

Below is a code example to get server info from GCE.

$shell_command  = "gcloud compute instances list";
$result = shell_exec($shell_command);
//echo "\n$result\n";
$data = explode("\n",$result);
//print_r($data);
$headers = turn_linux_row_to_array($data[0]);
unset($data[0]);
$servers_array = array();
foreach($data as $row){
  $server_data = turn_linux_row_to_array($row,$headers);
   if(!empty($server_data)){
     $servers_array[] = $server_data;
   }
}
//function to move text out put to array
function turn_linux_row_to_array($row,$headers=array()){
$final_data_array = array();
$data_array_position = 0;
$row_length = strlen($row);
$current_word = '';
//echo "\nRow length is :: $row_length\n";
for($i=0; $i<$row_length; $i++){
   $char = substr( $row, $i, 1 );
    if($char != ' '){
     //This is a part of a value
     $current_word .=$char;
    }else{
    if($current_word!=''){
       if(!empty($headers) && isset($headers[$data_array_position]) ){
          $final_data_array[$headers[$data_array_position]] =
    $current_word;
       }else{
         $final_data_array[] = $current_word;
       }
       $data_array_position++;
   }
   $current_word = '';
 }
}
//print_r($final_data_array);
return $final_data_array;
}

This code is complicated, and likely buggy.

If a line does not end in a space character, then the last word on that line will be ignored.
The output of gcloud compute instances list is a table.  For example:

NAME                                             ZONE          MACHINE_TYPE   PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
gke-cluster-asia-eas-default-pool-dc8f484c-knbs  asia-east1-a  n1-standard-1               10.140.0.2   104.155.227.25  RUNNING
gke-cluster-asia-eas-default-pool-dc8f484c-x8cv  asia-east1-a  n1-standard-1               10.140.0.3   104.199.226.16  RUNNING
gke-cluster-asia-eas-default-pool-dc8f484c-z5wv  asia-east1-a  n1-standard-1               10.140.0.4   104.199.134.9   RUNNING

If the table contains an empty value (such as for the "PREEMPTIBLE" column above), then the turn_linux_row_to_array() function will ignore it, resulting in a mismatch between the headers and the values.

I don't recommend trying to improve this code.  Instead, noting that all Google Cloud commands accept a --format option, you should choose a format that is easy to parse.  I would recommend replacing the entire code with:

$servers = json_decode(shell_exec('gcloud compute instances list --format=json'), true);

… to take advantage of json_decode().  That's it — you're done!


Unit-testable C# FizzBuzz To support a demonstration I'm going to be doing, I need a short C# program that can be unit tested. I decided to make a FizzBuzz split into a few methods:

using System;
namespace FizzBuzz
{
    class FizzBuzzer
    {
        public static void Main()
        {
            FizzBuzzer fizzBuzzer = new FizzBuzzer();
            int n = Convert.ToInt32(Console.ReadLine());
            fizzBuzzer.StartLoop(n);
        }

        public int StartLoop(int n)
        {
            int fizzBuzzes = 0;
            for(int i = 0; i < n; i++)
            {
                string output = getOutputForI(i);
                if(output == "FizzBuzz") {
                    fizzBuzzes++;
                }
                Console.WriteLine(output);
            }
            return fizzBuzzes;
        }

        public string getOutputForI(int i)
        {
            string s = "";
            if(i % 3 == 0)
            {
                s += "Fizz";
            }
            if(i % 5 == 0)
            {
                s += "Buzz";
            }
            if(s.Length == 0)
            {
                s = "" + i;
            }
            return s;
        }
    }
}

I want people to focus on the point of my demonstration, and not on potential mistakes in my code. As someone new to C#, I can't evaluate my code very well. Are there any beginner mistakes that would distract pedantic C# experts?

I am of course open to any type feedback, I mainly just want people to not laugh at or get annoyed by my code.

Edit:

here are example unit tests

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FizzBuzz.Tests
{
    [TestClass()]
    public class FizzBuzzerTests
    {
        [TestMethod()]
        public void StartLoopTest()
        {
            Assert.AreEqual(6, FizzBuzzer.StartLoop(100));
        }

        [TestMethod()]
        public void GetOutputFor0()
        {
            Assert.AreEqual("FizzBuzz", FizzBuzzer.getOutputForI(0));
        }

        [TestMethod()]
        public void GetOutputFor4()
        {
            Assert.AreEqual("4", FizzBuzzer.getOutputForI(4));
        }
    }
}

and for context, here is the updated code (based on Ron Beyer's answer) that those tests are run against:

using System;
namespace FizzBuzz
{
    public static class FizzBuzzer
    {
        public static void Main() { }

        public static int CountFizzBuzzes(int max)
        {
            int fizzBuzzes = 0;
            for (int i = 1; i <= max; i++)
            {
                string result = FizzBuzz(i);
                if (result == "FizzBuzz")
                {
                    fizzBuzzes++;
                }

                Console.WriteLine(result);
            }
            return fizzBuzzes;
        }

        public static string FizzBuzz(int input)
        {
            string s = "";
            if (input % 3 == 0)
            {
                s += "Fizz";
            }
            if (input % 5 == 0)
            {
                s += "Buzz";
            }
            if (s.Length == 0)
            {
                s = "" + input;
            }
            return s;
        }
    }
}

Since it's a code-review site, I'll focus on issues you have with your code...
Having Main in your class
I would generally avoid this. I understand that this is probably a single-class demonstration project, but typically C# projects have a Program class that has Main inside of it, and I would stick with that. If you want to be able to unit-test FizzBuzzer, the Main function would not be unit-testable. As a result, your code-coverage of this class will be lower.
Inconsistent method names
You have a method properly cased as StartLoop and then you have an improper cased getOutputForI. Stick with the Microsoft recommendation of Capitalization Rules for Methods which should be Pascal Cased.
Method names and parameters that don't self-document
The name you give a method should identify to the caller what it does. StartLoop both starts and ends a loop, and runs the entire sequence. Ideally this would be named Run instead of StartLoop, but even then, what is it returning? Maybe CountFizzBuzz would be even better. Similarly, getOutputForI certainly gets the output for the method parameter I, but that really doesn't say what it does. Maybe consider renaming it to FizzBuzz(int input) instead.
Similarly the method parameters are not self documenting. What is n exactly in StartLoop? It would be more apparent if the method were something like Run(int max). Which would also require a modification of your for loop because you would stop just shy of max. i is also not apparent of what it is (see a suggested version in the paragraph above).
Mixing UI with code
This makes your code unit-test unfriendly. You can't unit test the output to the console, so in order to unit test this you would need to pass a stream to the output:
public int CountFizzBuzz(int max, TextWriter output)
{
    int fizzBuzzes = 0;
    for (int i = 0; i <=max; i++)
    {
        string fizzBuzz = FizzBuzz(i);
        if (fizzBuzz == "FizzBuzz")
        {
            fizzBuzzes++;
        }
        output.WriteLine(fizzBuzz);
    }
    return fizzBuzzes;
}

Now this is unit-testable because you can create a TextWriter and pass in a value that can be Asserted later.
Inconsistent Brackets
You have two methods of writing brackets in your code, the "Microsoft" way, and the "Java" way. Again, I would stick with Microsoft practices here and use the one that has both brackets on their own lines.
Using an instance object for something that has no state
FizzBuzzer has no state, so why isn't everything static? There isn't a good reason to require a new each time you have to run the "Fizz Buzzer", take up space on the stack, etc. This class should be made static.

So with all my recommendations, here is what it would possibly turn out like:
public static class FizzBuzzer
{
    public static int CountFizzBuzzes(int max)
    {
        return CountFizzBuzzes(max, Console.Out);
    }

    public static int CountFizzBuzzes(int max, TextWriter output)
    {
        int fizzBuzzes = 0;
        for (int i = 0; i <= max; i++)
        {
            string result = FizzBuzz(i);

            if (result == "FizzBuzz")
                fizzBuzzes++;

            output.WriteLine(result);
        }
        return fizzBuzzes;
    }

    public static string FizzBuzz(int input)
    {
        string s = "";

        if (input % 3 == 0)
            s += "Fizz";

        if (input % 5 == 0)
            s += "Buzz";

        if (s.Length == 0)
            s = "" + input;

        return s;
    }
}

I still don't find this completely "ideal" as CountFizzBuzzes really does two things, counts them and outputs them to the stream. This really should be two separate methods for separation of concerns.
Just as a final note, your Main has an issue... Right now when you start the program it just stares at you with a blank window until you mash the right key(s).
public static void Main()
{
    FizzBuzzer fizzBuzzer = new FizzBuzzer();
    int n = Convert.ToInt32(Console.ReadLine());
    fizzBuzzer.StartLoop(n);
}

What is to stop the user here from entering "My Name Is" instead of "42"? The Convert.ToInt32 will throw an exception and the program will terminate. The user isn't even prompted for a number or any thing. At least prompt the user:
There are a multitude of questions on here about how to validate console input, so I'll leave that to you to research, but you should prompt the user "Please Enter a Number:" and if that isn't a number, tell them and ask again (and provide them a way to quit).


Import data from XML files into data.frame I have a number of XML files containing data I would like to analyse. Each XML contains data in a format similar to this:

<?xml version='1.0' encoding='UTF-8'?>
<build>
  <actions>
    ...
  </actions>
  <queueId>1276</queueId>
  <timestamp>1447062398490</timestamp>
  <startTime>1447062398538</startTime>
  <result>ABORTED</result>
  <duration>539722</duration>
  <charset>UTF-8</charset>
  <keepLog>false</keepLog>
  <builtOn></builtOn>
  <workspace>/var/lib/jenkins/workspace/clean-caches</workspace>
  <hudsonVersion>1.624</hudsonVersion>
  <scm class="hudson.scm.NullChangeLogParser"/>
  <culprits class="com.google.common.collect.EmptyImmutableSortedSet"/>
</build>

These are build.xml files generated by the continuous integration server, Jenkins. The files themselves don't have some important data that I would like, like the Jenkins job name, or the build number that created the xml. The job and build ids are encoded into the path of each file like .\jenkins\jobs\${JOB_NAME}\builds\${BUILD_NUMBER}\build.xml

I would like to create a data frame contain job name, build number, duration, and result.

My code to achieve this is the following:

library(XML)

filenames <- list.files("C:/Users/jenkins/", recursive=TRUE, full.names=TRUE, pattern="build.xml")

job <- unlist(lapply(filenames, function(f) {
    s <- unlist(strsplit(f, split=.Platform$file.sep))
    s[length(s) - 3]
}))

build <- unlist(lapply(filenames, function(f) {
    s <- unlist(strsplit(f, split=.Platform$file.sep))
    s[length(s) - 1]
}))

duration <- unlist(lapply(filenames, function(f) {
    xml <- xmlParse(f)
    xpathSApply(xml, "//duration", xmlValue)
}))

result <- unlist(lapply(filenames, function(f) {
    xml <- xmlParse(f)
    x <- xpathSApply(xml, "//result", xmlValue)
    return(x)
}))

build.data <- data.frame(job, build, result, duration)

Which gives me a data frame that looks like this:

  job             build result     duration
1 clean-caches    37    SUCCESS    248701
2 clean-caches    38    FAILURE    1200049
3 clean-caches    39    FAILURE    1200060
4 clean-caches    40    FAILURE    1200123
5 clean-caches    41    SUCCESS    358024
6 clean-caches    42    SUCCESS    130462

This works, but I have serious concerns about it from both a style and a performance point of view. I'm completely new to R, so I don't know what would be a nicer way to do this.

My concerns:

Repeated code:

The code blocks to generate the job and build vectors are identical. Same for duration and result. If I decide to import more nodes from XML, I'll end up repeating even more code.

Several iterations must be made of my list of files. There are thousands of XML files, and this number will likely grow. As above, if I wish to extract more data from the XML, I must add more iterations.

With a few XML files to read you could have done something like this to address your concerns, where the files are only read at once, but all loaded into memory at the same time:

subdirs <- strsplit(dirname(filenames),
                    split = .Platform$file.sep)
subdirs <- lapply(subdirs, rev)
job   <- sapply(subdirs, `[[`, 3)
build <- sapply(subdirs, `[[`, 1)
xmls <- lapply(filenames, xmlParse)
duration <- sapply(xmls, xpathSApply, "//duration", xmlValue)
result   <- sapply(xmls, xpathSApply, "//result", xmlValue)
build.data <- data.frame(job, build, result, duration)

With thousands of files though, it makes more sense to process the files one by one and only keep the useful information before moving from one file to the next. It also makes sense to write a function to process each file. It could be:

build.info <- function(file, xml_fields = c("duration", "result")) {
   res <- list()
   # process filepath
   subdirs <- rev(unlist(strsplit(dirname(file),
                                  split = .Platform$file.sep)))
   res$job   <- subdirs[[3]]
   res$build <- subdirs[[1]]
   # process xml data
   doc <- xmlTreeParse(file)
   build <- doc$doc$children$build
   res[xml_fields] <- lapply(build[xml_fields], xmlValue)
   # return as a data.frame
   as.data.frame(res)
}

See how the function returns a one row data.frame. Then you can call the function on all files via lapply and bind all the outputs together:

build.data <- do.call(rbind, lapply(filenames, build.info))

With a few changes, you can write a more general function that will take one or more files and do the binding itself (like file.info does)

build.info <- function(file, xml_fields = c("duration", "result")) {
   stopifnot(length(file) > 0L)
   if (length(file) == 1L) {
      res <- list()
      # process filepath
      subdirs <- rev(unlist(strsplit(dirname(file),
                                     split = .Platform$file.sep)))
      res$job   <- subdirs[[1]]
      res$build <- subdirs[[3]]
      # process xml data
      doc <- xmlTreeParse(file)
      build <- doc$doc$children$build
      res[xml_fields] <- lapply(build[xml_fields], xmlValue)
      # return data.frame
      as.data.frame(res)
   } else {
      do.call(rbind, lapply(file, build.info))
   }
}

build.data <- build.info(filenames)


Split a string into a list of tokens I have the following assignment that I succeeded in solving, but the code is very inefficient.  I would appreciate if someone could show me a more efficient way, perhaps with substring. Note that I am not allowed to use imports or regexes or add more functions.

/**
 * Separates a given string into tokens, which are the "words" that are
 * separated by one or more occurrences of the given separator character.
 * Returns the tokens as an array of String values.
 */
public static String[] tokenize (String str, char separator) {
    // Removes all the occurrences of the separator at the beginning and end of str
    String source = trim(str, separator);
    String[] tokens = new String[charRunCount (source,separator)+1];
    String tmp = ""; // a string in order to take a word, then run over this string
    int j = 0;
    int i = 0;
    while (i < tokens.length) {
        if ( source.charAt (j) != separator ) {
            do {
                tmp += source.charAt (j);
                if ( j >= source.length () - 1 ) {
                    break;
                }
                else { // so that we math the source length
                    j++;
                }
            } while (source.charAt (j) != separator);
        }
        if ( source.charAt (j) == separator ) {
            j++;
            while (source.charAt (j) == separator) {
                j++;
            }
        }
        tokens[i] = tmp;// taking the token into place
        tmp = ""; //resetting the token so we can begin anew

        i++;
    }
    return tokens;
}

the charRunCount() function:

public static int charRunCount(String str, char c){
    char last = 0;
    int counter = 0;
    for (int i = 0; i < str.length(); i++) {
        // whenever a run starts.
        if (last != c && str.charAt(i) == c) {
            counter++;
        }
        last = str.charAt(i);
    }
    return counter;
}

tmp is never a good name for a variable.  In this case, you should call it token instead, or perhaps word.  And you rightly complain that building strings using repeated += operations is inefficient, and correctly suggest that .substring() would be better.

Logically, then, you need to find the starting and ending indexes of each token!  So, let's define those helper functions (as private static functions):

/**
 * Considering str starting at startIndex, find the index at which the
 * next token starts.
 *
 * @return The index of the start of a token (or str.length() if no more
 *         tokens).
 */
private static int start(String str, char sep, int startIndex) {
    int i;
    for (i = startIndex; i < str.length() && str.charAt(i) == sep; i++);
    return i;
}

/**
 * Considering str starting at startIndex, find the index at which the
 * current token ends.
 *
 * @return The index just beyond the end of a token (the index of a
 *         sep character, or str.length() if this is the last token)
 */
private static int end(String str, char sep, int startIndex) {
    assert(str.charAt(sep) != sep);
    int i;
    for (i = startIndex; i < str.length() && str.charAt(i) != sep; i++);
    return i;
}

Then, we can use them in tokenize():

public static String[] tokenize(String str, char sep) {
    int tokenCount = 0;
    for (int s, e = 0; (s = start(str, sep, e)) < str.length(); e = end(str, sep, s)) {
        tokenCount++;
    }
    String[] tokens = new String[tokenCount];
    tokenCount = 0;
    for (int s, e = 0; (s = start(str, sep, e)) < str.length(); ) {
        tokens[tokenCount++] = str.substring(s, e = end(str, sep, s));
    }
    assert(tokens.length == tokenCount);
    return tokens;
}

Notice that now you can take advantage of the helper functions to predetermine the size of the array.  Also, a lot of the repetitiveness of your conditions and loops is eliminated.

All of the analysis is done using string indexes, so there is no string manipulation other than just the essential .substring() calls — and even the trim() call is gone!


Longest common prefix for set of strings Question:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example :
Input: strs = ["flower","flow","flight"]
Output: "fl"

Source: https://leetcode.com/problems/longest-common-prefix/
My Code:
public String longestCommonPrefix(String[] strs) {
        StringBuilder lcp = new StringBuilder();

        //compute min length
        int minLength = Integer.MAX_VALUE;
        for(String str:strs){

            if (str.length() < minLength) {
                minLength = str.length();
            }

        }

        for (int i = 0; i < minLength;i++){
            char cmp = strs[0].charAt(i);
        for(String str:strs){

            if (str.charAt(i) != cmp) {
                return lcp.toString();
             }

           }
          lcp.append(cmp);
        }

        return lcp.toString();
    }

Questions:

Current time complexity is O(mn) where n is number of strings and m is the min string length.
Can it be faster?
How to improve code style in general.

1. Don't think too much about performance.
Worst performance problems arise because the coder thought something could be faster but she didn't consider that the JVM does runtime optimizations for her code.
So always prefer writing readable code that works. Only step into performance optimization if you actually faced a performance issue and you have proven by measurement that this particular piece of code is the problem and the alternative approach really solves the problem.
2. Why are you inventing the wheel a 4th time?
The JVM has methods to compare strings. There is even a startsWith() method that would perfectly fit.
3 Structure your code
Your code has 2 obvious parts. The first one you marked with an inline comment.
Better use methods with good names for this kind of structuring.
An alternative solution could look like this:
My solution made some assumption on the behavior of the methods in the String class which I verified with spikes coded as JUnit Tests along with the acceptance test using your given example.
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class LongestCommonPrefixTest {

    @Test
    void spike__does_StartsWith_returnTrueForTheEmptyString() {
        assertTrue("someWord".startsWith(""));
    }

    @Test
    void spike__does_substring_returnTheEmptyStringForEndIndexZero() {
        assertEquals("", "someWord".substring(0, 0));
    }

    @Test
    void spike__does_substring_returnShorterStringForLengthMinus1() {
        String someWord = "someWord";
        assertEquals("someWor", someWord.substring(0, someWord.length() - 1));
    }

    @Test
    void acceptanceTest() throws Exception {
        String[] strs = { "flower", "flow", "flight" };
        String longestCommonPrefix = //
                new LongestCommonPrefix().longestCommonPrefix(strs);
        assertEquals("fl", longestCommonPrefix);
    }

}

And this is the solution I came up with:
public class LongestCommonPrefix {
    public String longestCommonPrefix(String[] strs) {
        String currentPrefix = selectFirstWordOrEmptyString(strs);
        for (String currentWord : strs) {
            currentPrefix = findCommonPrefixIn(currentPrefix, currentWord);
        }
        return currentPrefix;
    }

    private String selectFirstWordOrEmptyString(String[] strs) {
        return 0 == strs.length ? "" : strs[0];
    }

    private String findCommonPrefixIn(String currentPrefix, String currentWord) {
        while (!currentWord.startsWith(currentPrefix)) {
            currentPrefix = currentPrefix.substring(0, currentPrefix.length() - 1);
        }
        return currentPrefix;
    }
}

A performance improvement could be possible if you always pass the shorter of currentPattern and currentWord as first parameter to the private method and the longer one as second. But as I wrote you shouldn't do that unless necessary.


Changing desktop background to the next available one How could I improve this working Perl script, which changes my desktop background to the next available one, without opening a terminal? Specifically, how could I iterate over my .fehbg and walls/ lazily, without reading them into arrays?  I couldn't find a way to do that; I need the for loops.

Other than that, are there any inefficiencies in my program, which could be spotted by a more experienced programmer?

#!/usr/bin/perl
# A background switching script which can be run from dmenu

use 5.18.2;
use strict;
use warnings;
use File::Basename;

my @fehbg = ();
my @files = ();
open 'FEHFH', '</home/chummer/.fehbg';
while(<FEHFH>){
    @fehbg = split/'/;
}
close FEHFH;
my $current = basename($fehbg[-2]);
opendir WALLSDIR, '/home/chummer/pictures/walls';
foreach(readdir WALLSDIR){
    unless($_ eq '.' || $_ eq '..'){
    push(@files, $_);
}
}
closedir WALLSDIR;
for(my $i = 0; $i <= $#files; ++$i){
    if($current eq $files[$i]){
    if(exists($files[$i+1])){
        foreach($files[$i+1]){ s/\s+/\\ /g; }
    system"feh --bg-fill /home/chummer/pictures/walls/$files[$i+1]";
    last;
    }
    else{
        foreach($files[0]){ s/\s+/\\ /g; }
    system"feh --bg-fill /home/chummer/pictures/walls/$files[0]";
    last;
    }
}
}

Use while to iterate over directory elements and skip reading them all at once into array,

opendir my $WALLSDIR, '/home/chummer/pictures/walls';
while (my $file = readdir($WALLSDIR)) {
    next if $file eq '.' or $file eq '..';

    # ..
}

Since you're not checking if open() or opendir() calls were successful at all, put

use autodie;

at beginning of your script, and exceptions with description will be thrown when some of these calls fails.

Stylistic remark, my @fehbg = (); is same as just my @fehbg;

Use lexical file-handles together with three argument open (also lexical dir-handle for opendir),

open my $FEHFH, '<', '/home/chummer/.fehbg';

Again stylistic remark,

for my $i (0 .. $#files)

is a more readable/simpler equivalent of,

for (my $i = 0; $i <= $#files; ++$i)

Then foreach($files[$i+1]){ s/\s+/\\ /g; } is longer and less performant version of $files[$i+1] =~ s/\s+/\\ /g;


Multiplication table using a list comprehension I have just started reading through Learn you a Haskell I got up to list comprehension and started to play around in GHCi, my aim was to make a times table function that takes a number n and an upper limit upperLimit and return a nested list of all the 'tables' up to n for example

> timesTable 2 12
[[1,2..12],[2,4..24]]

the actual function/list comprehension I came up with is

> let timesTable n upperLimit = [[(n-y) * x | x <- [1..upperLimit]] | y <- reverse [0..(n-1)]]

Any feedback on the above would be greatly appreciated as this is the first time I have really used a functional language, so if there is a better way or something I have missed please let me know.

Your function could be simplified a little, and I find it helpful to define functions using declarations, since type signatures are really helpful (although admittedly your example is simple enough that it doesn't matter):

timesTable :: Int -> Int -> [[Int]]
timesTable n u = [[y * x | x <- [1 .. u]] | y <- [1 .. n]]

The key thing I noticed was that you were using n-y: it should be obvious that this part of the expression becomes the following values in each iteration of y: [n-(n-1), n-(n-2), ... n-0], which is just [1 .. n].


Parallel SQL queries using completable future My problem is I'm having a table and 7 child table. I'm fetching details using querying the main table first then querying the child tables one by one sequentially. To improve performance I decided to execute all the seven queries parallely using completable future.

 StoryDetail storyDetail = new StoryDetail();
      CompletableFuture<IStoryDetail> iStoryDetailCompletableFuture = CompletableFuture
          .supplyAsync(() -> storyRepository.getStoryDetails(id), executorService);
      CompletableFuture<List<Comment>> iCommentFuture = CompletableFuture
          .supplyAsync(() -> commentRepository.getComments(id), executorService);
      CompletableFuture<List<Images>> iImageFuture = CompletableFuture
          .supplyAsync(() -> imageRepository.getImagesByStoryId(id), executorService);

Here we are executing all the queries sequentially:

CompletableFuture.allOf(iCommentFuture, iStoryDetailCompletableFuture, iImageFuture)
      ;

And waits for all of them to finish then sets the value in the StoryDetail object:

  storyDetail.setComments(iCommentFuture.get());
  storyDetail.setImages(iImageFuture.get());
  mapStoryDetail(iStoryDetailCompletableFuture.get(), storyDetail);

Is the approach correct?

Yes, your approach is correct.

However, you parallelize various queries, which probably go to a remote backing database. As you told us nothing about the runtime of these queries, the nature of the database, the complexity of the underlying statements, I can only ask you to measure.

Parallelism induces overhead - in the runtime AND in program complexity. Check, whether it is worth it, and where your bottlenecks lie.

In my experience from enterprise applications, real big data transfers are normally not made better by parallelism, as the bottleneck is often the network between application server and database.


Cartesian product of two tuples - python I'm solving exercise 4 from Discussion 3 of Berkley's CS 61A (2012) (see page 4):

Fill in the definition of cartesian_product. cartesian_product takes in two tuples and returns a tuple that is the Cartesian product of those tuples. To find the Cartesian product of tuple X and tuple Y, you take the first element in X and pair it up with all the elements in Y. Then, you take the second element in X and pair it up with all the elements in Y, and so on.
def cartesian_product(tup_1, tup_2):
    """Returns a tuple that is the cartesian product of tup_1 and tup_2.
    >>> X = (1, 2)
    >>> Y = (4, 5)
    >>> cartesian_product(X, Y)
    ((1, 4), (4, 1) (1, 5), (5, 1), (2, 4), (4, 2) (2, 5), (5, 2))
    """

My solution:
def cartesian_product_recursive(tup_1, tup_2):
    """Returns a tuple that is the cartesian product of tup_1 and tup_2

    >>> X = (1, 2)
    >>> Y = (4, 5)
    >>> cartesian_product(X, Y)
    ((1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2))
    """
    length1 = len(tup_1)
    length2 = len(tup_2)
    def product(tup_1, tup_2, index1, index2):
        if index1 == length1:
            return ()
        elif index2 == length2:
            return product(tup_1, tup_2, index1 + 1, 0)
        else:
            return ((tup_1[index1], tup_2[index2]),) + ((tup_2[index2], tup_1[index1]), ) + product(tup_1, tup_2, index1, index2 + 1)
    return product(tup_1, tup_2, 0, 0)

I know that Python has a built-in function itertools.product, but at this point in the course, the only operations on tuples that we have studied are indexing [1] [-1], slicing [1:], and concatenation +, so my solution needs to restrict itself accordingly.
Can this solution be improved?

If you can use the built-in itertools module, then itertools.product is probably the easiest, but it probably not allowed.  itertools.product creates an iterable of the cartesion product of two sequences.  Since you want it with both the tup1 element first and the tup2 element first, you need to do it twice:

def cartesian_product_itertools(tup1, tup2):
    return tuple(product(tup1, tup2))+tuple(product(tup2, tup1))

The second approach would be to roll your own generator-based solution, using the yield statement.  This can then be converted to a tuple in the same way.  You need an inner function to handle the generator, and an outer function to convert it to a tuple:

def cartesian_product_iter(tup1, tup2):
    def cartesian_product_iter_inner(tup1, tup2):
        for t1 in tup1:
            for t2 in tup2:
                yield t1, t2
                yield t2, t1
    return tuple(cartesian_product_iter(tup1, tup2))

You can also do a similar looping version:

def cartesian_product_loop(tup1, tup2):
    res = ()
    for t1 in tup1:
        for t2 in tup2:
            res += ((t1, t2), (t2, t1))
    return res

For a recursive version, you can greatly simplify by using slices instead of indexes:

def cartesian_product_recursive(tup_1, tup_2):
    res = ((tup_1[0], tup_2[0]), (tup_2[0], tup_1[0]))
    if len(tup_2) == 1:
        return res
    res += cartesian_product_recursive(tup_1[:1], tup_2[1:])
    if len(tup_1) == 1:
        return res
    res += cartesian_product_recursive(tup_1[1:], tup_2)
    return res

I prefer short-circuiting, hence the returns.  If you prefer if...else, here is an equivalent implementation:

def cartesian_product_recursive_2(tup_1, tup_2):
    res = ((tup_1[0], tup_2[0]), (tup_2[0], tup_1[0]))
    if len(tup_2) > 1:
        res += cartesian_product_recursive_2(tup_1[:1], tup_2[1:])
    if len(tup_1) > 1:
        res += cartesian_product_recursive_2(tup_1[1:], tup_2)
    return res


Luhn algorithm MS-SQL This a solution Luhn algorithm for credit validation.

This algorithm is a basic one inspired by wikipedia. I mean no check for length, type, and so on. You can enhance the base code as you want it to be.

The listing code of the following fucntion is tested on MSSQL 2012:

IF OBJECT_ID('dbo.LuhnALGValidation') IS NOT NULL
BEGIN
    DROP FUNCTION dbo.LuhnALGValidation
    IF OBJECT_ID('dbo.LuhnALGValidation') IS NOT NULL
        PRINT '<<< FAILED DROPPING FUNCTION dbo.LuhnALGValidation >>>'
    ELSE
        PRINT '<<< DROPPED FUNCTION dbo.LuhnALGValidation >>>'
END
go
CREATE FUNCTION dbo.LuhnALGValidation
(
@Luhn VARCHAR(8000)
)
RETURNS BIT
AS
BEGIN
IF @Luhn LIKE '%[^0-9]%'
RETURN 0
DECLARE @Index SMALLINT,
@Multiplier TINYINT,
@Sum INT,
@Flag INT,
@temp TINYINT,
@Plus TINYINT
SELECT @Index = LEN(@Luhn),
@Multiplier = 1,
@Flag = 0,
@Sum = 0
WHILE @Index >= 1
BEGIN
    SELECT @temp = CAST(SUBSTRING(@Luhn, @Index, 1) AS TINYINT)
    IF @Flag = 1
    BEGIN
        SELECT @temp = 2 * CAST(SUBSTRING(@Luhn, @Index, 1) AS TINYINT)
        IF @temp > 9
        BEGIN
            SELECT @temp = @temp - 9
        END
    END

    SELECT @Sum = @Sum + @temp

    IF @Flag = 1
        SELECT @Flag = 0
    ELSE
        SELECT @Flag = 1
    SELECT @Index = @Index - 1
END
RETURN CASE WHEN @Sum % 10 = 0 THEN 1 ELSE 0 END
END
go
IF OBJECT_ID('dbo.LuhnALGValidation') IS NOT NULL
    PRINT '<<< CREATED FUNCTION dbo.LuhnALGValidation >>>'
ELSE
    PRINT '<<< FAILED CREATING FUNCTION dbo.LuhnALGValidation >>>'
go

I want it to work in database side. No matter in performance.

If you can help me to enhance this code.

Checking if the input is valid

You use the pattern `` to check if the input contains any non numeric characters and then return 0 if it does. There is a better way to do this, use the ISNUMERIC() function.

VARCHAR(8000)?

Your input allows 8000 characters, which seems like more than you are likely to need. I would consider lowering this to a value that makes a little more sense. I can't see you ever needing to validate numbers over a hundred characters in length. Feel free to correct me if I am wrong about this though, I don't know what kind of data you intend to work with.

Changing @x = @x + y to @x += y

I don't know if you are familiar with this syntax, but instead of doing:

SELECT @temp = @temp - 9

you can do:

SELECT @temp -= 9

which does exactly the same.

@Plus

You seem to have mistakenly left the @Plus variable in the query, you can delete it as it is not used.

A neat little trick

Here is a little tick to toggle the value of @Flag between 1 and 0:

SELECT @Flag = 1 - @Flag

This works because if @flag is one, it becomes this:

SELECT @Flag = 1 - 1

and if `@Flag1 is zero then it becomes this:

SELECT @Flag = 1 - 0

Your IF Statement

Firstly, you set @temp, then if a condition is true, you set it to something else. This would be better expressed as an IF statement to set it if the condition is true, and an else to set it otherwise. This means that @temp is set at most twice in each iteration of the loop, as opposed to the current at most three times.

Speaking of IF's

I understand that leaving out the BEGIN/END where you can is tempting, but it makes it more difficult for people to understand what the query is actually doing. I would recommend including the BEGIN/END even for the smallest IF statements.

Setting multiple variables using SELECT

According to this page, and my own testing after reading, it is more efficient to use select to set multiple variables at once. If you choose to use the little trick above to set @Flag, you can reduce this:

SELECT @Sum = @Sum + @temp

IF @Flag = 1
    SELECT @Flag = 0
ELSE
    SELECT @Flag = 1
SELECT @Index = @Index - 1

to this:

SELECT
    @Sum += @temp,
    @Flag = 1 - @Flag, --Trick to toggle @Flag between 1 and 0
    @Index -= 1

The end result

I took the liberty of combining the declaring and initial setting of the variables:

CREATE FUNCTION dbo.LuhnALGValidation
(
    @Luhn VARCHAR(8000)
)
RETURNS BIT
AS
BEGIN

IF ISNUMERIC(@Luhn) = 0
BEGIN
    RETURN 0
END

DECLARE
    @Index SMALLINT = LEN(@Luhn),
    @Multiplier TINYINT = 1,
    @Sum INT = 0,
    @Flag INT = 0,
    @temp TINYINT;

WHILE @Index >= 1
BEGIN

    IF @Flag = 1
    BEGIN
        SELECT @temp = 2 * CAST(SUBSTRING(@Luhn, @Index, 1) AS TINYINT)
        IF @temp > 9
        BEGIN
            SELECT @temp -= 9
        END
    END
    ELSE
    BEGIN
        SELECT @temp = CAST(SUBSTRING(@Luhn, @Index, 1) AS TINYINT)
    END

    SELECT
        @Sum += @temp,
        @Flag = 1 - @Flag, --Trick to toggle @Flag between 1 and 0
        @Index -= 1
    END

    RETURN CASE WHEN @Sum % 10 = 0 THEN 1 ELSE 0 END
END
GO


Divide a set of strings into those which contain "a" and those which don't I am beginning to learn Python on my own through edX and I was given this basic problem: "Given a list of cities, separate the list into two lists, namely one with cities containing the letter 'a' in their name and one with cities not containing the letter 'a'."

This is my approach. It works, but I can't help but feel like there is a much more concise way to get this result. If anybody could offer some other methods I would be interested:

cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]

a_city, no_a_city = [],[]
for city in cities:
    for x in range(0, len(city)):
        if city[x] == "a":
            a_city.append(city)
            break
        else:
            if x == len(city) - 1:
                no_a_city.append(city)

print("a_city:", a_city)
print("no_a_city:", no_a_city)

I am also interested in learning more about the interaction between nested loops/conditionals and complexity if anybody has some resources.

This usecase is actually covered by one of the itertools recipes. itertools is a package in the Python standard library that supplies fast and efficient tools for iterating over things or creating certain iterable things (like the combination of all pairs and such). It is an often used library and well worth it to get acquainted with.

The recipe is as follows:

from itertools import filterfalse, tee

def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

In your specific case you would use it like this:

if __name__ == "__main__":
    cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
    no_a_city, a_city = map(list, partition(lambda city: "a" in city, cities))
    print("a_city:", a_city)
    print("no_a_city:", no_a_city)

The map(list, ...) part is needed because what the partition function returns are generators that generate values on the fly. They can be consumed into a list.

The predicate used is a lambda function, an anonymous function which in this case returns truthy or falsy values. It is used to test each element of the iterable.

Instead of manually iterating over each name (even worse, over each index of each name, have a look at Loop Like A Native), I used the fact that strings support the in operator.

I also added a if __name__ == "__main__": guard to allow importing from this script from another script.

One thing you could have used in your code is the fact that for loops have an optional else clause which is run if no break statement interrupted the loop:

a_city, no_a_city = [],[]
for city in cities:
    for char in city:
        if char == "a":
            a_city.append(city)
            break
    else:
        no_a_city.append(city)

As for complexity, this has the same complexity as your code. You have two nested for loops, making this on average \$\mathcal{O}(nk)\$ with \$n\$ being the number of cities and \$k\$ being the average length of the city names.

The in operator for strings is \$\mathcal{O}(k)\$ (it is just the same loop you wrote, but probably written in C) and it is used once per city. However, due to the tee my code iterates twice over the cities, so would be \$\mathcal{O}(2nk)\$, which in terms of algorithmic complexity is also \$\mathcal{O}(nk)\$.


App that sets configuration data I've been writing my code like this for a really long time now, I am wondering if there is a more efficient way to do this. This is especially after a senior developer said my code was very amateurish.

App Purpose: I need to set some data for new employees when they join our organisation. This is a simple command app written in .net that takes an argument, splits it and then assigns the variables. A command might look like this:

Setdata.exe -Marcus -true -true -false -false.

The output is a file that we install on one of our sql servers.

The example below is a small one, but it is not common for the settings to hit 40-50 lines.

Code:

  internal static void ExportSolution(SqlService service, string parms)
    {
        try
        {
            parms = parms.Replace(" ", "");
            string[] args = parms.Split('-');

            string solutionName = args[1];
            bool managed = Convert.ToBoolean(args[2]);
            bool prefix= Convert.ToBoolean(args[3]);
            bool profile= Convert.ToBoolean(args[4]);
            bool email= Convert.ToBoolean(args[5]);
            bool calendar= Convert.ToBoolean(args[6]);
            bool appSettings= Convert.ToBoolean(args[7]);

            AppSettingsRequestAppSettingsRequest= new AppSettingsRequest();

            AppSettingsRequest.SolutionName = solutionName;

            AppSettingsRequest.Managed = (managed == true) ? true : false;

            AppSettingsRequest.prefix= (prefix== true) ? true : false;

            AppSettingsRequest.Managed profile= (profile== true) ? true : false;

            AppSettingsRequest.email= (email== true) ? true : false;

            AppSettingsRequest.calendar= (calendar== true) ? true : false;

            AppSettingsRequest.appSettings= (appSettings== true) ? true : false;

            byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
            string filename = solutionName + ".zip";
            File.WriteAllBytes(filename, exportXml);

            Console.WriteLine("Solution exported to {0}.", filename);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

Initial thoughts are that I could create a new class and then instantiate a new object with these variables, but is there anything to gain from doing this?

Ignored code

From the code sample provided, you're not actually doing anything with the AppSettingsRequest object after you've created it. Why? What is the purpose of this object?

Global variables

byte[] exportXml = exportSolutionResponse.ExportSolutionFile;

What is exportSolutionResponse? It comes out of nowhere, without being defined anywhere. This seems to be a global variable (I can't otherwise explain its existence).

Global variables are generally a bad idea. They create shortcuts in code that is one of the straws that will eventually break the camel's back (in this case, unmaintainable spaghetti code).

Stringly typing

As you seem to be using a console application, the parameters can be parsed an an array of values, not as a single string. Why are you concatenating these values into a string, only to then split the string again?

This can be improved by using explicit method parameters:

internal static void ExportSolution(SqlService service, string name, params bool[] values)

This means you no longer have to do the conversion in this method; which is a good separation of concerns.

Given that you are expect a fixed amount of booleans, it's better to explicitly name these booleans instead of allowing any array of arbitrary length:

internal static void ExportSolution(SqlService service, string name, bool managed, bool prefix, bool managedprofile, bool email, bool calendar, bool appsettings)

Vague names

Your variable names leave something to be desired. I can only guess at what these variables mean. Rename them to something clearer. I've guessed at what these booleans are used for:

internal static void ExportSolution(SqlService service, string userName, bool isManaged, bool hasPrefix, bool useManagedProfile, bool importEmail, bool importCalendar, bool overrideAppSettings)

Don't get caught up on the names, my interpretations are only a guess. But these examples are much clearer on what the impact of these booleans is.

No null checking

This ties into the earlier point. In your original code, you are taking in any string and splitting it into an array, and then assuming that this array will contain at least 8 values.

What happens when the array contains less than 8 values? You're going to end up with an IndexOutOfRangeException. While you do catch and display exceptions, it's still better to avoid exceptions where possible. It's not that hard to validate the length of the array before you try to access its elements.

if(args.Length < 8)
{
    Console.WriteLine("Insufficient parameters provided");
    return;
}

Pokémon exception handling (link)

catch (Exception ex)
{
    Console.WriteLine(ex);
}

Instead of catching all exceptions, catch the exceptions you're interested in. For example:

catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Insufficient parameters provided");
}

Note: as mentioned before, it is better to prevent the exception when possible, instead of just catching it afterwards. This only serves as a simple example of how you catch specific exceptions instead of all possible exception types.

Needlessly verbose code

AppSettingsRequest.Managed = (managed == true) ? true : false;

this can immediately be refactored to:

AppSettingsRequest.Managed = managed;

For two reasons:

== true is redundant. If the variable is already a boolean, its "trueness" doesn't need to be checked. managed == true will always equal managed.
? true : false is redundant. The evaluation (left of the ?) is already a boolean, and what you're doing here is saying "if this evaluation is true, set this to true; if this evalutation is false, set it to false". It's much short to just say "set this to the evaluation's value". managed ? true : false will always equal managed.

Note: if you were using nullable booleans, bullet point 1 wouldn't necessarily be correct (as you're also checking for non-null in that case), but you're not using nullable booleans here.

Saving some lines of code

bool managed = Convert.ToBoolean(args[2]);
AppSettingsRequest.Managed = managed;

Can be shortened to

AppSettingsRequest.Managed = Convert.ToBoolean(args[2]);

In general, I wouldn't advise this. The added clarity from separating the steps makes things easier. However, given that one of your main issues is the amount of settings, combining the two steps will halve your line count. At the same time, the combined line is not unreadable by any stretch of the imagination so it's perfectly okay to combine them here.

Separating your concerns

In general, your method is taking on too many tasks. It manipulates the input string, converts the values, handles them, writes to storage and updates the UI (console output). This is too many responsibilities for a single method.

However, this seems to be a very small and simple console application, and the overhead cost of implementing some separations may end up costing more effort than it's worth. I would still suggest a basic separation between the following tasks:

Parsing the input values (to their correct string/bool types)
Instantiating the settings object and settings its properties
Writing your data to disk


Twiddle Multiple Bits The following C# methods take n bits and operates on them all in one pass.

// Sets n bits to zero at index i.
uint zerobits(uint x, int n, int i) {
    return x & ~((uint.MaxValue >> (sizeof(uint) * 8 - n)) << i);
}

// Sets n bits to one at index i.
uint setbits(uint x, int n, int i) {
    return x | ((uint.MaxValue >> (sizeof(uint) * 8 - n)) << i);
}

// Toggles n bits at index i.
uint togglebits(uint x, int n, int i) {
    return x ^ ((uint.MaxValue >> (sizeof(uint) * 8 - n)) << i);
}

Is there any way to optimize these? Or do they not need to be optimized at all?

The following is the IL generated for zerobits(uint x, int n, int i);

There seems to be full optimization by inlining sizeof(uint) * 8 = 32, and uint.MaxValue = -1 = 0xffffffff

The CIL runtime stack works only with 4 byte or 8 byte integers, even the LDC_I4_S pushes a byte as a 4 byte integer to the stack, so, there is no performance gain in changing parameter types to smaller integers, byte or short

A slight improvement (may be);

These methods need not to be instance members and can be defined static. Changing them to static will remove 1 push instruction to the stack (argument 0, the instance to invoke the method on) at the caller site.

That's all. 100 million iterations on my 2-cpu 8 core windows 7 HP machine executes in 17-18 ms, and 8-9 ms of it seems to be the iteration (empty loop) itself.

IL_0000:  ldarg.1       // push x (stack : x)
IL_0001:  ldc.i4.m1     // push 0xffffffff (uint.MaxValue is inlined, m1 = -1 = 0xffffffff) (stack : x, 0xffffffff)
IL_0002:  ldc.i4.s   32 // push 0x20 (sizeof(uint) * 8 is inlined) (stack: x, 0xffffffff, 0x20)
IL_0004:  ldarg.2       // push n (stack: x, 0xffffffff, 0x20, n)

IL_0005:  sub           // subtract -> (0x20 - n) (stack : x, 0xffffffff, 0x20-n)

// The following two instructions are for ENSURING SHIFTING RIGHT WITH A POSITIVE INTEGER
IL_0006:  ldc.i4.s   31 // push 0x1f (stack : x, 0xffffffff, 0x20-n, 0x1f)
IL_0008:  and           // (0x20 - n) & 0x1f (stack : x, 0xffffffff, 0x20-n) - We assume that n < 0x20

IL_0009:  shr.un        // shift right unsigned, 0xffffffff >> (0x20-n) (stack : x, 0xffffffff >> (0x20-n))

IL_000a:  ldarg.3       // push i (stack : x, 0xffffffff >> (0x20-n), i)

// The following two instructions are for ENSURING SHIFTING LEFT WITH A POSITIVE INTEGER
IL_000b:  ldc.i4.s   31 // push 0x1f (stack : x, 0xffffffff >> (0x20-n), i, 0x1f)
IL_000d:  and           // (i & 0x1f) (stack : x, 0xffffffff >> (0x20-n), i) - We assume that i < 0x20

IL_000e:  shl           // shift left (0x20-n) << i (stack : x, (0xffffffff >> (0x20-n)) << i)
IL_000f:  not           // not (stack : x, ~(0xffffffff >> (0x20-n)) << i))
IL_0010:  and           // and x & ~(0xffffffff >> (0x20-n)) << i) (stack : x & ~((0xffffffff >> (0x20-n)) << i)
IL_0011:  ret           // return x & ~(0xffffffff >> (0x20-n)) << i)


Processing a list of pairs of items using promises and functional programming I posted an answer on StackOverflow which I believed to be adherent to the principles of Functional Programming.

However, I was told by the original asker that it was not 'functional' as my function used an internal variable oldData which kept track of results.

I believe that the code still satisfies the paradigms of functional programming as it does not mutate it's arguments, does not use globals and has no side effects (assuming action is not a network call)

Is the function process() violating the principles of functional programming? If so, how would I fix it?

var items = [
    ["item1", "item2"],
    ["item3", "item4"],
    ["item5", "item6"],
    ["item7", "item8"],
    ["item9", "item10"]
]

function action(item) {
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            resolve(item + ":processed");
        }, 100)
    });
}

function process(items) {
  return items.reduce((m, d) => {
    const promises = d.map(i => action(i));
    let oldData;
    return m.then((data) => {
        oldData = data;
        return Promise.all(promises);
      })
      .then(values => {
        //oldData.push(...values);
        oldData.push.apply(oldData, values);
        return Promise.resolve(oldData);
      })
  }, Promise.resolve([]))
}

process(items).then(d => console.log(d))

//Prints:

// ["item1:processed","item2:processed","item3:processed","item4:processed","item5:processed","item6:processed","item7:processed","item8:processed","item9:processed","item10:processed"]

The original asker suggested that I update my code to use concat instead of push to create immutable arrays every time to make this properly functional. Does that make sense?

Does this function break the paradigm of functional programming in JS?

Short answer: It depends

One common response I get from Software Engineering SE on this topic is you don't have to be pure all the time. A function can still act functional even if the implementation isn't written in a functional manner. Take for example the following:

// All return an array with numbers starting from s to e with no
// side-effects and takes all input from args. The first one is
// obviously not "functional" but works just as well as the others.

function range(s, e){
  const array = []
  for(let i = s; i < e; i++){
    array.push(s)
  }
  return array
}

function range(s, e){
  return Array(e - l).fill(null).map((v, i) => s + i)
}

function range(s, e){
  return s == e ? [] : [s, ...range(s + 1, e)]
}

Striking a balance between ideal and practical is also a deciding factor. For instance, recursion is not a foreign concept in JS. But historically, due to stack size limits, loops became more prevalent. You can safely assume people can read loops better than recursion, and are therefore more likely to understand the first sample than the other two.

It looks like the purpose of process function is to batch-process arrays of items. This can be done with recursion. The idea is to process the current item, then concat the results of the next call, which does the same thing until there's nothing in the array. If you use Node or have Babel to transpile, you can use async/await to simplify the syntax.

const process = async (i) => {
  if (!i.length) return []

  const r1 = await Promise.all(i[0].map(action))
  const r2 = await process(i.slice(1))

  return [...r1, ...r2]
}

If you can't do async/await, here's an expanded version with regular promise syntax.

function process(i) {
  if (!i.length) return Promise.resolve([])

  return Promise.all(i[0].map(action)).then(function(r1) {
    return process(i.slice(1)).then(r2 => r1.concat(r2))
  })
}


Tetris-like algorithm (2D matrix) The algorithm should be checking if the block fits perfectly when it falls.

The block is always the same shape:

 .##....

   ..##....

Keep in mind I wrote this in 1 hour - all the time we had for the task. How can I make it more optimized?

#include <stdio.h>
#include <stdlib.h>
int check(char *k, int r, int s){
    int i, j, flag = 0;
    for (i = 0; i < r; i ++){
        for (j = 0; j < s; j ++){
            if (k[i * s + j] == '*' && k[(i + 1*2) * s + j + 1] == '.'){
                flag = 1;
            }
        }
    }
    return flag;
}
void toLadders(char *k, int r, int s){
    int i, j;
    for (i = 0; i < r; i ++){
        for (j = 0; j < s; j ++){
            if (k[i * s + j] == '*')
             k[i * s + j] = '#';
        }
    }

}
int main()
{
    int i, j, r, s;
    int flag = 0;

    do{
        scanf("%d %d", &r, &s);
    }while(r < 1 || s > 15);

    char matrix[r][s];

    for (i = 0; i < r; i ++){
        for(j = 0; j < s; j++){
            scanf(" %c", &matrix[i][j]);
        }
    }

    for (i = 0; i < r; i ++){
        for(j = 0; j < s; j++){
            if (matrix[i][j - 1] == '.' && matrix[i][j] == '#' && matrix[i][j + 2] == '.'
                && matrix[i + 1][j] == '.' && matrix[i + 1][j + 1] == '#' && matrix[i + 1][j + 2] == '#' && matrix[i + 1][j + 3] == '.'){

                matrix[i][j] = '*';
                matrix[i][j + 1] = '*';
                matrix[i + 1][j + 1] = '*';
                matrix[i + 1][j + 2] = '*';

            }
        }
    }

    for (i = 0; i < r; i ++){
        for (j = 0; j < s; j ++){
            if (matrix[i][j] == '*' && matrix[i + 1][j] == '.' && matrix[i + 2][j + 1] == '.' && matrix[i + 2][j + 2] == '.'){
                    matrix[i + 1][j] = '*';
                    matrix[i][j] = '.';
                    matrix[i + 1][j + 1] = '*';
                    matrix[i][j + 1] = '.';
                    matrix[i + 2][j + 1] = '*';
                    matrix[i + 1][j + 1] = '*';
                    matrix[i + 2][ j + 2] = '*';
                    matrix[i + 1][j + 2] = '.';
            }
        }
    }

    flag = check(&matrix[0][0], r, s);

    toLadders(&matrix[0][0], r, s);

    for (i = 0; i < r; i ++){
        for(j = 0; j < s; j++){
            printf("%c", matrix[i][j]);
        }
        printf("\n");
    }

    if (flag)
        printf("\nNot perfect!");
    else
        printf("\nPerfect!");

    return 0;
}

I honestly have no idea from your code what it is that it's supposed to do.  I've run it several times and am still no better off.
Naming
Naming is an important aspect of coding.  It makes your code much more approachable / self documenting.  Almost none of your names give me any kind of hint as to what they represent or do.  i,j,r,s They may mean something to you, but they don't to me.  Put them together and you get this line if (k[i * s + j] == '*').  Give your variables meaningful names.  Your method names are similarly abstract 'check', check what?  'toLadders' which seems to replace '*' with '#' for some reason.
Give your user a chance
You may write the best program in the world, but if you can't convince people to use it then it has almost no value.  Your program needs some information from the user, however they aren't told what it is.  You simply start scanning characters from stdin.  Maybe this is ok because stdin is always redirected from a file, but if not tell your users what you're expecting.  Ask them for input, then try to get it, don't just assume they're going to know what's expected of them.
Bounds Checking
Some of your bounds checking looks off to me.  You create a matrix[r][s] then do this:
for (i = 0; i < r; i ++){
    for(j = 0; j < s; j++){
        if (matrix[i][j - 1] == '.' && matrix[i][j] == '#' && matrix[i][j + 2] == '.'
            && matrix[i + 1][j] == '.' && matrix[i + 1][j + 1] == '#' && matrix[i + 1][j + 2] == '#' && matrix[i + 1][j + 3] == '.'){

It looks a lot like when j=s-1, you're going to be accessing matrix[i + 1][s - 1 + 3], which is out of bounds...

Keep in mind I wrote this in 1 hour - all the time we had for the task.

Honestly, the amount of time you had initially to write the task is a side issue, you presumably had the option to revisit the code and make it the best you could offer before posting.  Meaningful naming costs very little time and usually pays for itself with maintained understanding.  It is the biggest step you could take to make your code more approachable.  The more approachable your code is, the more value you are likely to get from reviews as reviewers will spend less time getting to grips with what you're doing allowing them to focus more on the how and why.


Function to get constants of range The following small function receives a range and returns it with only the cells that contain constants or Nothing if there's none.
Private Function GetConstants(ByVal Cells As Range) As Range
  On Error GoTo ErrHandler
  Set GetConstants = Intersect(Arg1:=Cells.SpecialCells(Type:=xlCellTypeConstants), Arg2:=Cells)
  Exit Function
ErrHandler: If Err.Number <> 1004 Then Err.Raise Number:=Err.Number, Source:=Err.Source, Description:=Err.Description, HelpFile:=Err.HelpFile, HelpContext:=Err.HelpContext
End Function

If there's no constants in the range Cells, the Range.SpecialCells method throws the error:

Run-time error '1004':
Application-defined or object-defined error

The error handler ignores it and returns the default value Nothing.
The use of the Intersect method fixes the issue that occurs when the range is only one cell. It otherwise treats it as the whole sheet.

Question:
Is there any edge case not being handled or not in the best overall way?
Did I miss something, are the names ideal, should I check If Not TypeOf Cells Is Range Then Exit Function, or maybe use another way instead of Intersect and checking Err.Number <> 1004?

I like the use of Intersect to handle single cell ranges.

You should avoid using Cells as variable name because it could easily be confused with the built in Cells collection.  By contrast Range As Range could be used because there is no default Range value.  Personally, I use Source and Target to name my ranges.  rSource and **rTarget would generally be considered better names but I think that the context in which they are used is descriptive enough.

The use of an Error Handler here is just fluff.  All it does is just throw the same error that would be thrown without it.  You should use Error Handlers to clean up the objects and reset the "Application State" when something goes wrong.

I don't see any issues with any "Edge Cases".  Raising the Error, however, does severely limit the possible "Use Cases".  The way it is written you can not test a series of ranges for constant values because it will throw an error.  IMO, it would be more useful to have the function escape the error and return Nothing.  In this way, you can create a customized Error Handler at the point of use.  For example: If not GetConstants(rngA) is Nothing Then ... If not GetConstants(rngB) is Nothing ....


Fetching environment variables — can I use pattern matching? I've got the following Elixir code:

defmodule Envvar do
    def exists?(env) do :os.getenv(env) != false end

    def get(env) do
        if exists?(env) do
            {env, :os.getenv(env)}
        else
            {env, nil}
        end
    end
end

Two things:

Am I using the ? correctly here?  I'm assuming that any predicate function should have the ? on the end of the name by convention.
Is there a way to code the get function as a pattern match rather than a if/else?  I'm asking here because I'm guessing that a pattern match would be more idiomatic Elixir code.

Using the ? for a boolean predicate is fine. At least it is what I would do in
Ruby and Elixir.

You won't be able to call exists?(env) in a guard clause so pattern matching does not win you much here.

You are calling :os.getenv() twice unneccessarily.
I'm not sure why you just want to convert 'false' to 'nil', here is a way:

defmodule Envvar do
  def get(env)
    do_get(:os.getenv(env))
  end

  defp do_get(false)
    {:env, nil}
  end

  defp do_get(result)
    {:env,result}
  end
end


Multiple producer single consumer on the same thread I implemented a multi-producer single consumer class, with an important restriction that once the consumer started working, it must continue its work on the same thread (the reasoning behind this is to allocate and free COM objects from a third party library, and these actions must be on the same thread according to that library).
Here's the code, followed by an example:
interface WorkerLogic<T>
{
    void Work(T item);
}

class ThreadedWorker<T> where T : class
{
    private readonly object locker = new object();
    private readonly Queue<T> queue = new Queue<T>();
    private readonly WorkerLogic<T> logic;
    private readonly Thread actualThread;
    private bool started = false;
    private readonly ManualResetEvent resetEvent = new ManualResetEvent(false);
    private volatile bool shouldWork = true;

    public ThreadedWorker(WorkerLogic<T> logic)
    {

        this.logic = logic;
        actualThread = new Thread(Spin);
    }

    private void Spin()
    {
        while (shouldWork)
        {
            resetEvent.WaitOne();
            while (shouldWork)
            {
                T item;
                lock (locker)
                {
                    if (queue.Count == 0)
                        break; // back to main loop and WaitOne
                    item = queue.Dequeue();
                    resetEvent.Reset();
                }
                try
                {
                    logic.Work(item);
                }
                catch (Exception ex)
                {
                    // log
                }
            }
        }
    }

    public void Stop()
    {
        Stop(TimeSpan.FromMilliseconds(500));
    }

    public void Stop(TimeSpan timeout)
    {
        shouldWork = false;
        lock (locker)
        {
            resetEvent.Set();
        }
        bool joined = actualThread.Join(timeout);
        if (!joined)
        {
            try
            {
                actualThread.Abort();
            }
            catch (ThreadStateException)
            {
                // swallow
            }
        }
    }

    public void Push(T item)
    {
        lock (locker)
        {
            queue.Enqueue(item);
            if (!started)
            {
                started = true;
                actualThread.Start();
            }
            resetEvent.Set();
        }
    }
}

Usage example for the code above:
public class UsageExample
{
    public class MyLogic : WorkerLogic<string>
    {
        public void Work(string s)
        {
            Console.WriteLine("working on '{0}', thread id = {1}", s, Thread.CurrentThread.ManagedThreadId);
        }
    }

    public static void Main()
    {
        ThreadedWorker<string> threadedWorker = new ThreadedWorker<string>(new MyLogic());
        threadedWorker.Push("My");
        threadedWorker.Push("name");
        threadedWorker.Push("is");
        threadedWorker.Push("Luca");
        threadedWorker.Stop();
    }

}

Example output:
working on 'My', thread id = 3
working on 'name', thread id = 3
working on 'is', thread id = 3
working on 'Luca', thread id = 3

I created a repl for this, feel free to play with it.
I'd like to have a peer review focused on correctness: is it thread safe? Am I missing an edge case?
Thanks!

I took rob.earwaker's advice (thanks!), and I implemented it using a BlockingCollection. The code is much simpler now :)
class ThreadedWorker<T> where T : class
{
    private readonly object locker = new object();
    BlockingCollection<T> queue = new BlockingCollection<T>(new ConcurrentQueue<T>());
    private readonly WorkerLogic<T> logic;
    private readonly Thread actualThread;
    private bool started = false;
    private volatile bool shouldWork = true;

    public ThreadedWorker(WorkerLogic<T> logic)
    {

        this.logic = logic;
        actualThread = new Thread(Spin);

    }

    private void Spin()
    {
        while (shouldWork)
        {
            T item;
            var dequeued = queue.TryTake(out item, TimeSpan.FromMilliseconds(100));
            if (!dequeued) continue;
            try
            {
                logic.Work(item);
            }
            catch (Exception ex)
            {
                // log
            }

        }
    }

    public void Stop()
    {
        Stop(TimeSpan.FromMilliseconds(500));
    }

    public void Stop(TimeSpan timeout)
    {
        shouldWork = false;
        bool joined = actualThread.Join(timeout);
        if (!joined)
        {
            try
            {
                actualThread.Abort();
            }
            catch (ThreadStateException)
            {
                // swallow
            }
        }
    }

    public void Push(T item)
    {
        if (!started)
        {
            lock (locker)
            {
                if (!started)
                {
                    started = true;
                    actualThread.Start();
                }
            }
        }
        queue.Add(item);
    }
}


Open Notify simple console application I made this code in python using Open Notify API, there is something that I could improve?
Im new to coding and I'm almost 4 hours understanding and coding this program that let you interact by some inputs and it can give you information about how many people are in space now, where is the ISS now and when it will go through a given coordinate.
import requests, json, os, datetime

clear = lambda: os.system('cls')
clear ()
def peopleInSpace():
    responseAstros = requests.get("http://api.open-notify.org/astros.json")
    astros = responseAstros.json()
    people = astros['people']

    peopleInSpa = []
    for d in people:
        peopleInSpa.append(d['name'])
    print('There are', astros['number'], 'people in space, and their names are:', (', '.join(peopleInSpa)))

def issNowF():
    responseIssNow = requests.get('http://api.open-notify.org/iss-now.json')
    issNow = responseIssNow.json()

    issNowLat = issNow['iss_position']['latitude']
    issNowLon = issNow['iss_position']['longitude']
    issNowTime = issNow['timestamp']
    print('The International Space Station is right now (', datetime.datetime.fromtimestamp(issNowTime), ' GMT -3) on these approximately coordinates:', issNowLat, issNowLon)

def issNextTime():
    clear()
    lat = input("What is the latitude?")
    lon = input('What is the longitude?')
    parameters = {"lat":lat, "lon":lon }
    responseIssNextTime = requests.get('http://api.open-notify.org/iss-pass.json', params=parameters)
    issNextTime = responseIssNextTime.json()['response']
    risetimes = []
    for d in issNextTime:
        time = d['risetime']
        risetimes.append(time)
    times = []

    print("The next 5 times ISS is going to go through the given coordinates is:")
    for rt in risetimes:
        time = datetime.datetime.fromtimestamp(rt)
        times.append(time)
        print(time)

clear()
print('Press 1 to see how many people are in space right now')
print('Press 2 for getting the coordinates of the ISS right now')
print('Press 3 for seeing when the ISS will go through certain coordinates')
r = input('')

if r == '1':
    clear()
    peopleInSpace()
elif r == '2':
    clear()
    issNowF()
elif r == '3':
    clear()
    issNextTime()
else:
    clear()
    print('Please open the program again and press only 1, 2 or 3')

Cross-platform console clear
Instead of clear = lambda: os.system('cls') try to use a more cross-platform solution:
import os

def cls():
    os.system('cls' if os.name=='nt' else 'clear')

which you can then call as:
cls()

Imports
Try writing your imports on separate lines and don't forget to remove the ones you're not using:
import datetime
import os

import requests

As you can see, I've also added an extra new line between stdlib modules and 3rd party modules. It's usually a good idea to do this as it improves readability.
Naming
In Python, the name of the variables and functions should be snake_cased. Meaning, instead of def peopleInSpace() you'd have def people_in_space() and instead of responseAstros you'd have response_astros.
Spacing & line wrapping
Try to add two new-lines (instead of one) between each function and try to end your lines somewhere between 79 - 100 chars. (I usually prefer to have more than 79 chars as specified in PEP8)
Let's see how your code looks if we take into account all the above suggestions:
import datetime
import os

import requests

def cls():
    os.system('cls' if os.name=='nt' else 'clear')

def people_in_space():
    response_astros = requests.get("http://api.open-notify.org/astros.json")
    astros = response_astros.json()
    people = astros['people']

    people_in_spa = []
    for d in people:
        people_in_spa.append(d['name'])

    print(f'There are {astros["number"]} people in space, and '
          f'their names are: {", ".join(people_in_spa)}')

def iss_now_f():
    response_iss_now = requests.get('http://api.open-notify.org/iss-now.json')
    iss_now = response_iss_now.json()

    iss_now_lat = iss_now['iss_position']['latitude']
    iss_now_lon = iss_now['iss_position']['longitude']
    iss_now_time = iss_now['timestamp']

    print(f'The International Space Station is right now '
          f'({datetime.datetime.fromtimestamp(iss_now_time)} GMT -3) '
          f'on these approximately coordinates: {iss_now_lat} {iss_now_lon}')

def iss_next_time():
    cls()

    lat = input("What is the latitude?")
    lon = input('What is the longitude?')

    parameters = {"lat":lat, "lon":lon }
    response_iss_next_time = requests.get(
        'http://api.open-notify.org/iss-pass.json', params=parameters
    )

    iss_next_time_resp = response_iss_next_time.json()['response']
    rise_times = []
    for d in iss_next_time_resp:
        time = d['risetime']
        rise_times.append(time)

    times = []

    print("The next 5 times ISS is going to go through the given "
          "coordinates is:")

    for rt in rise_times:
        time = datetime.datetime.fromtimestamp(rt)
        times.append(time)
        print(time)

cls()

print('Press 1 to see how many people are in space right now')
print('Press 2 for getting the coordinates of the ISS right now')
print('Press 3 for seeing when the ISS will go through certain coordinates')

r = input('')

if r == '1':
    cls()
    people_in_space()
elif r == '2':
    cls()
    iss_now_f()
elif r == '3':
    cls()
    iss_next_time()
else:
    cls()
    print('Please open the program again and press only 1, 2 or 3')

Looks already a bit nicer, isn't it? ^_^
Now, let's focus on improvements:
In people_in_space function, we can use list comprehensions and also wrap that request call into a try / except guard so we can catch any possible request exceptions:
def people_in_space():
    try:
        response_astros = requests.get(
            "http://api.open-notify.org/astros.json"
        )
    except requests.exceptions.RequestException as req_exception:
        # raise an exception here or do w/e you want
        # I'm just going to exit (import sys module for this to work)
        sys.exit(f'Could not fetch people in space: {str(req_exception)}')

    astros = response_astros.json()
    people_in_spa = [d['name'] for d in astros['people']]

    print(f'There are {astros["number"]} people in space, and '
          f'their names are: {", ".join(people_in_spa)}')

The above recommendations can also be applied to iss_next_time function:
def iss_next_time():
    cls()

    lat = input("What is the latitude?")
    lon = input('What is the longitude?')

    parameters = {"lat": lat, "lon": lon}

    try:
        response_iss_next_time = requests.get(
            'http://api.open-notify.org/iss-pass.json', params=parameters
        )
    except requests.exceptions.RequestException as req_exception:
        # raise an exception here or do w/e you want
        # I'm just going to exit (import sys module for this to work)
        sys.exit(f'Could not fetch next time: {str(req_exception)}')

    iss_next_time_resp = response_iss_next_time.json()['response']

    print("The next 5 times ISS is going to go through the given "
          "coordinates is:")

    for item in iss_next_time_resp:
        print(datetime.datetime.fromtimestamp(item['risetime']))

I've removed the times list since you were appending things to it but didn't use it anywhere else. And I've also saved you some space complexity by directly iterating over the iss_next_time_resp.
// LE:
Even if your solution isn't bad at all, this is how I'd do it:
import datetime
import os
import sys

import requests

def clear_screen():
    """
    Clear the console.

    Warning: on specific OSs you might need to export the
             TERM env variable.

    """

    os.system('cls' if os.name == 'nt' else 'clear')

class OpenNotify:
    """
    API client wrapper for open-notify.org.
    """

    def __init__(self):
        self.base_url = 'http://api.open-notify.org'

    def _get(self, resource, params=None):
        """
        Abstract get method for all subsequent GET requests.

        Arguments:
            resource (str): Name of the resource.
            params (dict or None): If provided, dict of GET params.

        Returns:
            <requests.Response> object or raises exception
        """

        url = f'{self.base_url}/{resource}'

        try:
            return requests.get(url, params=params) if params else requests.get(url)
        except requests.exceptions.RequestException as req_exception:
            print(f'Could not retrieve data at url {url} because: '
                  f'{str(req_exception)}')
            sys.exit()

    @staticmethod
    def _get_json_from_response(response, resource_item=None):
        """
        Decode response to json and get a specific resource
        item if provided.

        Arguments:
            response (requests.Response): The response
            resource_item (str or None): The desired resource item or None

        Returns:
            json object or raises an exception
        """

        try:
            json_data = response.json()
        except ValueError as val_error:
            print(str(val_error))
            sys.exit()

        if resource_item:
            return json_data.get(resource_item)

        return json_data

    def _get_astronauts_info(self):
        """
        Get astronauts information.

        Returns:
            json object
        """

        response =  self._get('astros.json')
        return self._get_json_from_response(response)

    def _get_iss_data(self):
        """
        Get iss data (latitude, longitude and timestamp in GMT -3).

        Returns:
            dict
        """

        response = self._get('iss-now.json')
        timestamp = self._get_json_from_response(response, 'timestamp')

        return {
            'latitude': self._get_json_from_response(response, 'iss_position')['latitude'],
            'longitude': self._get_json_from_response(response, 'iss_position')['longitude'],
            'timestamp': datetime.datetime.fromtimestamp(timestamp),
        }

    def _get_iss_next_position_time(self, latitude, longitude):
        """
        Get iss's next position time given the latitude
        and longitude.

        Arguments:
            latitude (str): The desired latitude
            longitude (str): The desired longitude

        Returns:
            json object
        """

        response = self._get(
            'iss-pass.json',
            params={'lat': latitude, 'lon': longitude}
        )
        return self._get_json_from_response(response, 'response')

    def list_astros_info(self):
        astronauts_info = self._get_astronauts_info()
        astronauts_names = ", ".join([item["name"] for item in astronauts_info["people"]])

        print(f'There are {astronauts_info["number"]} people in space, and '
              f'their names are: {astronauts_names}')

    def list_iss_info(self):
        iss_info = self._get_iss_data()
        print(f'The International Space Station is right now '
              f'{iss_info["timestamp"]} GMT-3 on these approximately '
              f'coordinates: lat {iss_info["latitude"]} long {iss_info["longitude"]}')

    def list_iss_next_position_time(self, latitude, longitude):
        iss_next_position_info = self._get_iss_next_position_time(latitude, longitude)

        print('The next 5 times ISS is going to go through the '
              'given coordinates is:')

        for item in iss_next_position_info:
            print(datetime.datetime.fromtimestamp(item['risetime']))

def main():
    print("""Choose from the options below:

    1) See how many people are in space right now.
    2) Get the coordinates of the ISS right now.
    3) See when the ISS will go through certain coordinates.

    q) Exit
    """)

    user_input = input('Please choose an option: ')

    open_notify = OpenNotify()

    if user_input == '1':
        clear_screen()
        open_notify.list_astros_info()
    elif user_input == '2':
        clear_screen()
        open_notify.list_iss_info()
    elif user_input == '3':
        clear_screen()

        latitude = input('Please enter the latitude: ')
        longitude = input('Please enter the longitude: ')

        open_notify.list_iss_next_position_time(latitude, longitude)
    else:
        print('Invalid option')
        sys.exit()

if __name__ == '__main__':
    main()

A few things to think about:

There's still room for improvements in regards to user input validation;
The retrieved API data can change and there're no sanity checks against this;
The menu can be dynamically created in order to avoid hardcoding future next options;
The OpenNotify class might be a bit redundant since we're not making changes to any specific state variables but as the API grows and you want to add other functionality to it...this might become helpful.


Python's eval command in Arduino I have made an equivalent of Python's "eval" command in Arduino (which in itself is quite a feat) but the part that decodes the output of it is not small enough to fit in another 30 functions since this will be running on an Arduino Micro.

Any suggestions on compacting it? (btw I don't care about the actual function, rather the bit in "void Loop()" since that part is gonna be repeated a lot.)

struct evals {
  int pointer;
  bool boolout;
  String stringout;
  int intout;
  float floatout;
};
String variables[50];
String LocalVariables[50];

void setup() {
  for (int Variable = 0; Variable < 50; Variable++) {
    LocalVariables[Variable] = "";
  }
  Serial.begin(9600);
  LocalVariables[0] = "TestVariable";
  variables[0] = "true";
}
void loop() {
  if (Serial.available()) {
    String read = Serial.readString();
    evals read2 = eval(read);
    switch (read2.pointer) {
      case 0:
        Serial.println("NULL");
        break;
      case 1:
        Serial.print("INT ");
        Serial.println(read2.intout);
        break;
      case 2:
        Serial.print("FLOAT ");
        Serial.println(read2.floatout);
        break;
      case 3:
        Serial.print("STRING ");
        Serial.println(read2.stringout);
        break;
      case 4:
        Serial.print("BOOL ");
        Serial.println(read2.boolout);
        break;
      case 5:
        read2 = eval(variables[read2.intout]);
        switch (read2.pointer) {
          case 0:
            Serial.println("NULL");
            break;
          case 1:
            Serial.print("INT ");
            Serial.println(read2.intout);
            break;
          case 2:
            Serial.print("FLOAT ");
            Serial.println(read2.floatout);
            break;
          case 3:
            Serial.print("STRING ");
            Serial.println(read2.stringout);
            break;
          case 4:
            Serial.print("BOOL ");
            Serial.println(read2.boolout);
            break;
        }
    }
  }
}
struct evals eval(String input) {
  evals output;
  input.replace("\n", "");
  input.replace("\r", "");
  char input2[input.length() + 1];
  input.toCharArray(input2, input.length() + 1);
  if (input.length() == 0) {
    output.pointer = 0;
    return output;
  }
  if (input2[0] == '"' and input2[strlen(input2) - 1] == '"') {
    input.remove(0, 1);
    input.remove(strlen(input2) - 2, 1);
    output.pointer = 3;
    output.stringout = input;
    return output;
  } else if (input == "true") {
    output.pointer = 4;
    output.boolout = true;
    return output;
  } else if (input == "false") {
    output.pointer = 4;
    output.boolout = false;
    return output;
  } else {
    String inputs = input;
    inputs.replace("0", "");
    inputs.replace("1", "");
    inputs.replace("2", "");
    inputs.replace("3", "");
    inputs.replace("4", "");
    inputs.replace("5", "");
    inputs.replace("6", "");
    inputs.replace("7", "");
    inputs.replace("8", "");
    inputs.replace("9", "");
    if (inputs.length() == 0) {
      output.pointer = 1;
      output.intout = input.toInt();
      return output;
    } else {
      if (inputs[0] == '.' and inputs.length() == 1) {
        output.pointer = 2;
        output.floatout = input.toFloat();
        return output;
      } else {
        for (int Variable = 0; Variable < 50; Variable++) {
          if (LocalVariables[Variable] == "") {
            continue;
          } else if (LocalVariables[Variable] == input) {
            output.pointer = 5;
            output.intout = Variable;
            return output;
          }
        }
        output.pointer = 0;
        return output;
      }
    }
  }
}

I'll focus on the void loop() part as you ask it, even though it can't be reviewed in isolation, especially from the evals structure.

So, what is this loop all about? You want to select the correct behavior based on the way the evaluated data has been tagged. Which mean we have three levers to act upon: the selection mechanism, the tagging mechanism, and the way the data is represented. I believe you can do better with all three:

tagging your data with a char* is a bad idea. The first important thing to note is that comparing a char* with a string literal is undefined behavior. It works with most compilers, but if you enable all warnings, as you should do, you'll see it isn't guaranteed by the standard. It means that you should rely on proper string comparisons instead, character by character -e.g with strcmp- which are of course slow, if you really want to keep the string-tagging. But you don't: there are faster, simpler and more robust mechanisms such as enums.

For instance:

enum class Type : char { NULL, INTEGER, FLOATING_PRECISION, STRING, BOOL };

Representing your data with a struct containing as many members as there are possible types is a waste of space you should care about. You can use unions to make it more compact.
Selecting the correct behavior can be made in several ways, the one you chose among them. But, not wandering very far, you could have used a switch, which is arguably easier to read and can be optimized by the compiler: the program will go through the if else clauses in succession, whereas a switch can be turned into a jump-table with logarithmic look-up. If you want to explore further, and have a more scalable selection mechanism, you could have a try at a virtual function.


Designing a service/business logic layer that returns useful/consistent messages This is a question regarding design of a service or business logic layer that returns or exposes messages meaningful to the user.

RegisterUser method that takes a user.  What should it return? Should it always return

a Service Information object?
a newly created user?
a boolean, and based on the result, you can interrogate this service's error messages?

public bool RegisterUser(User user)
{
    if (String.IsNullOrEmpty(user.EmailAddress) || !user.EmailAddress.IsValidEmailAddress())
    {
        AddMessage(new Message
        {
            Description = "Invalid Email Address",
            Success = false
        });
    }
    if (String.IsNullOrEmpty(user.Password))
    {
        AddMessage(new Message
        {
            Description = "Password is Required",
            Success = false
        });
    }
    return Messages.Count == 0;
}

The problem with returning a message like this is that you are "hard coding" the messages in the registration method.  If you want to add localization (i.e. return a message in the users language as determined by the culture setting of the client) to the application later it will be much harder.  A cleaner approach would be to use custom exceptions and exception handling.  For example, if the an invalid email address is entered then a InvalidEmailException would be thrown by the RegisterUser method.  The part of the application that calls the RegisterUser method would determine what to present to the user for this type of exception or to percolate it up higher in the application for handling.  This is a cleaner separation of concerns of handling exceptions in the application from what is presented to the user.  This also promotes reuse because different users of the method may want to handle it differently.


C# overload method simplification I have the following routine that I would like to simplify:

public void SetUniform(RenderContext ctx, string uName, object value)
{
    if (ctx == null)
        throw new ArgumentNullException("ctx");
    if (value == null)
        throw new ArgumentNullException("value");

    if (value is int)
        SetUniform(ctx, uName, (int)value);
    else if (value is Vertex2f)
        SetUniform(ctx, uName, (Vertex2f)value);
    else if (value is Vertex3f)
        SetUniform(ctx, uName, (Vertex3f)value);
    else if (value is Vertex4f)
        SetUniform(ctx, uName, (Vertex4f)value);
    else if (value is Matrix4x4)
        SetUniform(ctx, uName, (Matrix4x4)value);
    else
        throw new NotSupportedException(value.GetType() + " is not supporteds");
}

As you can read, the above routine is essentially the generic version of all SetUniform. I need this routine becuase I don't know the value type at compile time, but in this way I need to check its type at runtime each time I need it.

How can I reduce this routine is a more simple and performant-wise way?

Due the comments, I need to clarify some question that seems not enought clear.

The "Uniform" state belongs to a specific class ShaderProgram, not to a wide set of classes (the ones listed on the snippet above are only a subset). Each SetUniform implementation access to the internal state of ShaderProgram, which I would not like expose, even using an internal modifier.
The SetUniform overload with object parameter is required because I get the value  using reflection, indeed I have no idea at compile time what is the value type. Indeed I have defined an additional overload which recall specific implementation.
Each SetUniform overload have a different implementation. Specifically, they call the one of the routines specified here.

You can overload your SetUniform method with the different types of value:

public void SetUniform(int value)
{

}
public void SetUniform(Vertex2f value)
{

}
public void SetUniform(Vertex3f value)
{

}
...

You could also try using the Null Object Pattern to avoid the null checks or define some default behaviour.