Storing option value I currently have a design that is used to store user/selected options in a database, but I am not sure what I am doing is good or not. I need some opinion, suggestion and criticise on the design.

Pre-Condition:

The option is not always going to change
A lot of options is going to be used

Database Design:

Let's say I have a column named "country" in my user table and I store this data as an integer instead of a string (the country name). Then I use mapping to map the value to the country name in the code when I want to use it.

The reason I am doing this is because I am thinking that storing the value as an integer and retrieving the value from the integer is faster compared to a string. Furthermore, it is more or less on storage consumption.

The above is just an example; I wouldn't do this if I only need to store the user's country. I'm actually got plenty of tables that are required to store the user's option. Some of the options contain long strings such as 20 - 50 chars.

Code Mapping Design:

I created 2 Enum class: one is the base class and the other is the particular option class and I will implement the base class that help me to do the mapping.

Base Class:

abstract class BaseEnum {

    private static $constCacheArray = NULL;

    private static function getConstants() {
        if (self::$constCacheArray == NULL) {
            self::$constCacheArray = array();
        }
        $calledClass = get_called_class();
        if (!array_key_exists($calledClass, self::$constCacheArray)) {
            $reflect = new ReflectionClass($calledClass);
            self::$constCacheArray[$calledClass] = $reflect->getConstants();
        }
        return self::$constCacheArray[$calledClass];
    }

    public static function getAllOptions() {
        $options = array();
        foreach (self::getConstants() as $key => $value) {
            $options[substr($key, 1)] = $value;
        }
        return $options;
    }

    public static function getValue($key) {
        $key = '_' . $key;
        if(isset(self::getConstants()[$key])) {
            return self::getConstants()[$key];
        }
        return FALSE;
    }

    public static function isKeyExist($key) {
        $key = '_' . $key;
        if(isset(self::getConstants()[$key])) {
            return TRUE;
        }
        return FALSE;
    }

}

Country Class:

class Country extends BaseEnum {
    const _1 = 'Afghanistan';
    const _2 = 'Albania';
    const _3 = 'Bangladesh';
    const _4 = 'Brazil';
    const _5 = 'Denmark';
    const _6 = 'United Kingdom';
    ...

}

When the time I want to use to display the option into HTML, I do this:

<?php
    ...
    $options = Country::getAllOptions();
    foreach($options as $key => $value) {
        echo '<option value="'.$key.'">'.$value.'</option>'
    }
    ...
?>

When I want to display user-selected value, I do this:

 <?php
        ...
        $user = new User();
        $options = Country::getAllOptions();
        foreach($options as $key => $value) {
            if($user->getCountry() == $key) {
                echo '<option value="'.$key.'" selected="selected">'.$value.'</option>';
            } else {
                echo '<option value="'.$key.'">'.$value.'</option>';
            }

        }
        ...
    ?>

Is there any wrong with this design? Or is it better to maintain all these options in the DB? Or is there other any other better ways to do this?

This looks pretty good IMO. If you are considering taking these values to the database, make sure you create a separate table for each category. Do not use enum type columns.

However there are few minor things I noticed that you can refactor.

Initialize $constCacheArray as an array so you can avoid the first 3 lines in getConstants()
isKeyExist method can be a single line

public static function isKeyExist($key) {
    return (isset(self::getConstants()['_' . $key]);
}

getValue method has similar logic too but for readability's sake you can keep it as it is.
Avoid method calls inside loops. Take $user->getCountry() out of the foreach and assign it to variable which you will use for comparison.
Also to remove the _s from the keys you can use a regex. If you plan to use string keys for enums (eg: const disabled = 'Disabled';), this will come in handy.

json_decode(preg_replace('/"_([0-9]*)":/i', '"$1":', json_encode($arr)), true)


Add 'ing' or 'ly' suffix to a string I have been practising Python Practice questions and came across this question:

Write a Python program to add 'ing' at the end of a given string
(length should be at least 3).
If the given string already ends with 'ing' then add 'ly' instead.
If the string length of the given string is less than 3, leave it
unchanged.   Sample String : 'abc'
Expected Result : 'abcing'
Sample String : 'string'
Expected Result : 'stringly'

Here's my code:
string = input()
if len(string) < 3:
  print(string)
elif string[-3:] == 'ing':
  print(string + 'ly')
else:
  print(string + 'ing')

However, something about this code seems wrong: though it works, fine I feel it smells bad. I can't pinpoint why.

1. Python strings have an .endswith() method. Use it.
While string[-3:] == 'ing' isn't particular hard to read, string.endswith('ing') is even clearer.
Potentially, depending on how it's implemented, .endswith() could even be slightly more efficient, since it doesn't have to copy the last three characters of the string.  However, always keep Knuth's maxim in mind.  The entire operation of testing whether a string ends with "ing" is so trivial that any performance difference between different ways of doing it will surely be negligible compared to e.g. the time consumed by reading and printing the string.  Thus, given two ways to do it, you should choose the most readable and idiomatic way even if it wasn't the most efficient.
2. Separate I/O from computation.
It's common for beginning programmers to litter their code with input() and print() calls in the middle of program logic, simply because those are the only ways of receiving and returning data they're familiar with.  But in practice, that's almost always a mistake.(*)
Your main task is to modify a string.  Reading the string from standard input and printing the result to standard output are merely auxiliary tasks to that (and may or may not even be strictly necessary, unless the exercise explicitly specifies that particular method of input and output).  You shouldn't unnecessarily intermix those auxiliary tasks into your solution for the main task.
The simplest way to do that would be to just pull the print() calls out of the program logic, e.g. like this:
string = input()

if string.endswith('ing'):
  string += 'ly'
elif len(string) >= 3:
  string += 'ing'

print(string)

This is OK if you expect to only ever use this code for processing data read from one file (or pipe) and written to another.  You're still doing the input, processing and output in one linear program, but at least the processing logic is now grouped together in a single block of code that you can extract from the script if you want to reuse it, and the I/O code is clearly separated from it, making it easy to change to another I/O method later if you need to.
Alternatively, you could go a step further and wrap the program logic in a function that takes the input string as a parameter and returns the output.  And, while you're at it, you can use the if __name__ == '__main__' idiom to make your I/O code only run when your script is invoked directly:
def inglify(string):
  if len(string) < 3:
    return string
  elif string.endswith('ing'):
    return string + 'ly'
  else:
    return string + 'ing'

if __name__ == '__main__':
  string = input()
  print(inglify(string))

The advantage is that now your script file is also usable as a module that you can import into another script to gain access to any functions defined in it without executing the I/O part of the code.

*) So, when is it appropriate to include print() calls directly in your code, then?  Off the top of my head, I can think of three or four cases (with some partial overlap between them):

When I/O is the main purpose of your code, with everything not directly relevant to this purpose already split off into reusable functions.  For example, print(inglify(input())) really does nothing but read data, call a function and print the result.  Obviously, using print() there is not only appropriate but necessary.

When your code is interactive, i.e. when it prints something to the console, expects the user to reply, then prints something in response, etc.  The REPL that you can start by running python with no script file argument is one example of such a program.  In this case the input and output are intrinsically part of your program logic and cannot be easily separated from it.  That said, you should still try to keep such interactive loops as simple as possible, and split off any parts of your code that don't directly involve interactive I/O into reusable functions or modules.

When you're doing debug printing, i.e. when what you're printing isn't the actual intended output of your program, but merely some metadata to help in tracing its execution.  This can sometimes be a very useful ways to find out what your code is actually doing, and it's the one case where putting print() or other I/O calls even deep inside your program logic can be acceptable.  Of course, if you're leaving such debug logging in your finished code, you should probably only enable it if requested by the user.  (For example, many command-line tools will accept a --verbose or --debug switch to turn on such extra output.)  Often it's best to use an actual logging framework designed for this purpose.

I would also personally include an exception for "simple data processing" scripts that involve nothing more than reading in some data, processing it and printing it out, much like the first rewritten version of your code that I suggested above.
Such scripts are characterized by the fact that they only perform a single task, that this task involves reading, processing and writing data, and that their control flow is simple and mostly linear.  That is, such a script might consist of a loop that reads the input, another loop or two to process it, and then a loop to print out the results.  Sometimes it might even have a loop that e.g. reads a line of input, processes it, and prints out the result before reading the next line, etc.  But what it definitely shouldn't have is print (or, worse yet, input) calls buried deep within conditional code, or in functions whose main purpose isn't obviously to perform I/O.
While such scripts can be refactored to separate the I/O code from the rest of the data processing, often that can actually make the code harder to read, since it breaks up the simple step-by-step program flow into a more complex sequence of function calls.  Basically, if your code is naturally structured like a cooking recipe, with nothing but simple sequential steps, it's sometimes better to just keep it like that and not complicate it by needless refactoring.


Retrieve min from stack in O(1) I wrote some Python code to solve the following problem.  I'm curious to see if someone else can find a better solution, or critique my solution.

How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element?  Push, pop and min should all operate in O(1) time.

class SmartStack:
    def __init__(self):
        self.stack= []
        self.min = []

    def stack_push(self,x):
        self.stack.append(x)
        if len(self.min) != 0:
            if x < self.stack_min():
                self.min.append(x)
        else:
            self.min.append(x)

    def stack_pop(self):
        x = self.stack.pop()
        if x == self.stack_min():
            self.min.pop()
        return x

    def stack_min(self):
        return self.min[-1]

def main():
    print "Push elements to the stack"
    list = range(10)
    stack = SmartStack()
    for i in list:
        stack.stack_push(i)
    print "Print stack and stack minimum"
    print stack.stack
    print stack.stack_min()
    print "Push -1 to stack, print stack and stack minimum"
    stack.stack_push(-1)
    print stack.stack
    print stack.stack_min()
    print "Pop from stack, print stack and stack minimum"
    print stack.stack_pop()
    print stack.stack
    print stack.stack_min()

if __name__ == "__main__":
    main()

Your implementation fails if there are duplicates values in the stack:

def main():
    stack = SmartStack()
    stack.stack_push(1)
    stack.stack_push(1)
    stack.stack_push(3)
    stack.stack_pop()
    stack.stack_pop()
    print(stack.stack_min())

$ ./smartstack
Traceback (most recent call last):
  File "./smartstack", line 35, in <module>
    main()
  File "./smartstack", line 32, in main
    print(stack.stack_min())
  File "./smartstack", line 23, in stack_min
    return self.min[-1]
IndexError: list index out of range

Suggested fix:

def stack_push(self,x):
    self.stack.append(x)
    if not self.min or x <= self.stack_min():
        self.min.append(x)

The naming is redundant: methods of the SmartStack class shouldn't need to have "stack_" in their names.

If you are targeting Python 2, be sure to use new-style classes (i.e., SmartStack should have object as a superclass).


C++ Pi Calculator - Leibniz Formula Yesterday I saw a CodeTrain video in where Daniel Shiffman tried to approximate Pi using the Leibniz series. It was interesting so I decided to try it too.

I wrote this console application with a simple goal: Approximate as fast as possible as many digits of Pi the program can until it reaches the maximum number the cycle counter can achieve(without starting to commit calculation errors with the series formula) OR the program is stopped.

It starts by first running two background threads which execute two functions that do all the job: piLoop(), for calculating the series; and displayLoop(), for refreshing the screen and displaying the actual calculated Pi. To prevent concurrency problems, mutexes are used to prevent the threads from accessing Pi and other program shared variables at the same time. The program runs until piCycles reaches the maximum value a long long int can get OR the End key is pressed.

The final program runs, by glancing at it (that means a very unreliable measurement), at an approximated rate of 30 million cycles per second in my computer. That means it can calculate the 10th digit of PI (around 87 billion cycles) in about an hour.

I want to know if there are some optimizations that can be made so the program can run at all his power.

main.cpp

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <windows.h>
#include <limits>

void piLoop();
void displayLoop();
void getShouldStop();

namespace {
    typedef std::numeric_limits<long double> ldbl;
    typedef std::numeric_limits<long long int> ullint;

    const char displayDigits = ldbl::max_digits10;
    const short int updateDelay_ms = 50; // You can modify this value to change the speed of console refreshing.
    const long long int maxCicles = ullint::max();

    bool shouldStop = false;
    long double PI = 0;
    unsigned long long int piCicles = 0;
    std::mutex piLock;
}

int main()
{
    std::thread piCalculatorThread( piLoop );
    std::thread displayUpdaterThread( displayLoop );
    piCalculatorThread.join();
    displayUpdaterThread.join();

    std::cin.get();

    return 0;
}

void getShouldStop() {
    shouldStop = GetAsyncKeyState( VK_END ) || shouldStop;
}

// If PI mutex is not locked, proceed to calculate the next PI, else wait
void piLoop() {
    while ( true ) {
        piLock.lock();

        if ( shouldStop ) {
            piLock.unlock();
            return;
        }

        // Here the series is calculated
        PI += ((long double)((piCicles&1)>0 ? -1 : 1)) / (piCicles*2 + 1);

        if ( piCicles == maxCicles ) {
            shouldStop = true;
            piLock.unlock();
            return;
        }

        piCicles++;

        piLock.unlock();
    }
}

// Wait until PI mutex is unlocked, then refresh the screen.
void displayLoop() {
    std::cout.precision( displayDigits );
    while ( true ) {
        piLock.lock();

        system("cls");
        std::cout << "\n\n  ----- PI Calculator ----- \n\n  - \"Seeing how PI is calculated is more enjoyable while eating some snacks.\"";
        std::cout << "\n\n\n    PI:      " << PI * 4;
        std::cout << "\n    Cicles:  " << piCicles << std::endl;
        if ( maxCicles == piCicles ) //  Just in case someone has the time to run this program for long enough
            std::cout << "\n    Max precise 64-bit computable value reached!" << std::endl;

        if ( !shouldStop ) getShouldStop();

        piLock.unlock();

        if ( shouldStop ) return;

        std::this_thread::sleep_for( std::chrono::milliseconds( updateDelay_ms ) );
    }
}

I think this code can also be run on other operating systems by removing the windows.h header and the getShouldStop() function as well, so Linux users may also give it a try.

Here is a link to download the Windows executable if you want to test it.

Threading structure
I rather dislike the overall structure of the code. Rather than having two threads contending over a single location where the current estimate of \$\pi\$ is stored, I'd rather have the calculator thread compute successive approximations, and write them to a queue. The display thread would then wait on value to show up in the queue, display it, and repeat. The locking and such should be in the queue itself.
You've also created not just one, but two secondary threads. There's no real point in this. You started with the process' primary thread, then all it does is create two other threads, then wait for them to finish. It might as well do something useful, and only create one other thread.
Formula
It seems to me that if you're going to try to make it faster, you could at least do a minor improvement to the formula. One that's quite a bit faster, and still utterly trivial (in fact, arguably simpler than the plain Leibniz formula) is:
\$ {\pi \over 4} = {\sum_{n=0}^{\infty} {2 \over (4n+1)(4n+3)}}\$
Summation
This does have one interesting twist: if you just use a naive summation over this formula, you'll find that it "gets stuck"--with a typical double, no matter how many iterations you do, it will only ever get about 8 digits correct.
The problem is that you have a number of relatively large magnitude, and you're trying to add numbers of relatively small magnitude to it. Each of them individually is too small to affect the larger number, so it remains constant.
In this case, there's a pretty simple cure: start from the smallest numbers, and work your way toward larger numbers. That way, the sum you have and the amount you're adding to it each time have closer to the same magnitude, so more terms continue to improve the overall result.
For this particular program, that has a bit of a problem though: since we're trying to display the approximation as it gets better over time, we want approximations that actually do get better over time--and if we start from the smallest, and sum toward the largest, our approximation is truly terrible for almost the entire time, then at the very end, the last few iterations suddenly make it a lot better in a hurry.
As a compromise, we can take a middle ground: work from beginning to end, but work in "chunks" of (say) 10'000'000 terms, so we have an overall estimate, and we have a temporary sum of only the most recent terms. At the beginning of each iteration of the inner loop, we start over from a value of 0.0, so we don't have a drastically larger term dominating when we do the addition. Then when we've added those terms together, we add the result to the overall estimate.
This also works nicely with updating the display--each time we add an intermediate value to our overall estimate, we can send the result out to be displayed.
Portability
I've left out the asynchronous keyboard reading, so the code can be portable. I'd rather use an even better formula than just let one that converges extremely slowly run for weeks on end (and then add non-portable code to let them quit more easily when they get bored).
Code
So, doing things this way, we could end up with code on this general order:
#include <iostream>
#include <iomanip>
#include <deque>
#include <mutex>
#include <thread>
#include <condition_variable>

namespace concurrent {
    template<class T>
    class queue {
        std::deque<T> storage;
        std::mutex m;
        std::condition_variable cv;
    public:
        void push(T const &t) {
            std::unique_lock<std::mutex> L(m);
            storage.push_back(t);
            cv.notify_one();
        }

        // This is not exception safe--if copying T may throw,
        // this can/will lose data.
        T pop() {
            std::unique_lock<std::mutex> L(m);
            cv.wait(L, [&] { return !storage.empty(); });
            auto t = storage.front();
            storage.pop_front();
            return t;
        }
    };
}

int main() {
    concurrent::queue<double> values;

    auto t = std::thread([&] {
        double pi4 = 0.0;
        for (double n = 0.0; n < 8'000'000'000.0; n += 10'000'000) {
            double temp = 0.0;
            for (double i = 0; i < 10'000'000; i++)
                temp += 2.0 / ((4.0 * (n + i) + 1.0) * (4.0 * (n + i) + 3.0));
            pi4 += temp;
            values.push(4.0 * pi4);
        }
        values.push(-1.0);
    });

    double pi;
    while ((pi=values.pop())> 0.0)
        std::cout << "\r" << std::setw(11) << std::setprecision(11) << std::fixed << pi;
    t.join();
}

On my machine, this calculates Pi to 10 places in about 45 seconds. Unless your computer is quite old/slow (like mine is) it'll probably run faster than that for you.
On the other hand, for watching the value converge, this does have kind of the opposite problem: it finds around six or seven digits nearly instantly, then grinds for a long time to a few more. Visually, some might find the Leibniz formula more appealing for the fact that it goes first above, then below, then back above, below again, and so on as it approaches the true value of Pi (though that's more apparent if you draw a graph rather than just printing out the values).


Doubly linked list with different dependencies I need to connect different Task with a double linked list and different Dependencies which affect a calculation for which I need the values of both Task:

public class Task {
    private List<Dependency> parents = new ArrayList<Dependency>();
    private List<Dependency> children = new ArrayList<Dependency>();

    //Uses the parents values and calls `calculateForwards` of the children
    public void calculateForwards() { .. }
    //Uses the children values and calls `calculateBackwards` of the children
    public void calculateBackwards() { .. }
}

public interface Dependency {
    Task getTask();
    void setForwards(Task t);
    void setBackwards(Task t);
    Dependency createCopy(Task t);
}

public class EA implements Dependency {
    private Task task;

    //............

    @Override
    public void setForwards(Task t) {
        if (t.getEarlyStart() < task.getEarlyFinish())
        t.setEarlyStart(task.getEarlyFinish());

        t.setEarlyFinish(t.getEarlyStart() + t.getDuration());
    }

    @Override
    public void setBackwards(Task t) {
        if (t.getLatestFinish() > task.getLatestStart())
        t.setLatestFinish(task.getLatestStart());

        t.setLatestStart(t.getLatestFinish() - t.getDuration());
    }

    //............

 }

For now dependencies are created with the Task it points to and added to the children list. Then a copy of the dependency is created that points to the original task and added to the parent list of the child:

public void addChild(Dependency r) {
    children.add(r);
    r.getTask().addParent(r.createCopy(this));
}

private void addParent(Dependency r) {
    parents.add(r);
}

As you can see this data structure does the job, but very ugly in my eyes. How can I solve this more elegantly?

Task.java,
Dependency.java,
EA.java (implements Dependency)

Task depends on Dependency (not very troubling in itself) :

public class Task {
    private List<Dependency> parents = new ArrayList<Dependency>();

Also Dependency depends on concrete class Task (somewhat more troubling):

public interface Dependency {
    Task getTask();

Although dependency cycles of size 2 are not intrinsically a problem, in this case interface Dependency is pretty much useless, [if we look at the implementation, which is a hybrid holder and wrapper for Task]. Too generic a name and getters and setters on the interface are also signs that this interface does not pull its weight.

If the problem model is a graph it is expected that class that represents the node of that graph should be depend on itself. Dependency cycles of 1 is generally better than 2.

My Suggestion

The only methods that contain logic in the implementation of Dependency is setBackwards and setForwards. But when we read them we see that they manipulate the insides of Task, and therefore should be moved into that class. After the said move you can remove Dependency and EA, and directly use Task instead.


Which is the best approach for searching the dictionary items? We can search for the list of dictionaries using the below some approaches, Can one please help me, which one is the memory efficient approach to use?

Provided that:

names are unique in the list
There will be definitely a name in each dictionary.

Where as:

items = [list_of_dicts]
name_to_b_searched = "some_name"

1 direct return from the for loop

def get_by_name(self, name_to_be_searched):
    for i in items:
        if i['name'] == name_to_be_searched:
              return i

2 Break from the for loop and return found dictionary

def get_by_name(self, name_to_be_searched):
    found = None
    for i in items:
        if i['name'] == name_to_be_searched:
              found = i
              break
    return found

3 A generator function

def get_by_name(self, name_to_be_searched):
    for i in items:
        if i['name'] == name_to_be_searched:
              yield i

4 An inline generator

get_by_name =next(i for i in items if i['name'] == name_to_be_searched, None)

Sometimes I could have a huge csv records (in items), so was thinking which approach would be better to search a record.
OR if there is any other approach you would recommend please let me know.

None of the above.

  OR if there is any other approach you would recommend please let me
  know.

The whole point of using dictionaries is that you don't need to search anything and can access everything in O(1) (on average) instead of the O(n) in all of your suggestions.

  names are unique in the list
  There will be definitely a name in each dictionary.

So, instead of using a list of dictionaries, use a dictionary of dictionaries using the name as the outer key.

Instead of

items = [{'name': 'a', 'age': 22, ...},
         {'name': 'b', 'age': 30, ...}]

you should have

items = {'a': {'age': 22, ...},
         'b': {'age': 30, ...}}

Now you can access each dictionary directly by using the name.

name = 'b'
print(items[name]['age'])
#  30

No loops, no searches, O(1) access.


Text revelation effect I would be glad if someone could take a look at my code and maybe improve it. It's an animation effect to gradually reveal text as if it were being decoded. I wouldn't mind if it could run with jQuery (if it's shorter or better). I uploaded it on jsbin.com. It's all about the effect and not about encryption or decryption.

I've written the following JS Code:

var got,
    chars,
    decrypted = document.getElementById("decoded"),
    encrypted = document.getElementById("encoded");
function change() {
    var randstring = "",
        rslength = chars.length - got.length,
        i;
    for (var x=0;x<rslength;x++) {
        i = Math.floor(Math.random() * chars.length);
        randstring += chars[i];
    }
    if (randstring[0] === chars[got.length]) {
        got += randstring[0];
        decrypted.textContent = got;
    } else {
        encrypted.textContent = randstring;
    }
    if (chars.length > got.length) {
        setTimeout(change, 10);
    } else {
        encrypted.textContent = "";
    }
}
function startdecrypt() {
    chars = decrypted.textContent;
    decrypted.textContent = "";
    got = "";
    setTimeout(change, 10);
}
if (window.addEventListener) {
    window.addEventListener('load', startdecrypt, false); //W3C
} else {
    window.attachEvent('onload', startdecrypt); //IE
}

And this short HTML part:

Enjoy this effect!

var decrypted = document.getElementById("decoded");
var encrypted = document.getElementById("encoded");

function startdecrypt() {
    // Original text, split into an array and reversed (for faster pop())
    var originalText = decrypted.textContent.split('').reverse();
    var decryptedText = "";
    var i = 0;

    decrypted.textContent = "";

    var shuffleInterval = setInterval(function(){

      // Generate random strings. You can modify the generator function range
      // (Math.random()*(to-from+1)+from);
      var shuffledText = '';
      var j = originalText.length;
      while(j--) shuffledText += String.fromCharCode((Math.random()*94+33) | 0);
      // You can also use this generator to use only the remaining letters
      // while(j--) shuffledText += originalText[(Math.random()*j) | 0];

      // On every 10 cycles, remove a character from the original text to the decoded text
      if(i++ % 10 === 0) decryptedText += originalText.pop();

      // Display
      decrypted.textContent = decryptedText;
      encrypted.textContent = shuffledText;

      // Stop when done
      if(!shuffledText.length) clearInterval(shuffleInterval);

    // 50ms looks more dramatic
    },50);
}

if (window.addEventListener) {
    window.addEventListener('load', startdecrypt, false); //W3C
} else {
    window.attachEvent('onload', startdecrypt); //IE
}

Changes

Everything in one function
Simplified the code
Using setInterval rather than setTimeout. This is more efficient since you don't create timers everytime
More drama by adding random string generator, instead of just your original set of letters. This adds more mystery to the next letters.
In addition to the code, a monospace font would be more dramatic. It avoids the to-fro movement of the decoding text.


Recursive directory tree printer I wrote this program that recursively prints all the files and directories starting at the current directory:

import Data.Tree (Tree (..))
import System.Directory (doesDirectoryExist, getCurrentDirectory, getDirectoryContents)

main :: IO ()
main = do
  currentDirectory <- getCurrentDirectory
  tree <- tree currentDirectory "."
  printTree 0 tree

printTree :: Int -> Tree FilePath -> IO ()
printTree indent tree = do
  putStrLn $ (replicate indent ' ' ++ rootLabel tree)
  mapM_ (printTree $ indent + 2) (subForest tree)

treeHelper :: FilePath -> IO [Tree FilePath]
treeHelper path =
  let filter' = filter (`notElem` [".", ".."]) in
  do
    contents <- getDirectoryContents path
    trees <- mapM (tree path) (filter' contents)
    return trees

tree :: FilePath -> FilePath -> IO (Tree FilePath)
tree parent path =
  let fullPath = (parent ++ "/" ++ path) in
  do
    isDirectory <- doesDirectoryExist fullPath
    case isDirectory of
      False -> return $ Node path []
      True -> treeHelper fullPath >>= (return . Node (path ++ "/"))

If you run it, it might print something like this:

./
  dist/
    build/
      autogen/
        cabal_macros.h
        Paths_Tree.hs
      tree/
        tree
        tree-tmp/
          Main.hi
          Main.o
    package.conf.inplace
    setup-config
  Setup.lhs
  tree.cabal
  Tree.hs

I think this is pretty nifty. It's a toy program, so I purposefully left out stuff like error checking and symlink handling and etc. How would you improve this program? Am I duplicating functionality available in a library? Are there places where the code could be tighter? Is my Haskell style not up to snuff?

You can also use unfoldTree (or unfoldTreeM here) to build Data.Tree:

import Control.Monad
import System.Directory
import System.FilePath
import Data.Tree

dirTree :: FilePath -> IO (Tree FilePath)
dirTree root = unfoldTreeM step (root,root)
    where step (f,c) = do
            fs <- getDirectoryContents f
            ds <- filterM doesDirectoryExist fs
            return (c, [(f </> d, d) | d <- ds, d /= "." && d /= ".."])

main :: IO ()
main = do
  t <- dirTree "."
  putStrLn $ drawTree t

Update: As Björn Lindqvist correctly noted in his edit suggestion, my use of doesDirectoryExist doesn't work here (it uses directory names instead of directory paths).

The correct version of dirTree would be:

dirTree :: FilePath -> IO (Tree FilePath)
dirTree root = unfoldTreeM step (root,root)
    where step (p, c) = do
            isDirectory <- doesDirectoryExist p
            fs <- if isDirectory then getDirectoryContents p else return []
            return (c, [(p </> f, f) | f <- fs, f `notElem` [".", ".."]])


Calling a function on an object if not null Here is code for check null in object:

public static TResult IfNotNull<TInput, TResult>(this TInput obj, Func<TInput,TResult> expression)
    {
        if (obj == null || expression == null) return default(TResult);
        var value = expression(obj);
        return value;
    }

The above code is best pratice of check nullability in object.  I'm working on c# V4.0.

Example usage :

Person.IfNotNull(x => x.User).IfNotNull(x => x.Name) ?? "";

To be sure it always works you should add a constraint to the method:

where TInput : class

This will ensure that TInput is a reference type.

It makes no sense to call it on structs. For them, you need another overload with a different constraint and some ? question marks:

public static TResult IfNotNull<TInput, TResult>(
     this TInput? obj,
     Func<TInput, TResult> expression
) where TInput : struct
{
    if (!obj.HasValue) return default(TResult);
    var value = expression(obj.Value);
    return value;
}

Someone may ask at this point: but why do we need two extensions if theoretically a single one does the job too?

Consider this:

((decimal?)2).IsNotNull(x => x.Value * 2)

With a single extension you need to use the .Value property for nullable types. With two extensions you get a clean value so you just do

((decimal?)2).IsNotNull(x => x * 2)

But isn't this just a convenience? Of course it is. Don't we write extensions  exactly for that reason?

As a matter of fact I use a similar code myself:

public static TResult IIf<TArg, TResult>
(
    this TArg arg,
    Func<TArg, bool> predicate,
    Func<TArg, TResult> ifTrue,
    Func<TArg, TResult> ifFalse = null
)
{
    if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); }
    if (ifTrue == null) { throw new ArgumentNullException(nameof(ifTrue)); }

    return predicate(arg) ? ifTrue(arg) : (ifFalse == null ? default(TResult) : ifFalse(arg));
}

but you can create a simplified version of your method and combine it with the IIf

public static bool IsNotNull<TInput>(this TInput obj) where TInput : class
{
    return obj != null;
}

to do this

Person
    .IIf(p => p.IsNotNull(), p => p.User)
    .IIf(u => u.IsNotNull(), u => u.Name, u string.Empty);


Rails 5 helpers to fetch tasks with different filters I moved a lot of the loading/logic from my view to my controller, and it's working great but after I did this I now have several very similar helper methods in my controller.

What is a more efficient way of doing this? Is there? I assume get_last_task_owed and get_first_task_owed I would be able to do in the view by finding the .first and .last of the record respectively.

  def get_projects_owed
    current_user.projects.where('end_date > ?', Date.today).order(:start_date).pluck(:name, :start_date, :end_date)

  end

  def get_all_projects
    current_user.projects.order(:start_date).pluck(:name, :start_date, :end_date)
  end

  def get_all_tasks
    @project.tasks.order(:product, :task_start_date).pluck(:product, :task_name, :task_start_date, :task_end_date).to_json
  end

  def get_last_task_owed
    tasks = @project.tasks
    tasks.where('task_end_date >= ?', Date.today).order('task_end_date DESC').first.task_end_date.strftime("%B %d, %Y")
  end

  def get_first_task_owed
    tasks = @project.tasks
    tasks.where('task_end_date >= ?', Date.today).order('task_end_date ASC').first.task_end_date.strftime("%B %d, %Y")
  end

  helper_method :get_projects_owed
  helper_method :get_all_projects
  helper_method :get_clients_with_projects
  helper_method :get_all_tasks
  helper_method :get_last_task_owed
  helper_method :get_first_task_owed

One possible improvement is using scopes:

def get_projects_owed
  current_user.projects.owed.recent_first.pluck(:name, :start_date, :end_date)
end

def get_all_projects
  current_user.projects.recent_first.pluck(:name, :start_date, :end_date)
end

def get_last_task_owed
  get_owed_tasks.last.task_end_date.strftime("%B %d, %Y")
end

def get_first_task_owed
  get_owed_tasks.first.task_end_date.strftime("%B %d, %Y")
end

def get_owed_tasks
  tasks = @project.tasks
  tasks.owed.order('task_end_date DESC')
end

helper_method :get_owed_tasks

class Project
  scope :owed, -> { where('end_date > ?', Date.today) }
  scope :recent_first, -> { order(:start_date) }
end

class Task
  scope :owed, -> { where('task_end_date >= ?', Date.today) }
end


How many of a particular item of clothing do I need? I am learning Go and want to do things the go-way, please have a look this code suggest how to make it better Go.

This is a simulation to determine how items of a particular type of clothing you need. Rules are as follows:

Simulation starts with all the clothes in the clean pile
Every morning you take one item from the clean pile and add it to the dirty pile (assuming an item of clothing becomes dirty the moment you put it on)
On wash days - before you put on a new item - all the items in the dirty pile go into washing pile
Every morning all items in the washing pile are put into the clean pile

Assuming there is a washing day every Monday, how many items of clothing do you need to never run out of clean ones?

There are some extra rules (I have made them flags):

Every second Thursday is also a washing day
There is an extra step in the washing process - drying. After an item is washed, the next day it is put into the drying pile, and only after drying does it go into the clean pile.

Code in the go-playground at: https://play.golang.org/p/3jawv55Y3p

package main

import (
    "flag"
    "fmt"
    "time"
)

func even(number int) bool {
    return number%2 == 0
}

func isWashingDay(today time.Time, thursday bool) bool {
    if today.Format("Mon") == "Mon" {
        fmt.Println("Monday!")
        return true
    } else if thursday && today.Format("Mon") == "Thu" {
        _, week := today.ISOWeek()
        if even(week) {
            fmt.Println("Thursday!")
            return true
        }
    }
    return false
}

func main() {
    numberOftshirtsPtr := flag.Int("shirts", 9, "a int number of tshirts")
    thursdayPtr := flag.Bool("thursday", true, "a bool use Thursday")
    dryingPtr := flag.Bool("drying", true, "a bool use drying")
    flag.Parse()

    var clean, minClean = *numberOftshirtsPtr, *numberOftshirtsPtr
    var dirty, washing, drying int
    today, _ := time.Parse(time.RFC3339, "2017-02-06T00:00:00+00:00")

    fmt.Println("Date       | C | D | W | Y ")

    testDays := 365
    for i := 0; i < testDays; i++ {
        if *dryingPtr {
            clean += drying
            drying = 0

            drying = washing
            washing = 0
        } else {
            clean += washing
            washing = 0
        }

        if clean == 0 {
            fmt.Println("Run out of clean shirts!")
            break
        }

        if isWashingDay(today, *thursdayPtr) {
            washing = dirty
            dirty = 0
        }

        // take a clean tshirt and wear it - it immediately becomes dirty
        clean--
        dirty++

        if clean < minClean {
            minClean = clean
        }

        fmt.Printf("%s | %d | %d | %d | %d \n", today.Format("2006-01-02"), clean, dirty, washing, drying)

        today = today.AddDate(0, 0, 1)
    }

    fmt.Println("Total days:", testDays)
    fmt.Println("Minimum clean shirts:", minClean)
}

For a beginner to go your program is good. You have obviously read up on flag handling, and you've got a grasp on the pointers. I have come to like the flag processing in go (though having previously learned/understood getopt and written my own library in Java, I feel like go should allow more powerful commandline handling).

Flags

So, having said you have a good grasp on those concepts, I am going to recommend that you change the flag handling (and as a consequence, you remove the pointers).

In addition, you should be putting in the number of days to simulate, and perhaps the starting date, as flags too.

So, flag functions include both ...Ptr and ...Var variants. I recommend using the ...Var variants where you can. Your code:

numberOftshirtsPtr := flag.Int("shirts", 9, "a int number of tshirts")
thursdayPtr := flag.Bool("thursday", true, "a bool use Thursday")
dryingPtr := flag.Bool("drying", true, "a bool use drying")
flag.Parse()

I would write like:

numberOftshirts := 9
doThursdays := true
doDrying := true

flag.IntVar(&numberOftshirts, "shirts", numberOftshirts, "the number of tshirts")
flag.BoolVar(&doThursdays, "thursday", doThursdays, "use Thursday")
flag.BoolVar(&doDrying, "drying", doDrying, "use drying")
flag.Parse()

By taking the address of the var and giving it to flag, we can then use the variables as-is later without having to keep the pointer handling at all, so code like:

var clean, minClean = *numberOftshirtsPtr, *numberOftshirtsPtr

becomes:

var clean, minClean = numberOftshirts, numberOftshirts

Note that, by convention, using hungarian notation in go is not good code-style. You should not suffix pointer variables with Ptr. A pointer to an int containing the number of T-Shirts is still numberOftshirts and not numberOftshirtsPtr

OK, so the above code changes the flag handling to be Var-based, and it reads easier, and removes all pointer references later.

I would also add flags for the starting date, and number of days to simulate.

Washing Day

Your washingday function is a good idea, but you are doing string processing in places where the time library has better options to offer. Note that time has constantes for the days-of-week, and those constants are declared as a Weekday type, and that type has a String() function available: https://golang.org/pkg/time/#Weekday - what this means is that you can avoid the string-conversions in the function. I personally would probably use the String() option too to print the days. Actually, I would remove the println from the function because it is making the function do too much - (computation and presentation). I would have your function as:

func isWashingDay(today time.Time, doThursday bool) bool {

    if today.Weekday() == time.Monday {
        //fmt.Printf("%v!\n", time.Monday)
        return true
    }

    if doThursday && today.Weekday() == time.Thursday {
        _, week := today.ISOWeek()
        if even(week) {
            //fmt.Printf("%v!\n", time.Thursday)
            return true
        }
    }

    return false
}

Note that I no longer have any raw text in there (it's all time variables, etc), and also note that I no longer have if ... else ... statements. When the if part of a condition always has a return in it, there's no need for the else at all.

Main

Your program is essentially contained inside the main-method. This makes the main method bulky, and the code is not reusable. Even in example progams and learning exercises, you should try to break your code in to functions that can be run, and tested independently. Go has a strong toolset related to unit-tests and benchmarks, and you should get in the habit of creating small, independent functions that are easy to process in the testing systems too.

One way to improve the bulkiness of the main method is to declare a struct to contain the state of a given day. You can get clever with some function processing too. I would create a state struct, and use it for a bunch of the logic....

type ClothesState struct {
    day     time.Time
    clean   int
    dirty   int
    washing int
    drying  int
}

In addition, to separate out your printing of the state, I would create a bit of a string helper function... I'll explain it later, but show you here, now:

func format(day, clean, dirty, washing, drying interface{}) string {
    return fmt.Sprintf("%-11v| %-2v| %-2v| %-2v| %2-v", day, clean, dirty, washing, drying)
}

With this function, we can add a String() method to our state too that uses it:

func (cs ClothesState) String() string {
    return format(cs.day.Format("2006-01-02"), cs.clean, cs.dirty, cs.washing, cs.drying)
}

Now we can use the %v (or %s) style fmt to print the state:

fmt.Printf("%v\n", state)

Further, I would take the state-tansition logic and make it a method on the struct too:

func (cs ClothesState) Advance(doDrying, doThursdays bool) ClothesState {
    tomorrow := cs.day.AddDate(0, 0, 1)

    clean := cs.clean
    clean += cs.drying

    drying := cs.washing
    if !doDrying {
        // take all the drying directly in to clean
        clean += drying
        drying = 0
    }

    washing := 0
    dirty := cs.dirty
    if isWashingDay(tomorrow, doThursdays) {
        washing = dirty
        dirty = 0
    }

    clean--
    dirty++

    return ClothesState{
        day:     tomorrow,
        clean:   clean,
        dirty:   dirty,
        washing: washing,
        drying:  drying,
    }

}

Now you have an immutable state struct that you can then advance through the daily logic. Each advance returns a new state.

Conclusion

You've made a great start in to Go. I encourage the use of structs to localize logic, the use of smaller, single-purpose functions, and separating the presentation code (printlns) from the calculation code.

I have taken your code and re-worked it in a way I would consider an improvement, and I have tweaked the starting state to match your logic (and also kept the println statements in the isWashingDay so that it matches the output of your program.

Have a look, and see how the logic is separated, how the flags are used, and so on: https://play.golang.org/p/B62HmIoxNc

package main

import (
    "flag"
    "fmt"
    "time"
)

func even(number int) bool {
    return number%2 == 0
}

func isWashingDay(today time.Time, doThursday bool) bool {

    if today.Weekday() == time.Monday {
        fmt.Printf("%v!\n", time.Monday)
        return true
    }

    if doThursday && today.Weekday() == time.Thursday {
        _, week := today.ISOWeek()
        if even(week) {
            fmt.Printf("%v!\n", time.Thursday)
            return true
        }
    }

    return false
}

func format(day, clean, dirty, washing, drying interface{}) string {
    return fmt.Sprintf("%-11v| %-2v| %-2v| %-2v| %-2v", day, clean, dirty, washing, drying)
}

type ClothesState struct {
    day     time.Time
    clean   int
    dirty   int
    washing int
    drying  int
}

func (cs ClothesState) String() string {
    return format(cs.day.Format("2006-01-02"), cs.clean, cs.dirty, cs.washing, cs.drying)
}

func (cs ClothesState) Advance(doDrying, doThursdays bool) ClothesState {
    tomorrow := cs.day.AddDate(0, 0, 1)

    clean := cs.clean
    clean += cs.drying

    drying := cs.washing
    if !doDrying {
        // take all the drying directly in to clean
        clean += drying
        drying = 0
    }

    washing := 0
    dirty := cs.dirty
    if isWashingDay(tomorrow, doThursdays) {
        washing = dirty
        dirty = 0
    }

    clean--
    dirty++

    return ClothesState{
        day:     tomorrow,
        clean:   clean,
        dirty:   dirty,
        washing: washing,
        drying:  drying,
    }

}

func main() {
    numberOftshirts := 9
    doThursdays := true
    doDrying := true

    flag.IntVar(&numberOftshirts, "shirts", numberOftshirts, "the number of tshirts")
    flag.BoolVar(&doThursdays, "thursday", doThursdays, "use Thursday")
    flag.BoolVar(&doDrying, "drying", doDrying, "use drying")
    flag.Parse()

    today, _ := time.Parse(time.RFC3339, "2017-02-06T00:00:00+00:00")

    // Set the state with 1 dirty shirt to match OP logic
    state := ClothesState{
        day:   today,
        clean: numberOftshirts - 1,
        dirty: 1,
    }

    minClean := state.clean

    fmt.Println(format("Date", "C", "D", "W", "Y"))
    fmt.Printf("%v\n", state)

    testDays := 365
    for i := 0; i < testDays; i++ {
        state = state.Advance(doDrying, doThursdays)
        fmt.Printf("%v\n", state)

        if state.clean < minClean {
            minClean = state.clean
        }

    }

    fmt.Println("Total days:", testDays)
    fmt.Println("Minimum clean shirts:", minClean)
}


Getting hexagonal arrays of dots arranged in this spiral pattern Answers to this explain why I can't reliably get int type arrays. While there are some workarounds I have a hunch there's a better, cleaner or otherwise "less tricky" way to get these hexagonal arrays of dots arranged in this spiral pattern than the way I've done it by using several conditions.

Is my hunch correct?

Note: hexit_60() and get_points() are used in different ways in other places so I don't want to combine them.

Context: This is used in a simulation and plotting routine for points in reciprocal space of a hexagonal lattice as part of a diffraction calculator.

import numpy as np
import matplotlib.pyplot as plt

def hexit_60(n_max):
    pairs = []
    if n_max >= 0:
        pairs.append(np.zeros(2, dtype=int)[:, None])
    if n_max >= 1:  # https://stackoverflow.com/q/61382568/3904031 trap 0*[n] because casts to float
        seq = [1, 0, -1]
        p0  = np.hstack((seq, seq[::-1]))
        N   = len(p0)
        p1  = np.hstack((p0[N-2:], p0[:N-2]))
        pairs.append(np.stack((p0, p1), axis=0))
    for n in range(2, n_max+1):
        seq = np.arange(n, -n-1, -1, dtype=int)
        p0  = np.hstack((seq, (n-1)*[-n], seq[::-1], (n-1)*[n]))
        N   = len(p0)
        p1  = np.hstack((p0[N-2*n:], p0[:N-2*n]))
        pairs.append(np.stack((p0, p1), axis=0))
    if len(pairs) > 0:
        pairs = np.hstack(pairs)
    else:
        pairs = None
    return pairs

def get_points(a, n_max):
    vecs = a * np.array([[1.0, 0.0], [0.5, 0.5*np.sqrt(3)]])
    pairs = hexit_60(n_max = n_max)
    if isinstance(pairs, np.ndarray):
        points = (pairs[:, None]*vecs[..., None]).sum(axis=0)
    else:
        points = None
    return points

fig = plt.figure()
for i, n_max in enumerate([-1, 0, 1, 2, 3, 4]):
    ax = fig.add_subplot(2, 3, i+1)
    # plt.subplot(2, 3, i+1)
    ax.set_title('n_max: ' + str(n_max))
    points = get_points(a=1.0, n_max=n_max)
    if isinstance(points, np.ndarray):
        x, y = points
        ax.scatter(x, y)
        ax.plot(x, y, '-k', linewidth=0.5)
    ax.set_xlim(-4.2, 4.2)
    ax.set_ylim(-4.2, 4.2)
    ax.set_aspect('equal')
plt.show()

return early

For the special case, n_max == -1, you can return early

def hexit_60(n_max):
    if n_max == -1:
        return None

This allows you to simplify the loop a lot

special case

the part before the for-loop can be included in the main loop by taking one of the other answers to your int question, and use casting.

reverse

The reverse of seq is also the negative. If you extract the (n-1)*[-n] to another variable, you can make this a lot clearer.

np.roll

np.hstack((p0[N-2*n:], p0[:N-2*n])) is equivalent to np.roll(p0, 2 * n)

generator

You can make the hexit_60 into a generator, even further simplifying it

def hexit_60_gen(n_max):
    if n_max == -1:
        return
    yield np.zeros(2, dtype=int)[:, None]
    for n in range(1, n_max + 1):
        seq = np.arange(-n, n + 1, dtype=int)
        middle = np.array((n - 1) * [-n], dtype=int)
        p0 = np.hstack((-seq, middle, seq, -middle,))
        p1 = np.roll(p0, 2 * n)
        yield np.vstack((p0, p1))

This code is a lot clearer to read to me.

It generates the same points:

all(
    np.array_equal(
        hexit_60(n_max), np.hstack(list(hexit_60_gen(n_max)))
    )
    for n_max in range(10)
)

get_points

You need to adapt this slightly:

def get_points_gen(a, n_max):
    vecs = a * np.array([[1.0, 0.0], [0.5, 0.5 * np.sqrt(3)]])
    pairs = list(hexit_60_gen(n_max=n_max))
    if pairs:
        return (np.hstack(pairs)[:, None] * vecs[..., None]).sum(axis=0)

if pairs is empty, this returns None implicitly.

The one thing I would is replace [0.5, 0.5 * np.sqrt(3)] by

angle = np.pi / 3 # diagonal
[np.cos(angle), np.sin(angle)]

So you don't have as many magic numbers in the code

draw_hexagon

can be simplified with a slight reordering and a continue

def draw_hexagon():
    fig = plt.figure()
    for i, n_max in enumerate([-1, 0, 1, 2, 3, 4]):
        ax = fig.add_subplot(2, 3, i+1)
        # plt.subplot(2, 3, i+1)
        ax.set_title('n_max: ' + str(n_max))
        points = get_points_gen(a=1.0, n_max=n_max)
        ax.set_xlim(-4.2, 4.2)
        ax.set_ylim(-4.2, 4.2)
        if points is None:
            continue
        x, y = points
        ax.scatter(x, y)
        ax.plot(x, y, '-k', linewidth=0.5)
        ax.set_aspect('equal')
    plt.show()

This latest part can be made a bit cleaner, using the principles of clean architecture, but this is good enough, or a bit more parametrized, but this is good enough.

--

alternative approach

Instead of the approach of the hexit_60, you can have a function to assemble the first side of the hexagon, and then apply rotations to this:

ANGLE = np.pi / 3
COS_ANGLE = np.cos(ANGLE)
SIN_ANGLE = np.sin(ANGLE)
ROTATION_MATRIX = [[COS_ANGLE, -SIN_ANGLE], [SIN_ANGLE, COS_ANGLE]]

Then to get one side, using np.linspace to do the interpolation:

def side_points(n):
    if n == 0:
        return np.array([[0], [0]])
    p0 = np.array([n, 0])
    p1 = n * np.array([COS_ANGLE, SIN_ANGLE])
    return np.linspace(p0, p1, n, endpoint=False).T

And then the rotations is a simple generator

def rotations(side):
    yield side
    if np.array_equal(side, np.array([[0], [0]])):
        return
    for _ in range(5):
        side = np.dot(ROTATION_MATRIX, side)
        yield side

Note that this can be easily adjusted to any regular polygon, by adjusting the angle, and passing in the appropriate cosinus, sinus and or rotation_matrix as function parameter instead of using the global

from functools import lru_cache

@lru_cache(None)
def cos_angle(sides):
    return np.cos(2 * np.pi / sides)

@lru_cache(None)
def sin_angle(sides):
    return np.sin(2 * np.pi / sides)

@lru_cache(None)
def rotation_matrix(sides):
    return np.array(
        [
            [cos_angle(sides), -sin_angle(sides)],
            [sin_angle(sides), cos_angle(sides)],
        ]
    )

def side_points(n, sides=6):
    if n == 0:
        return np.array([[0], [0]])
    p0 = np.array([n, 0])
    p1 = n * np.array([cos_angle(sides), sin_angle(sides)])
    return np.linspace(p0, p1, n, endpoint=False).T

def rotations(side, sides=6):
    yield side
    if np.array_equal(side, np.array([[0], [0]])):
        return
    rot = rotation_matrix(sides)
    for _ in range(sides - 1):
        side = np.dot(rot, side)
        yield side

def points(n_max, sides=6):
    return np.hstack(
        list(
            itertools.chain.from_iterable(
                rotations(side_points(n, sides), sides)
                for n in range(n_max + 1)
            )
        )
    )

Then drawing the polygon is simply:

def draw_polygon(sides=6):
    fig = plt.figure()
    for i, n_max in enumerate([-1, 0, 1, 2, 3, 4]):
        ax = fig.add_subplot(2, 3, i + 1)
        # plt.subplot(2, 3, i+1)
        ax.set_title("n_max: " + str(n_max))
        ax.set_xlim(-4.2, 4.2)
        ax.set_ylim(-4.2, 4.2)
        if n_max < 0:
            continue
        all_points = points(n_max, sides=sides)
        ax.scatter(*all_points)
        ax.plot(*all_points, "-k", linewidth=0.5)
        ax.set_aspect("equal")
    return fig

draw_polygon(7)


Improving handling of Express endpoint I have an API gateway in a larger set of microservices, and I'm handling one of my routes. The endpoint ends up making an RPC call to another service, and then I just log the response and send it back to the user. I haven't really completed the error handling section, because was thinking that I could add some middleware later on to handle my errors.

routes.post("/submit", async (request, result) => {
  logger.info("Received call to /gapf/submit endpoint");
  const gapf = request.body;

  // convert relevant request strings into integers
  gapf.facultyId = parseInt(gapf.facultyId, 10);
  gapf.created = parseInt(gapf.created, 10);
  gapf.lastModified = parseInt(gapf.lastModified, 10);
  if (gapf.documents !== undefined) {
    gapf.documents = gapf.documents.map(doc => {
      return {
        name: doc.name,
        link: doc.link,
        attachedDate: parseInt(doc.attachedDate, 10)
      };
    });
  }

  try {
    logger.info("Calling to Ticket Service with gapf body: %j", gapf);
    const response = await tridentClient.SubmitGAPF(gapf);
    logger.info("Received response from Ticket Service: %j", response);
    logger.info("Exiting /gapf/submit endpoint");
    result.json(response);
  } catch (err) {
    logger.error(
      "Received error from submitting to Ticket Service: ",
      err.message
    );
    // TODO: should add middleware later on to handle errors
    result.status(500);
    result.json({});
  }
});

Right now the error.message seems to be some binary data instead of JSON, so that would also need to be fixed later on.

Apart from the first issue below, your code is mostly clean!

What happens if one of the parseInt calls throws an exception? In that case, I'd send a HTTP 500 error as well. This is especially relevant in your scenario where the data comes from an unknown client.
Essentially, the solution boils down to wrapping all the code in a try-catch or employing middleware.

routes.post("/submit", async (request, result) => {
  try {
    /* all the code */
  }
  catch (err) {
    /* log & send a generic HTTP 500 error message as in your code */
    /* Beware that you might not intend to send a HTTP 500 message if
       the code in the try already sent something! */
  }
});

// <=>
routes.post("/submit", wrapSafe(yourCodeExtractedAsAFunction));

// <=>
routes.post("/submit", someMiddleWare(yourCodeAsAFunction));

Catching all exceptions (and not rethrowing ones you cannot handle) is fine in your case since your function is top-level enough for that.
Exactly as you say, if you add middleware, let the exception bubble up and let the middleware take care of it.
Omit the return in an arrow function if it is unnecessary and serves no clarity. So this block:

gapf.documents = gapf.documents.map(doc => {
  return {
    name: doc.name,
    link: doc.link,
    attachedDate: parseInt(doc.attachedDate, 10)
  };
});

Can be updated like this:

// You need enclosing parentheses, so that the parser can
// differentiate between a block statement and an object literal.
gapf.documents = gapf.documents.map(doc => ({
  name: doc.name,
  link: doc.link,
  attachedDate: parseInt(doc.attachedDate, 10)
}));

// convert relevant request strings into integers: Maybe you could describe what constitutes a "relevant request string". Is there a list of them?


Faster way to create linked list of length n in Python I'm attempting to create a linked list of length n using Python. I have the simple list implemented, a working concatenation function, and a working create_list function; however, I just want to know if there is a more efficient method at making the linked list than using my concatenate function (made for testing).

Simple List Class:

class Cell:

    def __init__( self, data, next = None ):
        self.data = data
        self.next = next

Concatenate Function:

def list_concat(A, B):
    current = A
    while current.next != None:
        current = current.next
    current.next = B
    return A

List create (that takes forever!):

def create_list(n):
    a = cell.Cell(0)
    for i in (range(1,n)):
        b = cell.Cell(i)
        new_list = cell.list_concat(a, b)
    return new_list

This is an assignment, but efficiency is not part of it. I am just wondering if there is a more efficient way to create a large list using this implementation of the structure.

The current algorithm has a failure in using the list_concat during list creation. The list_concat function walks to the end of the list for each node you want to add. So adding a node becomes O(n). This means creating a list of 10,000 items takes 1+2+3...+10,000 steps. That's O(n*n) performance.

As hinted, you should add the next node in the creation loop. You then get code that looks like this (I left out the list_concat function as it's not used):

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

def create_list(length=1):
  linked_list = Cell(0)
  head = linked_list
  for prefill_value in xrange(1, length):
    head.next = Cell(prefill_value)
    head = head.next
  return linked_list

You could also create the list in reverse order, allowing you to immediately fill the next attribute of the Cell. Your create_list function then looks like this (the reversed function should not be used for really huge lengths (several million) because it's created in-memory):

def create_list(length=1):
  tail = Cell(length - 1)
  for prefill_value in xrange(length - 2, -1, -1):
    tail = Cell(prefill_value, tail)
  return tail


Refreshing customer list periodically in the background I have a method RefreshCustomersInternal that refreshes customer data from a server and returns a Task. Since this process is very costly, I want to prevent this method from being called too many times in a short time or prevent the process from running if there's another refresh process running already. So a wrapper method RefreshCustomers is written for this purpose:

private Task _refreshTask;
private readonly object _refreshLock = new object();
private DateTime _lastRefreshTime = DateTime.MinValue;
private static readonly TimeSpan MinimumRefreshInterval = TimeSpan.FromSeconds(5);

private Task RefreshCustomers()
{
    lock (_refreshLock)
    {
        // If there is already a refresh task, just return this one.
        if (_refreshTask != null)
            return _refreshTask;

        // Check if the time between this refresh request and the previous one is too close.
        var intervalFromLastRefresh = DateTime.Now - _lastRefreshTime;
        if (intervalFromLastRefresh < MinimumRefreshInterval)
        {
            // If this refresh request is too close to the previous one,
            // make this request wait until the minimum refresh interval is passed,
            // then perform the refresh.
            var waitTaskSource = new TaskCompletionSource<bool>();
            _refreshTask = waitTaskSource.Task.ContinueWith(_=>RefreshCustomersInternal()).Unwrap();

            // Force the wait in a background thread to ensure a non-blocking UI experience.
            ThreadPool.QueueUserWorkItem(_ =>
            {
                Thread.Sleep(MinimumRefreshInterval - intervalFromLastRefresh);
                waitTaskSource.SetResult(true);
            });
        }
        else
            // If this refresh request is far enough from the last one,
            // just perform the normal refresh.
            _refreshTask = RefreshCustomersInternal();

        // When the refresh process is done, always clear the refresh task reference
        // and update the refresh timestamp.
        return _refreshTask = _refreshTask.ContinueWith(task =>
        {
            lock (_refreshLock)
            {
                _refreshTask = null;
                _lastRefreshTime = DateTime.Now;
            }
        });
    }
}

In a previous version of this method, instead of using the ThreadPool, it was simply just calling the Thread.Sleep method in a new Task:

if (intervalFromLastRefresh < MinimumRefreshInterval)
    _refreshTask = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(MinimumRefreshInterval - internvalFromLastRefresh);
        return RefreshCustomersInternal();
    }).Unwrap();

Since there is no guarantee that Task.Factory.StartNew will never start the new task on the UI thread, I updated it to use the ThreadPool to force the wait into a background thread.

The method seems working from some basic tests, but I wonder if there is any better way for the part where I had to use the ThreadPool.QueueUserWorkItem to force the wait in a background thread?

BTW, the code runs in .NET 4.0 hence the lack of all the neat async and await statements.

You are probably right in not using Task.Factory.StartNew. You should prefer Task.Run instead. Task.Run explicitly uses the default task scheduler which targets the thread pool while StartNew uses whatever the last used scheduler was.
I'm not sure you really need to distinguish the case between "I have to wait before refresh" and "I can run refresh now". The second one is just a special case of the first one with a delay of 0. Yes you may waste a scheduling cycle or two due to calling Delay but will 20ms or so really make a difference?
You have a bug: If your application runs when the system clock gets adjusted for DST the time can go backwards by 1h between one check an the next. The result will be that intervalFromLastRefresh is going to be negative in which case you will wait up to an hour extra before refreshing (we just hit this exact bug in one of our apps recently so the pain is still fresh ...).

With the above in mind you could simplify your implementation to:

private Task RefreshCustomers()
{
    lock (_refreshLock)
    {
        // If there is already a refresh task, just return this one.
        if (_refreshTask != null)
            return _refreshTask;

        // Check if the time between this refresh request and the previous one is too close.
        var intervalFromLastRefresh = DateTime.Now - _lastRefreshTime;

        var delay = MinimumRefreshInterval - intervalFromLastRefresh;
        if (delay < TimeSpan.Zero)
        {
            delay = TimeSpan.Zero;
        }
        else if (delay > MinimumRefreshInterval)
        {
            delay = MinimumRefreshInterval;
        }

        return _refreshTask = Task.Run(async delegate { await Task.Delay(delay); RefreshCustomersInternal(); })
                                  .ContinueWith(t => { lock (_refreshLock)
                                                        {
                                                            _refreshTask = null;
                                                            _lastRefreshTime = DateTime.Now;
                                                        } });
    }
}


Master/Slave smart-pointer I'm currently working on a project where i need to access objects from various places, pretty much like std::shared_ptr. At a certain point (e.g. when a library is unloaded) i need to destruct these objects. It is crucial to the project that the object is really destructed at this point, i can not just hand out weak_ptr and rely that no one keeps a shared_ptr. If i would just hand out weak_ptr to other parts of the program, anyone could call lock() and store the shared_ptr, delaying or preventing destruction of the objects. This would crash my program.

What happens in the background is this: I have a small number of classes providing generic access to yet unknown types, e.g. a class Object providing a method virtual getChilds()=0;. Libraries might then inherit from those classes with a class template <O> class TemplateObject; implementing the pure virtual functions. This way other parts of the program, including a GUI, can access in a limited way objects of a type, which was unknown at compile time. But if i destruct the Object with its virtual destructor, i call code that lives in the library - which obviously fails if i have already unloaded the library. I therefore need to make sure that the Object is destructed when the library is unloaded. The GUI e.g. is then able to notice that the object is already gone and can no longer be used.

My Idea was to create two smart pointers, namely master_ptrand slave_ptr. The master_ptr behaves pretty much like a unique_ptr or like "the one and only" shared_ptr, destructing the managed object. The slave_ptr acts much like a weak_ptr, just allowing a more direct access and hiding the option to get back the shared_ptr. The managed objects would be non-copyable and non-movable to make sure there are no copies left somewhere.

My implementation looks like this:

class ObjectInvalid{};

template <typename O>
class slave_ptr {
private:
    std::weak_ptr<O> m_ptr;

public:
    slave_ptr() {}
    slave_ptr(std::shared_ptr<O> ptr) : m_ptr(ptr) {}

    O& operator*() const {
        if (m_ptr.expired())
            throw ObjectInvalid();

        return m_ptr.lock().operator*();
    }

    O* operator->() const {
        if (m_ptr.expired())
            throw ObjectInvalid();

        return m_ptr.lock().operator->();
    }

    void reset() {
        m_ptr.reset();
    }
};

template <typename O>
class master_ptr {
private:
    std::shared_ptr<O> m_ptr;
public:
    master_ptr() = default;
    master_ptr(O* ptr) : m_ptr(ptr) {}

    //non-copyable
    master_ptr(const master_ptr&) = delete;
    master_ptr& operator=(const master_ptr&) = delete;

    //movable
    master_ptr(master_ptr&& other) = default;
    master_ptr& operator=(master_ptr&& other) = default;

    O& operator*() const {
        if (!m_ptr)
            throw ObjectInvalid();

        return m_ptr.operator*();
    }

    O* operator->() const {
        if (!m_ptr)
            throw ObjectInvalid();

        return m_ptr.operator->();
    }

    //allows reset before going out of scope
    void reset() {
        m_ptr.reset();
    }

    //cast to slave
    operator slave_ptr<O>() {
        return slave_ptr<O>(m_ptr);
    }
};

A small test tells me it works as i would expect, but before implementing it in a bigger project i wanted to aks here if theres any flaws i didn't see right now or if you could hint me to some improvements.

About priorities: Easy use and safety (no possible memory leaks, objects destructed when needed, exceptions thrown afterwards) are top priorities here. Performance is a "nice to have".

This is decidedly shady:

O& operator*() const {
    if (m_ptr.expired())
        throw ObjectInvalid();

    return m_ptr.lock().operator*();
}

O* operator->() const {
    if (m_ptr.expired())
        throw ObjectInvalid();

    return m_ptr.lock().operator->();
}

In the line:

return m_ptr.lock().operator->();

You create a shared pointer. Get the pointer value from the shared pointer. Destroy the shared pointer then return the pointer that was in the shared pointer.

So now you have a pointer but no guarantee that the object it points at exists anymore (as you destroyed your copy of the shared pointer).

There are a couple of operations on the master pointer that you don't support.

You can't test if it is empty.
So you are playing Russian roulette every time you use it.
You can't use it as part of a conditional (ie no conversion to bool).
You don't have a constructor that takes a nullptr => std::nullptr_t
You have a couple of problems with implicit construction.


Creating Immutable Student Object For a project I'm working on I have the following requirements:

We have two student types: Domestic and International

public enum StudentType {
    Domestic,International
}

Students of both types must have a ID number, First/Last name but only international students require documentation (Passports, drivers licence, etc).

I've decided to create the Student class as immutable, and came up with the following implementation:

public final class Student {

    private final String id;
    private final String firstname;
    private final String lastname;
    private final Collection<String> documents;;
    private final StudentType typeofStudent;

    private Student(String id, String firstname, String lastname, List<String> documents, StudentType typeofStudent)
    {
        this.id = id;
        this.firstname = firstname;
        this.lastname = lastname;
        this.documents = Collections.unmodifiableList(new ArrayList<String>(documents));
        this.typeofStudent = typeofStudent;
    }

    public static Student createDomestic(String id, String firstname, String lastname)
    {
        return new Student(id, firstname, lastname, Collections.emptyList(), StudentType.Domestic);
    }

    public static Student createInternational(String id, String firstname, String lastname, List<String> documents)
    {
        return new Student(id, firstname, lastname, documents, StudentType.International);
    }
}

I left out constructor validation to keep my code short and concise.

Advantages of the static method approach:

If the constructor was public, I would need to write a private helper method that checks if the student is domestic, the client didn't pass a list of documents. I would throw an exception to notify the client if this happened.
My code is shorter because I prohibit the client from passing a List<String> documents if the student was domestic. I simply ask for the ID, and first/last name. The Collections.unmodifiableList(); and StudentType are set when domestic students are created. In other words, no need for a private helper method.
The client knows exactly what type of student is being created without calling a getter/internal method to verify the student type.

Problem:

I came across this SESE page that was talking about the disadvantages of static. I became confused and wanted someone to review my code and tell me if my use of static methods are okay given what was said on that page?

The code and answer on this page provide what I need.

There are many code smells:

You create a single Student class, and differentiate students by an explicit type. This is a bit sad in an object-oriented language, where one should rather attempt to use interfaces and classes to represent types, leveraging the power of abstraction and polymorphism. Typically, your design would not scale well if you were to add new student types, or specific student behaviors (SRP / OCP from SOLID are at risk).
You create a property which should not be set not read (documents). This code is therefore a bit dubious (not useful, prone to misinterpretation).

Back to your domain: a student necessarily originates from somewhere (domestic), and may study abroad (international). In other words, I think you should simply have InternationalStudent inherit DomesticStudent, extending the class with the documents.

As for immutability, you don't have many options. The members must be final, and thus must be initialized during construction, with arguments passed to the constructor (either separately, or grouped inside a value object). Collections returned through getters must be wrapped by unmodifiable. You are already aware of this.

As for the creation method, you don't provide enough of your requirements to elicit a particular solution. Constructor calls or factories both seem fine to me.

Static methods may or may not be good, depending on the context. They do incite to consider a class as a namespace rather than a class (an object-orientation failure), and complicate testing (difficulty to mock dependencies).


Manage connection string I'm using dapper-dot-net for data access in my ASP.NET MVC application.
So in order to supply a connection string I've came up with the following pattern:

public static class ConnectionStringManager
{
    private static readonly SqlConnection conn;

    static ConnectionStringManager()
    {
        //initialize the connection with value from web.config file
        conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnName"].ConnectionString);
    }

    public static SqlConnection GetOpenConnection()
    {
        if (conn.State != System.Data.ConnectionState.Open)
            conn.Open();

        return conn;
    }
}

And a sample use of it with in a query:

public Customer GetCustomerById(int id)
{
    string sql = @"select * from Customer where Id = @id";
    using (var conn = ConnectionStringManager.GetOpenConnection())
    {
        Customer cust = conn.Query<Customer>(sql, new { id }).FirstOrDefault();
        return cust;
    }
}

So my question is if this is a good approach or not, and if not, what would you suggest to do different?

You create the SqlConnection only once, in the type constructor of ConnectionStringManager. Then you wrap its usage in a using block which is good practice but will dispose the object when it leaves the scope, so any subsequent usage will result in an ObjectDisposedException.

Instead, create a new connection in the GetOpenConnection method (maybe rename it to CreateConnection or similar in order to reflect the fact that there's work being done).


Presidential election predictor using matrix-processing I'm currently working on a project where I am trying to predict a presidential election based on the population density and region of a voter. I wrote a few MATLAB functions to parse the data, but it takes about a minute to run, which seems long.  My languages of choice are usually Java or Python and I feel like this calculation would only top a few seconds in those languages.

Quick side note: although this is for a school project, it is a simulation class, not a programming class.  The code works, which is what is required, the efficiency of the code is personal interest.

Main test script

%test metrics
printf("starting test\n");
p0 = parsePopMap("density2010.png"); %not shown because this returns quickly
[vm,rp,dp] = metrics(p0);
printf("republican:%d\ndemocrat:%d\n",rp,dp)

metrics.m

%generate matrix determining republican vote
function [voteMatrix,republicanPixels,democratPixels] = metrics(popGraph)

voteMatrix = zeros(rows(popGraph),columns(popGraph));

republicanPixels=0;
democratPixels=0;
printf("loading regions\n");
%regions is a matrix of size == popGraph, has values from 1-6
%so that any regions(row,column) returns the region of the country
load regions; %based on the printout, this happens within seconds
printf("calculating votes\n");

%suspected bottleneck
for r = [1:rows(popGraph)]
    for c = [1:columns(popGraph)]
        pixelRegion = regions(r,c);
        if (pixelRegion == 6)
            voteMatrix(r,c)=-1; %because it is water
        else
            vote = voteFromLocation(pixelRegion,popGraph(r,c));
            voteMatrix(r,c) = vote;
            if vote>.5
                republicanPixels +=1;
            else
                democratPixels +=1;
            end
        end
    endfor
endfor

voteFromLocation.m

function vote = voteFromLocation(region,popDens)

% array is percent for urban, suburban, rural
% probability area will vote republican
voteAverage = [ [.375,.51,.79];%pacific coast
                [.40,.54,.765];%midwest
                [.30,.47,.48];%Northeast
                [.485,.625,.725];%south
                [.46,.62,.795]];%Mountains/plains
voteDelta = [   [.05,.06,.1];%pacific coast
                [.04,.04,.07];%midwest
                [.12,.06,.10];%northeast
                [.09,.07,.27];%south
                [.12,.08,.21]];%mountains/plains

%represents the max value of that demographic
ruralThresh = 900; %so <=900 is rural
subThresh = 1100; % 900<x<=1100 is suburban
%urban is anything above 1100

demo = -1;
if(popDens<=ruralThresh)
    demo = 3;
elseif(popDens<=subThresh)
    demo = 2;
else
    demo = 1;
end
mean = voteAverage(region,demo);
stdDev = voteDelta(region,demo);
probVoteRep = (mean + stdDev * randn());

vote = probVoteRep;

I believe the source of the bottleneck is the for loops of metrics.m.  Most matrix processing I've seen uses different approaches, which I believe may be faster.

Replacing loops in MATLAB with equivalent matrix operations (a technique commonly referred to as vectorization) often, but not always, leads to improvements in performance. However, this frequently results in code that may be difficult for others to read, so it is advisable to use the profiler to identify bottlenecks and then try vectorizing only those sections of code where performance really matters. You could do something like this (outside the loop):

voteMatrix(regions == 6) = -1

This is equivalent to the first if condition in your loop. Try to do the same to the else condition. (Hint: you'll need to update your voteFromLocation method to handle arrays in the same manner.)

It's been a long time since I last used MATLAB, so my syntax may not be very accurate, but you get the general idea.


Sieve of Eratosthenes performance; Scala very slow compared to Node.js I am new to Scala so it might show. I am learning it for one of my classes and have to write a performance benchmark. I have written the Sieve of Eratosthenes in both Node.js and Scala, and my Node.js version runs much much quicker for n larger than 100,000. At n = 100,000 the Scala version runs in around a minute where as the Node.js one runs in milliseconds.

As far as I know the Scala version is implemented correctly as it finds the first few primes correctly.

The big disparity in time leads me to believe it's an algorithmic issue and the two pieces of code likely have different time complexities, but looking at the two pieces of code I don't see any stark differences other than iterating the list a couple extra times in the scala version (with the zipIndex and mapping).

Any help would be appreciated.

This is my Scala method

// Sieve of Eratosthenes
// pseudo code from https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
def sieve (n: Integer) = {
    // Let A be an array of Boolean values, indexed by integers 2 to n,
    // initially all set to true.
    var A = new ListBuffer[Boolean]()
    var i = 2
    for (i <- 2 to n) {
        A += true
    }

    // for i = 2, 3, 4, ..., not exceeding √n:
    // if A[i] is true:
    //    for j = i^2, i^2+i, i^2+2i, i^2+3i, ..., not exceeding n:
    //      A[j] := false.
    i = 2
    for ( i <- 2 to Math.sqrt(n.toDouble).toInt ) {
        if(A(i - 2)) {
            var j = 0
            for ( j <- i * i to n by i ) {
                A(j - 2) = false
            }
        }
    }

    // Output: all i such that A[i] is true.
    A.zipWithIndex.filter{case (b, i) => b }.map{ case (b, i) => i + 2 };
}

This is my Node.js code:

let _ = require('lodash');

// Sieve of Eratosthenes
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

function int (str, base=10) {
    return parseInt(str, base);
}

// Input: an integer n > 1.
let n = int(process.argv[2]);

//  Let A be an array of Boolean values, indexed by integers 2 to n,
//  initially all set to true.
 let A = _.range(n+1)
 A[0] = false
 A[1] = false

// for i = 2, 3, 4, ..., not exceeding √n:
//    if A[i] is true:
//      for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n:
//        A[j] := false.
for(let i = 2; i <= Math.sqrt(n); ++i) {
    if(A[i]) {
        for(let j = i*i; j <= n; j += i) {
            A[j] = false;
        }
    }
}

let primes = A.filter((el)=>el);

Lists vs. Arrays

The Scala version of your code ran surprisingly slower because you used a ListBuffer. In Scala you can think of a List as a traditional linked-list. Lists don't provide random access to their contents. That is, accessing an object at index n requires O(n) time. This really slowed down your code because you index into A in both your inner and outer for-loop.

To fix this problem you can simply use a different data structure like an Array.

object Sieve extends App {
  val n = 100000
  val a = Array.fill(n + 1)(true)
  a(0)  = false
  a(1)  = false
  val k = scala.math.sqrt(n).toInt

  for (i <- 2 to k; if a(i))
    for (j <- i * i to n by i)
      a(j) = false

  val res = a.zipWithIndex.filter(_._1).map(_._2)
  assert(res.length == 9,592)
}

Other Notes

_._1 represents accessing the first element in a tuple
Tuples are one indexed
So if we have a tuple t we can access the 5th element with t._5
The first underscore is what is known as placeholder syntax. For example:

    val a = List.range(0, 9)
    val b = a.map(i => i + 1)
    val c = a.map(_ + 1)       // placeholder syntax

In the above code snippet b and c are equivalent
When we are using a map operation on a List of tuples we can combine the tuple element access operator (t._N) and placeholder syntax. As a result we get code that looks something like:

    val res = a.zipWithIndex.filter(_._1).map(_._2)


Printing every digit of a number Which of these three methods is better?

import java.util.* ;
public class anycode{

  public static void print_digits3(int num){
    //this method converts integer to string and parses it
    int digit = 0 ;
    String num_str = new Integer(num).toString() ;
    int counter = 0  ;
    while(counter != num_str.length()){
       System.out.println("digit: " + num_str.charAt(counter)  + "| real integer digit: " + Integer.parseInt(num_str.substring(counter,counter+1))) ;
      counter++ ;
    }

  }

  public static void print_digits4(int num){
    //this method converts integer to array of chars and parses it
     char[]num_sequence_of_chars = new Integer(num).toString().toCharArray() ;
     for(int i = 0 ; i < num_sequence_of_chars.length ; i++){
       System.out.println("digit :" + num_sequence_of_chars[i] ) ;
     }
  }
  public static void print_digits2(int num){
    //this is the MATH method of parsing number - take every first digit div by
    // 1000,100,10,1 and update num - num% to get the rest

    //it s clunky, hard to read
    int digit = 0 ;

    Integer res_int = new Integer(num) ;

    int num_len = res_int.toString().length();// need to know if the number is 3-digit,4-digit etc
    //so we can know the power of 10 - 10^3, 10^2, 10^1 etc
    System.out.println("len of num : " + num_len) ;
    num_len-- ;
    double base = 0 ;
    int temp ;
    while( num_len >= 0){
      temp = num ;
      base = Math.pow(10,num_len) ;
      num = num / (int)base ;// type recasting to int is a must, it does not work without it - no idea why
      System.out.println("num :"  + num) ;
      num = (int) temp % (int)base ;
      num_len-- ;
  }

  }
  public static void print_digits(int num){
    int digit = 0 ;
    while(num != 0 ){
    digit = num%10 ;
    System.out.print(digit + "\t") ;
      num = num/ 10 ;
    }
  }

  public static void main(String args[]){
              print_digits2(7658) ;
              System.out.println("--------------------------") ;
              print_digits3(7658) ;
  }

}

How can I rewrite the print_digits2?  I want a more efficient MATH method of doing - no converting to string \ char[].

To be frank, I don't really know why you need such methods to print out individual characters, I'll just make my suggestions based on what you have...

Your class name anycode should be in PascalCase.
Your method names should be in camelCase.
Eclipse tells me that the assignments int digit = 0; in print_digits3 and print_digits2 are not used.
You have this comment: // type recasting to int is a must, it does not work without it - no idea why - that's because when you divide an int with a double, the result will be double type but you are assigning that to an int value. Therefore, you are required to cast the double into an int first for the assignment to be correct.
Recommended to use Integer.valueOf() instead of new Integer().

Not sure what's your aversion to using the char[] way of doing the same task, but here's a suggested approach anyways for comparison (to your print_digits4 method):

private static void printDigits( int num ) {
    for ( char c : String.valueOf( num ).toCharArray() ) {
        System.out.println( c );
    }
}


Maximum product of 3 integers in an int array I want to find the maximum product that can be obtained from any 3 integers in an integer array. The optimal solution has time complexity of \$O(n)\$ and space complexity of \$O(1)\$. I managed to write up as solution in Java that only traverses the array twice (so my time complexity is \$O(n)\$) and my space complexity is \$O(1)\$. I do not believe the solution can be any cleaner than this but would still like to see what other people think.

The \$O(n)\$ solution is obtained by keeping track of the max three integers and the min two integers. The max product will either be  (min_one * min_two * max_one) or (max_one * max_two * max_three).

// Assume input array is of at least length 3.

public int max_prod_three(int[] A){

    int len = A.length;

    // Base case
    if (len == 3) return A[0]*A[1]*A[2];

    int max = A[0], min = A[0], max_index = 0, min_index = 0;

    for (int i = 0; i < len; i++) {

        if (A[i] > max) {

            max = A[i];
            max_index = i;
        }
        else if (A[i] < min) {

            min = A[i];
            min_index = i;
        }
    }

    int max_sec = min, max_third = min , min_sec = max;

    for (int i = 0; i < len; i++) {

        if (i == max_index || i == min_index) continue;

        if (A[i] > max_sec) {

            max_third = max_sec;
            max_sec = A[i];
        }
        else if (A[i] > max_third) {
            max_third = A[i];
        }

        if (A[i] < min_sec) min_sec = A[i];

    }

    int prod_one = max * max_sec * max_third ;
    int prod_two = min * min_sec * max ;

    if (prod_one > prod_two) return prod_one ;
    return prod_two;
}

You can iterate through the array only once and get the max product but I found that the solution gets a bit too messy (with a lot more if else statements). But if anyone can do it cleanly, I would like to know.

Minor edge case
It's possible that the product of three integers will overflow.  For example, three positive integers may produce a negative product and cause your function to return the other product instead.  Since your function returns an int, it's not clear what you are supposed to do if that happens.  Perhaps you are guaranteed that the values are small enough not to overflow?
Otherwise the function looks correct and easy to understand.


Dynamically adding blocks of information to a page I have code that dynamically adds blocks of information to my page. I don't know in advance how many blocks there will be. I want to utilize Twitter Bootstrap (3.x) to layout them in three columns (e.g. I want to use col-xs-4).

Bottom line: is it okay to add col-* elements to a container without wrapping them in row elements?

I currently generate this markup:

.my-box {
  margin: 5px;
  padding: 5px;
  background-color: #fed;
}
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

One

Two

Three

Four

Etc.

I'm looking to get feedback on the above bit of code. (I've omitted the bit that generates the divs for brevity as well as the fact that I'm not necessarily looking for feedback on that bit. Ping me in a comment if you do think the way its generation is important.)

Things I've researched:

This seems to work fine, rendering just the way I want it to. However, this seems to go against common-sense semantics of rows and columns.

So I checked the Grid System documentation for Bootstrap, but it is unclear as to whether it is or isn't required to wrap col-* elements inside a row or not. Nowhere is it stated as an explicit requirement, but on the other hand the examples do wrap column elements in rows without exception.

Yes, it's fine to do. Rows are only used to create groups of horizontal content. In your case, your grid would wrap around (which you may want to consider is what you really want), but this is how responsive grids of photos are generally created.


Test a single-line file for punctuation and newline I have written the following program to read from a file (entire input in single line) and check for:

ASCII punctuation characters
a final newline

import re
file_name=input("Please enter the file name ")
with open(file_name, 'r') as fp:
    context=fp.read()
    regex = re.compile('[@_!#$%^&*()<>?/\|} {~]')
    if regex.search(context) is None:
        print("No special character found")
    else:
        print("Special character found")
    for x in range(0,len(context)-1):
        if (context[x].isspace())==True:
            print("spaces found in the file at ", x)
            break
        else:
            pass
        #print("No space found")
    for x in range(0, len(context)-1):
        if context[x]=='\n' or context[x]=='"':
            print("Yes new line is there at", x)
            break
        else:
            pass
        #print("No new line ")

\| is not a proper escape sequence.  To include the backslash in the string, it should be escaped using two backslashes, or you should use a “raw” string for the regular expression, so backslashes do not need to be escaped.

for x in range(0, len(context) - 1): does not check the last character of the string, since range(start, end) already does not include end.

if (context[x].isspace())==True: does not need the parentheses around context[x].isspace(), nor does it need the == True.

You can use enumerate() to loop over the contents of an iterable and get the index at the same time.  Also, a for ... else block can be used to detect if nothing was found.  With Python 3.6 or later, f-strings can be used to embed variables directly in strings.

for idx, ch in enumerate(context):
    if ch.isspace():
        print(f"spaces found in the file at {idx}")
        break
else:
    print("no space found")

It is strange to find a quotation mark, and declare that a new line has been found.  Are you sure you’ve got your logic correct?

PEP8 Guidelines:

spaces around all operators, like =, ==, -
use a space after each comma in argument lists
blank line after imports
longer, descriptive variable names (x is too short and not descriptive)