Return a Promise for a JSON POST Given this method, we don't know which syntax is the more appropriate.

async finishUpgrade({id}) {
    return new Promise((resolve, reject) => {
      let options = {
        method: 'POST',
        uri: this.apiUrl + `${id}/?action=proceed`,
        body: {}
        json: true
      };

      try {
        const res = await req(options);
        resolve(res);
      } catch(err) {
        reject(err);
      }
    });
  }

As you can see we use return new Promise(...).

Would it be correct/a better way to refactor it this way:

async finishUpgrade({id}) {
  let options = {
    method: 'POST',
    uri: this.apiUrl + `${id}/?action=proceed`,
    body: {}
    json: true
  };

  try {
    const res = await req(options);
    return Promise.resolve(res);
  } catch(err) {
    return Promise.reject(err);
  }
}

Given this method, we don't know which syntax is the more appropriate.

Neither is appropriate as both your options employ promise anti-patterns (creating new promises when you can just work with and return the one you already have).

Assuming req() already returns a promise (which you imply with your use of await), you should just return that promise directly.  I see no reason to even use async or await here.

// presumably from your use of this, this is a method declaration
function finishUpgrade({id}) {
  let options = {
    method: 'POST',
    uri: this.apiUrl + `${id}/?action=proceed`,
    body: {}
    json: true
  };
  return req(options);
}

this.finishUpgrade({id: someId}).then(result => {
    // upgrade done here
}).catch(err => {
    // error here
});

When you do need to modify the return value, you just add a .then() handler and the modified value you return from that .then() handler becomes the new resolved value:

// presumably from your use of this, this is a method declaration
function finishUpgrade({id}) {
  let options = {
    method: 'POST',
    uri: this.apiUrl + `${id}/?action=proceed`,
    body: {}
    json: true
  };
  return req(options).then(result => {
      // change the resolved value of the promise to our data object
      let data = { someData: someValue };
      data.response = result;
      return data;
  });
}

this.finishUpgrade({id: someId}).then(result => {
    // upgrade done here
}).catch(err => {
    // error here
});


Code to generate a random date of birth which will always represent an age less than 18 years from current date I want to generate a random date of birth [mm/dd/yyyy]which will
represent an age equal to less than 18years old
My requirement is to dynamically generate test data [date of birth]
to negatively test a system which needs a date of birth (age) to be
always greater than 18 years old
The system which I am trying to test compares the user's input
D.O.B. with the current date and calculates the age, if the age is
less than 18 years old then throws an error
I have tried to create the below python snippet to generate a date
of birth [for age less than 18 years old] and kindly need expert opinions to know if this
is indeed the correct/best approach?

start_date = date.today() - relativedelta(years=18)
end_date = date.today()
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_date + datetime.timedelta(days=random_number_of_days)
month = random_date.month
day = random_date.day
year = random_date.year
# Once I have the the day, month, year then I can convert it in ISO date format as per my needs

datetime.date has a .replace() method that returns a copy with some values changed.  This can be used to get the date 18 years ago.
end_date = date.today()
start_date = end_date.replace(year=end_date.year - 18)

datetime.date.toordinal returns an integer corresponding to the date. The ordinals for the start and stop date can be used in random.randint() to pick a random ordinal, which can then be converted back into a date with date.fromordinal().
random_date = date.fromordinal(random.randint(start_date.toordinal(), end_date.toordinal()))

date.isoformat() returns a date a as YYYY-MM-DD. Or use date.strftime() for more control over the date format.  In an f-string, a date is converted to ISO format, or a format string can be used:  f"{random_date:%a, %b %d, %Y}" -> 'Sat, Dec 14, 2013'.
If you want to generate a list of dates in the range, use random.sample() with a range object.
NUMBER_OF_DATES = 10

date_range = range(start_date.toordinal(), end_date.toordinal())
random_dates = [date.fromordinal(o) for o in random.sample(date_range, NUMBER_OF_DATES)]


Detect real "hard" character keys only Is there any simple way to detect user keystrokes that result in character input? In other words, ignore all soft keys and modifier keys? This works but seems sort of hacky:

var keycode = event.keyCode ? event.keyCode : event.charCode
if((keycode>=48 && keycode<=90) || (keycode>=96 && keycode<=111) || (keycode>=186 && keycode<=192) || (keycode>=219 && keycode<=222)){
    alert("realkey")
}

Yes, use keypress events instead of keydown events.  See example: http://jsfiddle.net/7fmjh/6/ - or a non-jquery example: http://jsfiddle.net/7fmjh/11/


Optimizing sum_combination_for(n) code I'm working on a piece of code for calculating all the possible combinations of numbers that sum to n. For example:

sum_combination(3) = [
  [1,1,1],
  [1,2],
  [3]
]

So my ruby code is this:

class Integer
  SUM_COMBINATION = {
    1 => [[1]],
    2 => [[1,1],[2]],
    3 => [[1,1,1],[1,2],[3]]
  }

  def sum_combination
    SUM_COMBINATION[self] ||= (
      (self-1).downto((self/2.0).ceil).map do |n|
        n.sum_combination.map { |c| (c+[self-n]).sort }
      end.flatten(1).uniq + [[self]]
    )
  end
end

The code works, but it's insanely slow for numbers above 50.

Notes:

Using uniq in a combinatorics problem is most likely a code smell. It means that you are generating more elements that you need (waste of space and time) and later you have to remove them (waste of more time).
The natural way seems to be  passing down which is the maximum subtraction value allowed, that way you won't repeat values in different orders.
I wouldn't extend Integer for a method like this, it does not seem a general enough abstraction.
Note that map + flatten(1) -> flat_map.

I'd write (also in functional style, as your code):

module Combinatorics
  def self.sets_with_sum(value, max = value)
    if value == 0
      [[]]
    else
      1.upto(max).flat_map do |n|
        sets_with_sum(value - n, [value, n].min).map do |ns|
          [n] + ns
        end
      end
    end
  end
end

p Combinatorics.sets_with_sum(4)
p Combinatorics.sets_with_sum(50).size

Even though I don't memoize anything, the performance is acceptable:

$ time ruby sum-combination.rb
[[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]
204226

real    0m8.416s


Python loop to write all possible strings that can be formed from some letters The code below generates a query with the product of possibilities that may vary from 'abc' to 'abc ... z'

import itertools
import time

res = itertools.product('abcdefgh', repeat=8)
fileObj = open("txt_abcdefgh.txt","w")
timestamp1 = time.time()

for i in res:
    print (i) #this only to check the progress of the process
    fileObj.write(i[0] + i[1] + i[2] + i[3] + i[4] + i[5] + i[6] + i[7] + '\n')

timestamp2 = time.time()
fileObj.write('This took %.2f seconds' % (timestamp2 - timestamp1))
fileObj.close()

However, I have an entry of only 8 items and the runtime is unsatisfactory.

Input      Time             Possibilities
abc        0.01 seconds     27
abcd       0.29 seconds     256
abcde      4.28 seconds     3,125
abcdef     31.59 seconds    46.656
abcdefg    542.44 seconds   823,543
abcdefgh   4806.84 seconds  16,777,216

Is there any other way to better this code, maybe with some other language, or with another programming technique?

1. Speeding up the code

Here's the initial measurement:

$ python ./cr163578.py
('a', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('a', 'a', 'a', 'a', 'a', 'a', 'a', 'b')
('a', 'a', 'a', 'a', 'a', 'a', 'a', 'c')
... much output deleted ...
('h', 'h', 'h', 'h', 'h', 'h', 'h', 'h')
$ tail -1 txt_abcdefgh.txt
This took 122.10 seconds

Let's make some improvements:

Omit the print statement, which generates lots of useless output that is just slowing us down.
Use the with statement to open and close the file.
Omit the time measurement — we can use the time program to do the measurement.

Here's version 2:

import itertools
with open('txt_abcdefgh.txt', 'w') as f:
    for i in itertools.product('abcdefgh', repeat=8):
        f.write(i[0] + i[1] + i[2] + i[3] + i[4] + i[5] + i[6] + i[7] + '\n')

This is about 8 times as fast as the original:

$ /usr/bin/time python cr163578.py
       16.73 real        16.45 user         0.23 sys

Now let's use the join method to build the output instead of lots of + operations. Here's version 3:

import itertools
with open('txt_abcdefgh.txt', 'w') as f:
    for i in itertools.product('abcdefgh', repeat=8):
        f.write(''.join(i) + '\n')

This is about 16 times as fast as the original:

$ /usr/bin/time python cr163578.py
        8.25 real         8.01 user         0.21 sys

And finally, let's avoid the need to append the newline to each line of output by using the writelines method of the file. Here's version 4:

import itertools
with open('txt_abcdefgh.txt', 'w') as f:
    f.writelines(map(''.join, itertools.product('abcdefgh', repeat=8)))

This is about 20 times as fast as the original:

$ /usr/bin/time python cr163578.py
        5.87 real         5.73 user         0.12 sys

2. Runtime complexity

If there are \$k\$ letters in your alphabet, and \$n\$ characters in the strings you are constructing, then there are \$k^n\$ strings altogther. Here \$k=8\$ and \$n=8\$ so there are \$8^8 = 16,777,216\$ possibilities, which take \$9 \times 8^8 = 150,994,944\$ bytes to store on disk.

Your aim is to have \$k=26\$ and \$n=26\$. But then there will be $$26^{26} = 6,156,119,580,207,157,310,796,674,288,400,203,776$$ possibilities, which can't possibly be generated or stored.

Whatever you are trying to do, you will have to find some other way to do it.


Auto registering class registry I built this auto registering registry to look into a package and import all modules and register any classes that are a subclass of a base class. I use it as a registry for a model's choices in Django and to be able to do a getattr on the class to get properties in a service that processes some data based on choices selected and dynamically finds the right class.

Reasoning behind this methodology is because we would have an unknown number of stat classes that will be created in the future. I wanted to avoid forgetting to register them and to hide the implementation details of the choices on the model (The model is absolutely massive). So I wanted a folder that just takes care of that for us.

I am trying to determine if this is breaking any best practices, is a good design, safe, efficient and not doing anything downright stupid. (Maybe the dynamic import).

Base class for using it other places if need be

class AutoRegClassRegistry(Singleton):
    PACKAGE = None
    BASE_CLS = None

    def __init__(self, force_import=True, *args, **kwargs):
        super(AutoRegClassRegistry, self).__init__(*args, **kwargs)

        self.force_import = force_import
        if self.PACKAGE:
            package_dir = os.path.dirname(self.PACKAGE.__file__)
            for module in [name for _, name, _ in pkgutil.iter_modules([package_dir])]:
                module = "{}.{}".format(self.PACKAGE.__name__, module)
                if self.force_import:
                    _ = __import__(module)
                for name, obj in inspect.getmembers(sys.modules[module], inspect.isclass):
                    if name == self.BASE_CLS.__name__:
                        continue
                    if issubclass(obj, self.BASE_CLS):
                        self.register(obj)

    def register(self):
        raise NotImplementedError("You must inherit from this class and override the register func")

Project structure

- init.py (this ClientStats class in here)
- base.py
- autoregister
    - init.py
    - hourly.py
    - daily.py
    - weekly.py
    - monthly.py

Implementation

class ClientStats(AutoRegClassRegistry):
    """
    A registry for client stats that also behaves as a tuple when used as a choices field. You can also do a getattr on
    this class to get the class, description or short of a stat.
    """
    PACKAGE = auto_register
    BASE_CLS = BaseStat

    def __init__(self, *args, **kwargs):
        self.__choices = []
        super(ClientStats, self).__init__(*args, **kwargs)

    def __getitem__(self, key):
        return self.__choices[key]

    def __iter__(self):
        return iter(self.__choices)

    def register(self, cls):
        cls_short = getattr(cls, "SHORT", None)
        if not cls_short:
            raise AttributeError("CLS {} doesn't have attribute 'SHORT' which is required to register to ClientStats")
        cls_desc = getattr(cls, "DESCRIPTION", None)
        if not cls_desc:
            raise AttributeError(
                "CLS {} doesn't have attribute 'DESCRIPTION' which is required to register to ClientStats")
        if hasattr(self, cls_short):
            raise AttributeError("ClientStats already has a {} registered".format(cls_short))
        setattr(self, cls_short, cls_short)
        setattr(self, "{}_DESC".format(cls_short), cls_desc)
        setattr(self, "{}_CLS".format(cls_short), cls)
        self.__choices.append((cls_short, getattr(self, "{}_DESC".format(cls_short))))

CLIENT_STATS = ClientStats()

Example class that gets registered

class DailyStatExample(BaseStat):
    SHORT = "DSE"
    DESCRIPTION = "Example stat class"

Sample usage of the ClientStats class:

models.py

class ExampleModel(models.Model):
    client_stats = MultiSelectSlugField(choices=CLIENT_STATS)

script.py

stats = ExampleModel.objects.get(pk=1).client_stats
for stat in stats:
    klass = getattr(CLIENT_STATS, "{}_CLS".format(stat)
    klass_inst = klass()
    klass.calculate(arg1, arg2)

Why

for module in [name for _, name, _ in pkgutil.iter_modules([package_dir])]:

and not

for _, module, _ in pkgutil.iter_modules([package_dir]):

? If it's about iterating eagerly, using list would work better than a list comprehension.

_ = __import__(module)

is also weird; why not just __import__(module)?

It makes sense for AutoRegClassRegistry to be an ABC, but by no means is this a requirement. It's worth noting that

def register(self):
    raise NotImplementedError("You must inherit from this class and override the register func")

has the wrong number of arguments, so will give an unhelpful error instead.

Don't use name mangling for self.__choices = [] unless there's good reason; _choices works just as well.

cls_short = getattr(cls, "SHORT", None)
if not cls_short:
    raise AttributeError("CLS {} doesn't have attribute 'SHORT' which is required to register to ClientStats")

seems like it breaks EAFTP;

cls_short = cls.SHORT

would work just as well and

try:
    cls_short = cls.SHORT
except AttributeError:
    raise AttributeError("CLS {} doesn't have attribute 'SHORT' which is required to register to ClientStats")

would be more descriptive of intent. The same happens immediately after.

The whole

if hasattr(self, cls_short):
    raise AttributeError("ClientStats already has a {} registered".format(cls_short))
setattr(self, cls_short, cls_short)
setattr(self, "{}_DESC".format(cls_short), cls_desc)
setattr(self, "{}_CLS".format(cls_short), cls)

looks really backwards, though; why not just put this in a simple data structure? Why does it have to be through messy attribute accesses.

This whole thing feels really dynamic, and dynamism should be a last resort. But I've never touched Django, so I can't really say whether what you're doing is justified or not.

As I said, I've never touched Django so I can't really say whether this could work, but I'd be tempted to do something more like

DailyStatExample = ClientStats.new("DSE", "Example stat class")

or

@ClientStats.register("DSE", "Example stat class")
class DailyStatExample:
    ...


Refactoring the legacy code which is using '§' char in the code I have a legacy code (might be 20 years old) as shown below. Where they are using the non ASCII '§' char in the code.
First they are preparing a SELECT query and the SELECT query looks like this...

SELECT 'ERROR_ID=§' || ERROR_ID ||  '§'  || ' AND ' ||  'DAT=:' || ...

They are using below code while preparing the SELECT query.
    strcat(query, "§" );

From the SELECT query result which still contains the '§', they are doing comparision as shown below and if '§' char is present in the char array, they are replacing it with single quotes.
Since they are using the non ASCII char '§' in the code, I have been repoted an issue where the '§' is not getting replaced with single quotes and they
are appearing as question marks '?' in the log file. Below is the code where they are doing the replace

len_before=strlen(file_str);
k=l=end=0;
while(end==0)
{
    if(file_str[k] == '\'')
    {
        strcpy( result,(char*)&file_str[k]);
        file_str[k] = '\'';
        strcpy((char*)&file_str[k+1],result);
        k++;
    }
    else
    {
        if((char)file_str[k]=='§') // Replace '§' by single quotes.
        {
            strncpy((char*)&file_str[k],"'",1);
        }
    }
    k++;
    l++;
    if(l>len_before)
        end=1;
};

So I am refactoring the code to not to use the non ASCII char '§' with sequence of chars as say ("!-!") for preparing the SELECT query as shown.

strcat(query, "!-!" );

And the result from the SELECT query I have to replace this sequence of chars ("!-!") with single quotes. Below is the refactored code...

string replaceAll(string inputString, string stringToFind, string stringToReplace)
{
    int found = inputString.find(stringToFind);
    while (found != string::npos)
    {
        inputString.replace(found, stringToFind.length(), stringToReplace);
        found = inputString.find(stringToFind, found + stringToReplace.length());
    }
    return inputString;
}

{
    // First replace every occurance of single quotes with double single quotes.
    string myString(file_str);
    myString = replaceAll(myString, "\'", "\'\'");

    // Replace the sequence of chars "!-!" with single quotes.
    myString = replaceAll(myString, "!-!", "\'");
}

Questions:

I would like to know if there are any pit falls which I need to look after?
Which sequence of chars can be used instead of "!-!"?
Is there any significane of char '§' (I believe that code is using '§' as a delimiter)in the code since they are connecting to the DB and fetching the data?

I don't see you using std::, surely you didn't put using namespace std somewhere in your code right?

I find your parameter names a bit confusing. stringToReplace is actually the replacement. The string you want to replace is stringToFind. Maybe use something like replaceWith or just replacement for the second parameter instead.

There is a type mismatch which your compiler should have caught (no warnings enabled?). The return value of find is size_t.

You can also pass the first argument as a reference and the other two as const reference.


LeetCode: Most Frequent Subtree Sum My solution to LeetCode problem Most Frequent Subtree Sum works, but I have several questions regarding the code. I am also looking for an advice on how to improve the code.

  Problem:

  Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

  Example 1

  5
 /  \
2   -3

  return [2, -3, 4], since all the values happen only once, return all of them in any order

  Example 2

  5
 /  \
2   -5

  return [2], since 2 happens twice, however -5 only occur once

My questions:

The function get_sums_freqs returns an int, but when I call it, I do not assign the result to anything: get_sums_freqs (root, sum_freqs);. Is it ok to do it this way?
For some reason, it feels like a bad style to me to initialize the hash map unordered_map<int, int> sum_freqs; in one function and then pass it to another function to fill it out. Is there a better way to do it? Or is this a correct way?

My solution:

vector<int> find_frequent_tree_sum(TreeNode* root) {

    // Collect freqs of sums into map
    unordered_map<int, int> sum_freqs;
    get_sums_freqs (root, sum_freqs);

    // Get the max freq
    int max_freq = 0;
    unordered_map<int, int>::iterator it;
    for (it = sum_freqs.begin(); it != sum_freqs.end(); ++it) {
        max_freq = max(max_freq, it->second);
    }

    // Collect all the values, which freq == max_freq
    vector<int> res;
    //unordered_map<int, int>::iterator it;
    for (it = sum_freqs.begin(); it != sum_freqs.end(); ++it) {
        if (it->second == max_freq) {
            res.push_back(it->first);
        }
    }

    return res;
}

int get_sums_freqs (TreeNode* root, unordered_map<int, int>& sum_freqs) {

    if (root) {

        int curr_sum = root->val +
            get_sums_freqs (root->left, sum_freqs) +
            get_sums_freqs (root->right, sum_freqs);

        sum_freqs[curr_sum]++;

        return curr_sum;

    } else {

        return 0;
    }
}

For context, here's the definition of TreeNode given by LeetCode:

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

The function get_sums_freqs returns an int, but when I call it, I do not assign the result to anything: get_sums_freqs (root, sum_freqs);. Is it ok to do it this way?

Your uneasiness here probably arises from the difference between a Tree and a TreeNode.  A TreeNode is an internal tree detail, which should be hidden from the user of the Tree.  I should be able to pass an Tree object to some function, and have it add some number of nodes to the Tree.  If I pass an nullptr as the TreeNode * root, the caller can't modify my tree.  Similarly, if two entities are supposed to share access to a Tree, that is fine as long as the TreeNode *root contains at least one node.  But you can't share a common empty Tree; instead you have two nullptr ... which are not "shareable".

class Tree {
    TreeNode *root;
    int num_nodes;
    int max_depth;
}

Now we have a Tree object, which can be shared ... even if it is an empty tree.  As a bonus, our Tree can hold meta-information about the tree, such as the number of nodes in the tree, the maximum depth of the tree, and so on.

The LeetCode challenge is promoting a broken tree model, by using a TreeNode * to represent a tree.  It works, but it has issues; I wouldn't want to see it used in a professional "Project".

I prefer not to walk into nullptr nodes.  Imagine:

void TreeNode::get_sums_freqs(unordered_map<int, int>& sum_freqs) { ... }

Now, you would be calling TreeNode::get_sums_freqs() with a nullptr for this, which is bad.

Instead:

int get_sums_freqs(TreeNode* node, unordered_map<int, int>& sum_freqs) {

    int curr_sum = root->val;

    if (node->left)
       curr_sum += get_sums_freqs(node->left, sum_freqs);
    if (node->right)
       curr_sum += get_sums_freqs(node->right, sum_freqs);

    sum_freqs[curr_sum]++;

    return curr_sum;
}

Note we are calling the current node node, instead of root.  We need to start off the search at the root of the tree, which is a little different:

void tree_get_sums_freqs(Tree* tree, unordered_map<int, int> &sum_freqs) {
    if (tree->root) {
       root_sum = get_sums_freqs(tree->root, sum_freqs);
       sum_freqs[root_sum]++;
    }
}

No root_sum needs to be returned from this top-level.

Of course, since LeetCode doesn't define their trees this way, you have your odd, unused return value.

  For some reason, it feels like a bad style to me to initialize the hash map unordered_map<int, int> sum_freqs; in one function and then pass it to another function to fill it out. Is there a better way to do it? Or is this a correct way?

This is fine.  It is a visitor pattern.  You create an accumulator object, and visit every node of your structure with it, to accumulate the results.


A shorter way of Enablling/Disabling a text box from RadioButton selections Three radio buttons and a text box, grouped in one group box... Just when I select one of those radio button the text box gets enabled, for the other two radio buttons it should be disabled. Here is the code that comes to mind at first, but it looks ugly to me becuase I have copy pasted the same AllowMissingData() method to Change evnt of each radio button. I was wondering if there is a better way of writing it:

private void RequiredRadioButton_CheckedChanged(object sender, EventArgs e)
{
        AllowMissingData();
}

private void AllowBlankRadioButton_CheckedChanged(object sender, EventArgs e)
{
        AllowMissingData();
}

private void SuppressRadioButton_CheckedChanged(object sender, EventArgs e)
{
        AllowMissingData();
}

private void AllowMissingData()
{
    if (AllowBlankRadioButton.Checked)
    {
        MissingDataValueTextBox.Enabled = true;
    }
    else
    {
        MissingDataValueTextBox.Text = System.String.Empty;
        MissingDataValueTextBox.Enabled = false;
    }
}

This cleans it up a little.  Removes the if statement at least:

private void AllowMissingData()
{
    MissingDataValueTextBox.Enabled = AllowBlankRadioButton.Checked;
    MissingDataValueTextBox.Text = AllowBlankRadioButton.Checked ? MissingDataValueTextBox.Text : System.String.Empty;
}


Generate out_filename from input_filename and suffix I do a lot of steps of processing over an input_file. To avoid having to think of an output_filename at every step, I created the following name generation function:

def generate_out_file(in_file, suffix='out'):
    body_str = in_file.strip('./')
    flag = '.' in body_str
    _list = body_str.split('.')
    body_list = _list[:-1] if flag else [in_file]
    extension = _list[-1] if flag else 'txt'
    out_file = '.'.join(body_list + [suffix, extension])
    if in_file.startswith('./'):
        out_file = './' + out_file
    if in_file.startswith('../'):
        out_file = '../' + out_file
    return out_file

It looks very huge for me. Can you review my code and help me to improve it?

You can dramatically simplify the function by using the os.path.splitext() instead:

import os

def generate_out_file(in_file, suffix='out'):
    """Appends '.out' to an input filename."""
    filepath, file_extension = os.path.splitext(in_file)
    return filepath + "." + suffix + file_extension

Demo:

$ ipython3 -i test.py
In [1]: generate_out_file("./file.txt")  # file in a current directory
Out[1]: './file.out.txt'

In [2]: generate_out_file("/usr/lib/file.txt")  # path to a file
Out[2]: '/usr/lib/file.out.txt'

In [3]: generate_out_file("file.txt")  # just a file name
Out[3]: 'file.out.txt'

In [4]: generate_out_file("file")  # no extension
Out[4]: 'file.out'

In [5]: generate_out_file("/usr/lib/file")  # no extension with a path
Out[5]: '/usr/lib/file.out'


Real World Business App A friend and I at IT school tasked ourselves with writing something just for the hell of it. Trying to simulate in a very basic way something that you may want to do in the real world. We thought of the following problem that we could solve ourselves.

X, Y and X INC is in need of a program. They wish to promote the sales of their products in bigger quantity. They wish to give the following discounts to promote better sales.

If 1 to a 100 of a certain item is sold the company wishes to grant a 10 percent discount.
If the amount of the product sold is between 101 and 200 the company wishes to grant a 12 percent discount.
If the amount of the product sold is between 201 and 500 the company wishes to grant a 15 percent discount
If the amount of product sold is greater than 500 the discount should be 20 percent.

The program should take a price input and a quantity input and should give a total with the applicable discount to the end user without divulging the percentage of the discount.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiscountApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the quanitity of the product bought.");
            var x = Console.ReadLine();
            int x1 = int.Parse(x);

            Console.WriteLine("Please enter the price of the product bought.");
            var y = Console.ReadLine();
            double y1 = double.Parse(y);

            double discount = 0;
            double outValue = 0;

            if (x1 <= 100)
            {
                discount = 0.1;
                outValue = returnTotal(discount, y1, x1);
                Console.WriteLine("The total with the discount is R{0}",outValue);
            }
            else if (x1 > 100 && x1 <= 200)
            {
                discount = 0.12;
                outValue = returnTotal(discount, y1, x1);
                Console.WriteLine("The total with the discount is R{0}",outValue);
            }
            else if (x1 > 200 && x1 <= 500)
            {
                discount = 0.15;
                outValue = returnTotal(discount, y1, x1);
                Console.WriteLine("The total with the discount is R{0}",outValue);
            }
            else
            {
                discount = 0.2;
                outValue = returnTotal(discount, y1, x1);
                Console.WriteLine("The total with the discount is R{0}",outValue);
            }

        }
        public static double returnTotal(double discount, double price, int quantity)
        {
            double Total = (price * quantity);
            double discountTotal = Total - (Total * discount);
            return discountTotal;
        }

    }

}

I'm not sure if a switch statement would be better. I'm not entirely sure how you would do multiple conditions in the switch statement.

If you do the checks in ascending order, you don't need greater then checks.
Since the only difference is the value of discount, you could use a dictionary.

static void Main(string[] args)
{
    Console.WriteLine("Please enter the quanitity of the product bought.");
    var x = Console.ReadLine();
    int x1 = int.Parse(x);

    Console.WriteLine("Please enter the price of the product bought.");
    var y = Console.ReadLine();
    double y1 = double.Parse(y);

    Dictionary<int, double> discountLevels = new Dictionary<int, double>
    {
        {100, 0.1},
        {200, 0.12},
        {500, 0.15}
    };

    double discount = 0.2;
    foreach (var discountLevel in discountLevels.OrderBy(discountLevel => discountLevel.Key))
    {
        if (x1 <= discountLevel.Key)
        {
            discount = discountLevel.Value;
            break;
        }
    }

    double outValue = 0;
    outValue = returnTotal(discount, y1, x1);
    Console.WriteLine("The total with the discount is R{0}", outValue);
}

The OrderBy ensures that the checks are done in the correct order.


Excel 2016 VBA - Show/Hide multiple shape groups I have the following code I'm using to show/hide multiple shape groups in Excel 2016 using VBA and macros:

   Sub Pic_1_SA_click()
   ActiveSheet.Shapes("Group 23").Visible = True
   ActiveSheet.Shapes("Group 71").Visible = False
   ActiveSheet.Shapes("Group 19").Visible = False
   ActiveSheet.Shapes("Group 20").Visible = False
   End Sub

   Sub Pic_1_SB_click()
   ActiveSheet.Shapes("Group 23").Visible = False
   ActiveSheet.Shapes("Group 71").Visible = True
   ActiveSheet.Shapes("Group 19").Visible = False
   ActiveSheet.Shapes("Group 20").Visible = False
   End Sub

   Sub Pic_2_SA_click()
   ActiveSheet.Shapes("Group 23").Visible = False
   ActiveSheet.Shapes("Group 71").Visible = False
   ActiveSheet.Shapes("Group 19").Visible = True
   ActiveSheet.Shapes("Group 20").Visible = False
   End Sub

   Sub Pic_2_SB_click()
   ActiveSheet.Shapes("Group 23").Visible = False
   ActiveSheet.Shapes("Group 71").Visible = False
   ActiveSheet.Shapes("Group 19").Visible = False
   ActiveSheet.Shapes("Group 20").Visible = True
   End Sub

Now the above is somewhat tedious if I plan to add more buttons. Is there any way to do this more efficiently?

The simple answer is to use pass an array of names to the Shapes.Range, hide all 4 Groups, and then make the one Group visible.

ActiveSheet.Shapes.Range(Array("Group 19", "Group 20", "Group 23", "Group 71")).Visible = msoTrue
ActiveSheet.Shapes("Group 20").Visible = msoFalse

Reference: MSDN - Shapes.Range Property(Excel)

Considering that all Group default names start with "Group ", you could further simplify it by creating a function that will return the ShapeRange based of the Group number.

Public Function getGroupRange(ws As Worksheet, ParamArray GroupNames() As Variant) As ShapeRange
    Dim n As Long
    For n = 0 To UBound(GroupNames)
        If IsNumeric(GroupNames(n)) Then GroupNames(n) = "Group " & GroupNames(n)
    Next
    Set getGroupRange = ws.Shapes.Range(GroupNames)

End Function

Sub Pic_1_SA_click()
    getGroupRange(ActiveSheet, 19, 20, 23, 71).Visible = msoFalse
    getGroupRange(ActiveSheet, 23).Visible = msoTrue
End Sub

Sub Pic_1_SB_click()
    getGroupRange(ActiveSheet, 19, 20, 23, 71).Visible = msoFalse
    getGroupRange(ActiveSheet, 71).Visible = msoTrue
End Sub

Sub Pic_2_SA_click()
    getGroupRange(ActiveSheet, 19, 20, 23, 71).Visible = msoFalse
    getGroupRange(ActiveSheet, 19).Visible = msoTrue
End Sub

Sub Pic_2_SB_click()
    getGroupRange(ActiveSheet, 19, 20, 23, 71).Visible = msoFalse
    getGroupRange(ActiveSheet, 20).Visible = msoTrue
End Sub


Data flow anomaly: how to do it correct? I am modifying Volley for Android a bit and Findbugs complains about the data flow and I am a bit lost. First the code:

String userAgent;
try {
    String packageName = getPackageName();
    PackageInfo info = getPackageManager().getPackageInfo(packageName, 0);
    userAgent = packageName + "/" + info.versionCode; // DD
} catch (PackageManager.NameNotFoundException e) {
    userAgent = "volley/0";
}

HttpStack stack;
if (Build.VERSION.SDK_INT >= 9) {
    stack = new HurlStack();
} else {
    stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}

So I thought that findbugs would differ between definition and declaration of a variable which should make the DD gone.

I also tried to predefine the userAgent with the content from the catch but an empty catch is bad practice as well. Also findbugs just complains with the data flow anomalies just on different places...

So what would be a good solid way to prevent the findbugs reports?

It would be bad practice to silently swallow an exception.  However, I think the following code would be acceptable:

String userAgent = "volley/0";  // Default value
try {
    String packageName = getPackageName();
    PackageInfo info = getPackageManager().getPackageInfo(packageName, 0);
    userAgent = packageName + "/" + info.versionCode;
} catch (PackageManager.NameNotFoundException justUseDefaultUserAgent) {
}

For the second snippet, I would use a ternary conditional to emphasize the goal of assigning stack a value no matter what.

HttpStack stack = (Build.VERSION.SDK_INT >= 9) ? new HurlStack() :
    new HttpClientStack(AndroidHttpClient.newInstance(userAgent));


Output strings from a set in lexicographical order Puzzle Description:

  You are given 'n' strings w1, w2, ......, wn. Let Si denote the set of strings formed by considering all unique substrings of the string wi. A substring is defined as a contiguous sequence of one or more characters in the string. More information on substrings can be found here. Let 'S' = {S1 U S2 U .... Sn} .i.e 'S' is a set of strings formed by considering all the unique strings in all sets S1, S2, ..... Sn. You will be given many queries and for each query and an integer 'k'. Your task is to output the lexicographically kth smallest string from the set 'S'.

  Input:

  The first line of input contains a single integer 'n', denoting the number of strings. Each of the next 'n' lines consists of a string. The string on the ith line (\$1 <= i<= n\$) is denoted by wi and has a length mi. The next line consists of a single integer 'q', denoting the number of queries. Each of the next 'q' lines consists of a single integer 'k'.
  Note: The input strings consist only of lowercase English alphabets 'a' - 'z'.

  Output:

  Output 'q' lines, where the ith line consists of a string which is the answer to the ith query. If the input is invalid ('k' > |S|), output "INVALID" (quotes for clarity) for that case.

  Constraints:

  \$1 <= n <= 50\$
  \$1 <= mi <= 2000\$
  \$1 <= q<= 500\$
  \$1 <= k<= 1000000000\$

  Sample Input:

2
aab
aac
3
3
8
23

  Sample Output:

aab
c
INVALID

  Explanation:

  For the sample test case, we have 2 strings "aab" and "aac".

  S1 = {"a", "aa", "aab", "ab", "b"} . These are the 5 unique substrings of "aab".

  S2 = {"a", "aa", "aac",  "ac", "c" } . These are the 5 unique substrings of "aac".

  Now, S = {S1 U S2} = {"a", "aa", "aab", "aac", "ab", "ac", "b", "c"}. Totally, 8 unique strings are present in the set 'S'.

  The lexicographically 3rd smallest string in 'S' is "aab" and the lexicographically 8th smallest string in 'S' is "c". Since there are only 8 distinct substrings, the answer to the last query is "INVALID".

  Time-limit: 5 secs

import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeSet;

public class find_str {

    private static final String INVALID = "INVALID";
    private TreeSet<String> mainset = new TreeSet<String>();
    private ArrayList<String> array = new ArrayList<String>();
    private String[] main_ary;
    private int length;
    public static void main(String args[]) {
        find_str fin = new find_str();
        Scanner scanner = new Scanner(System.in);
        int num_of_strings = scanner.nextInt();
        for (int i = num_of_strings; --i >=0;) {
            fin.process(scanner.next());
        }
        fin.initialize();
        int num_of_queries = scanner.nextInt();
        for (int i = num_of_queries; --i >=0;) {
            System.out.println(fin.query(scanner.nextInt()-1));
        }
    }

    private String query(int index) {
        if (index < length) {
            return main_ary[index];
        } else {
            return INVALID;
        }
    }

    private void process(String input) {
        int len = input.length();
        for (int i = 0; i < len; i++) {
            for (int j = i; j < len; j++) {
                mainset.add(input.substring(i, j + 1));
            }
        }
    }

    private void initialize() {
      length=mainset.size();
        main_ary=(String[]) mainset.toArray(new String[length]);
    //    array.addAll(mainset);
    }
}

This was written to solve puzzle only
First I thought of creating separate sets for each string and then later unionize all them to get final mainset and then sort them using custom comparator if necessary and later can be retrieved with index.
Later without doing all this nonsense, created tree-set which is populated with substrings on the run, thus combined process of unionizing and sorting.
For retrieving through index I had to make an ArrayList with contents of mainset.  I guess this doesn't take much time or memory than other process.

Just formal way :

Use TreeSet<String> ts to store S = {S1 U S2} :

if String is already stored, it returns false,
you can use ts.toString() to print all values of the Set, separated by ', ' between '[]'
you have addAll(..), containsAll(..), retainAll(..), ... ready made [and optimized] other tools.
You can put in Collections.synchronizedSet(s) if you have multi threaded concurrrent jobs.

You can rebuilt/combine your code from JVM, not only from mathematical constraints. ... wheels exist from long time.


Find all the missing number(s) Recently I've attended an interview, where I faced the below question:

  Question: "There is an sorted array. You need to find all the missing numbers. Write the complete code, without using any generics
  or inbuilt function or binary operators. First and last terms will be
  given. Array will be sorted. Array always starts with zero."

  Example:

Input:
int array[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };

Output:
Missing number(s): 5, 16, 17, 19, 22.

  If its single missing term, we can calculate the required total using
  summation formula, and find the difference between the actual total.
  Which gives the missing term.

Since there are multiple values missing, I came up with below approach.

Code:

public class MissingNumber {

    public static int count = 0;
    public static int position = 0;
    public static boolean flag = false;

    public static void main(String[] args) {

        int a[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };

        findMissingNumbers(a, position);

    }

    private static void findMissingNumbers(int a[], int position) {

        if (position == a.length - 1)
            return;

        for (; position < a[a.length - 1]; position++) {

            if ((a[position] - count) != position) {
                System.out.println("Missing Number: " + (position + count));
                flag = true;
                count++;
                break;
            }
        }

        if (flag) {
            flag = false;
            findMissingNumbers(a, position);
        }
    }

}

Output:

Missing Number: 5
Missing Number: 16
Missing Number: 17
Missing Number: 19
Missing Number: 22

This gives the required solution. But, is the code fine or can this be done with a better approach?

The problem as stated was:

  There is an sorted array. You need to find all the missing numbers. Write the complete code, without using any generics or inbuilt function or binary operators. First and last terms will be given. Array will be sorted. Array always starts with zero.

When I ask questions like this in interviews, one of the things that I'm looking for is can the candidate read a specification and make good decisions on implementing it?  The spec says what the inputs are and what the outputs are, so I would expect that somewhere in the code there would be a method with signature

int[] findMissingElements(int[] elements, int first, int last)

Note that the method is not void. This idea that a method prints out its result is found only in interviews and college assignments; it is nowhere found in industry.

I would also like to see some verification of the method preconditions given.  If the method is private then an assertion is appropriate. I'd also like to see the candidate take initiative to add some more preconditions that I did not give. I often give underspecified problems to see how the candidate deals with ambiguity: by asking clarifying questions, or by ignoring the problem and hoping for the best. In this case it is not stated that first is less than or equal to last but it seems reasonable to assume that.

int[] findMissingElements(int[] elements, int first, int last)
{
    assert(elements.Count > 0);
    assert(isSorted(elements));
    assert(elements[0] == 0);
    assert(first <= last);

If the method is public then these should be if(!precondition) throw ...


Python code for mad libs game I was doing a simple mad libs game thing but I want to know if there's any more efficient or readable way to write the code as I don't know the best ways to structure code as I am just begginning. Before I write any more of them please can someone tell me if there's a "better" or more accpeted way to write any of the code like if I should make more things in to functions and how to do so.
This is Python 3.6.6. The game is supposed to prompt the user to enter a random word of their choice (it has to be a certain type of word to make sense in the sentence like adjective or verb) and inputs the prompted words into a sentence so it's funny and doesn't make any sense

import random

print("<<<<<<<<<<<<<<<<<<<<<<<<< Mad Libs >>>>>>>>>>>>>>>>>>>>>>>>>")
adjective = []
noun = []
verb_pr = []
noun_p = []
verb_pa = []
verb = []
def nouns():
    global noun
    ans = input("Noun(singular):\n> ").lower()
    noun.append(ans)

def nouns_p():
    global noun_p
    ans = input("Noun(plural):\n> ").lower()
    noun_p.append(ans)

def adjectives():
    global adjective
    ans = input("Adjective:\n> ").lower()
    adjective.append(ans)

def verbs_pr():
    global verb_pr
    ans = input("Verb(-ing):\n> ").lower()
    verb_pr.append(ans)

def verbs_pa():
    global verb_pa
    ans = input("Verb(-ed):\n> ").lower()
    verb_pa.append(ans)

def verbs():
    global verb
    ans = input("Verb:\n> ").lower()
    verb.append(ans)

verbs_pr()
nouns_p()
nouns()
nouns()
verbs_pr()
nouns_p()
verbs_pa()
verbs()
nouns_p()
adjectives()
verbs_pr()
nouns_p()
verbs_pr()

random.shuffle(adjective)
random.shuffle(noun)
random.shuffle(verb_pr)
random.shuffle(noun_p)
random.shuffle(verb_pa)
random.shuffle(verb)

print("{3[0]} these {2[0]}, {1[0]} like a {1[1]}, I'm {3[1]} {2[1]} now, someone {4[0]} me do I {5[0]} {2[2]}, it's gonna be {0[0]}, {3[2]} {2[3]} that's what I'm {3[3]} about yeah".format(adjective,noun,noun_p,verb_pr,verb_pa,verb))

adjective = []
noun = []
verb_pr = []
noun_p = []
verb_pa = []
verb = []
verbs_pa()
nouns()
adjectives()
adjectives()
verbs_pr()
nouns()
verbs()
nouns_p()
verbs_pa()
nouns()
nouns()
nouns()
nouns()
adjectives()
nouns_p()
verbs()
nouns()
nouns()
adjectives()
nouns_p()
nouns()
nouns()
nouns()
verbs()

random.shuffle(adjective)
random.shuffle(noun)
random.shuffle(verb_pr)
random.shuffle(noun_p)
random.shuffle(verb_pa)
random.shuffle(verb)
print("""You have been {4[0]} into Hogwarts {1[0]} of {0[0]} and {0[1]}. You will be {2[0]} throughout the {1[1]} and will {5[0]} in the {3[0]}. You will be {4[1]} in one of the four houses.
{1[2]}, {1[3]}, {1[4]} or {1[5]} and will learn much about the {0[2]} {3[1]}. Once you arrive you will {5[1]} The Great {1[6]} for a feast with the headmaster, Proffessor
{1[7]}. You will need to get all the {0[3]} {3[2]} in {1[8]} Alley and get a {1[9]} from Ollivanders {1[10]} shop. We hope to {5[2]} you there.""".format(adjective,noun,verb_pr,noun_p,verb_pa,verb))

That works, but obviously, the code is repetitive, and a lot of work to maintain.  To prepare each Mad Lib, you have to count the number of each type of blank, to make the required number of prompts.  Then, you fill in the blanks using str.format(…) with some rather cryptic placeholders in the format string.

A smarter approach would be to have the computer do most of that work for you, so that you only need to supply a template in some human-friendly format, and the code figures out the necessary prompts.  That would necessitate a complete rewrite of the code.

Furthermore, you should avoid making separate lists for each part of speech, because that forces you to write separate code to handle each part of speech.  Rather, you should store the words in a dictionary, with the parts of speech as
keys, and list of words as values.  (More specifically, you can use a defaultdict to ensure that each key is initially associated to an empty list.)  Storing the data in a dictionary would also help you avoid the nasty use of global variables.

Suggested solution

This solution uses regular expressions to analyze the template and perform the word substitutions.

from collections import defaultdict
import random
import re

def mad_lib(template):
    blanks = re.findall(r'\{(.*?)\}', template)
    random.shuffle(blanks)
    words = defaultdict(list)
    for part_of_speech in blanks:
        words[part_of_speech].append(input(part_of_speech + ":\n> "))
    for answers in words.values():
        random.shuffle(answers)
    return re.sub(
        r'\{(.*?)\}',
        lambda match: words[match.group(1)].pop(),
        template
    )

print("<<<<<<<<<<<<<<<<<<<<<<<<< Mad Libs >>>>>>>>>>>>>>>>>>>>>>>>>")

print(mad_lib(
    "{Verb(-ing)} these {Noun(plural)}, {Noun} like a {Noun}, I'm {Verb(-ing)} {Noun(plural)} now, someone {Verb(-ed)} me do I {Verb} {Noun(plural)}, it's gonna be {Adjective}, {Verb(-ing)} {Noun(plural)} that's what I'm {Verb(-ing)} about yeah"
))

print(mad_lib(
    """You have been {Verb(-ed)} into Hogwarts {Noun(singular)} of {Adjective} and {Adjective}. You will be {Verb(-ing)} throughout the {Noun(singular)} and will {Verb} in the {Noun(plural)}. You will be {Verb(-ed)} in one of the four houses.
{Noun(singular)}, {Noun(singular)}, {Noun(singular)} or {Noun(singular)} and will learn much about the {Adjective} {Noun(plural)}. Once you arrive you will {Verb} The Great {Noun(singular)} for a feast with the headmaster, Proffessor
{Noun(singular)}. You will need to get all the {Adjective} {Noun(plural)} in {Noun(singular)} Alley and get a {Noun(singular)} from Ollivanders {Noun(singular)} shop. We hope to {Verb} you there."""
))


Use of getters and setters with a car information example I have very quickly mocked this up as an example model in Angular JS:

.factory('car', function() {
  function car(serial, name, type, manufacturer)
    //intended to be private
    var serial = serial;
    var name = name;
    var type = type;
    var manufacturer = manufacturer;

    this.getSerial = function() {
      return this.serial;
    }

    this.setSerial = function(newSerial) {
      this.serial = newSerial;
    }
});

There would be getters and setters for every property, and there is a legitimate need for getters and setters for all of them.

I am not a hardcore JavaScript developer, but I have been reading that providing getters and setters for every property is bad practice and providing them in general is bad practice.

Let's say there is a legitimate need for getters and setters for all of the properties, is it still bad practice?
Would other developers do it another way? I have also seen developers writing about it doing in completely different ways

I am after encapsulation of these properties and I assume that this is a good way to go about it.

JavaScript provides a analogy to private properties, but you should think of them as hidden as they do not behave as private properties. Protoptyped methods do not have access to hidden properties.

Properties defined with the "this" token are public and can be accessed anywhere the object can be accessed. Private properties are declared with the var token or as the objects passed parameters and should never require direct getting and setting

function MyObject (id, name) {
    this.id = id;                     // create public property
    var displayVal = "Hi I am "+name; // create Hidden property
    this.display = function () {      // create public function
         console.log(displayVal);     // this function closes over displayVal
    }
    // closure closes over all currently scoped variables thus
    this.displayName = function () {
         console.log(name)     // the argument passed to this object is also
                               // available as a hidden property
    }
}
MyObject.prototype.test = function () { // this prototype does not close over
                                        // the property displayVal
      // the next line will display undefined
      console.log(displayVal);  // undefined
}
var myObj = new MyObject(0, "OBJECT"); // creates a new object
console.log("Public id = " + myObj.id);  // accessing public property
myObj.display();                         // display private property

// hidden properties are not enumerable
for(var i in myObj){
    console.log(i + " as " + (typeof myObj[i]) );    // will report
                       // id as number
                       // display as function
                       // displayName as function
                       // test as function
}
// Note no hidden variables are displayed

JavaScript is a classless language and attempting to transfer class like concepts to it from other languages is bad practice. Use closure to define private (hidden) properties.

Object factories in my view are bad design, they slow down an already slow language and provide no extra benefit to the code.


Iterate through Expression Tree I'm trying to build an iterator (enumerator) that can select specific elements in an Expression tree by traversing the tree and deferring further iteration until needed.

My following implementation intends to keep it simple by leveraging the ExpressionVisitor. But since a visitor-pattern uses recursive stack calls to keep its place, I am using a Task thread in a synchronous manner to store the position of the IEnumerator between calls to MoveNext.

/// <summary>
/// Iterates through an expression tree collecting only expression elements that match the predicate.
/// </summary>
internal sealed class ExpressionCollector : IEnumerable<Expression>
{
    private ExpressionCollector(Expression root, Func<Expression, bool> predicate)
    {
        this.Root = root;
        this.Predicate = predicate;
    }

    private Expression Root { get; }
    private Func<Expression, bool> Predicate { get; }

    public static IEnumerable<Expression> Collect(Expression root, Func<Expression, bool> predicate)
        => new ExpressionCollector(root, predicate);

    public IEnumerator<Expression> GetEnumerator() => new Iterator(this);
    IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();

    private class Iterator : ExpressionVisitor, IEnumerator<Expression>
    {
        private Task itr;
        private CancellationTokenSource cancel;
        private TaskCompletionSource<Expression> found;
        private TaskCompletionSource<bool> isReady;

        public Iterator(ExpressionCollector owner) { this.Owner = owner; }

        public ExpressionCollector Owner { get; }

        public Expression Current { get; private set; }
        object IEnumerator.Current => this.Current;

        public void Dispose() => this.Reset();
        public bool MoveNext()
        {
            if (this.found is null || this.found.Task.IsCompleted)
                this.found = new TaskCompletionSource<Expression>();

            if (this.itr is null)
                this.itr = Task.Run(Iterate, (cancel = new CancellationTokenSource()).Token);

            this.isReady?.SetResult(true);
            switch (Task.WaitAny(itr, found.Task))
            {
                case 0:
                    this.Current = null;
                    this.found = null;
                    return false;
                case 1:
                    this.Current = found.Task.Result;
                    this.found = null;
                    return true;
                default: throw new NotSupportedException();
            }
        }
        public void Reset()
        {
            if (this.itr != null)
            {
                this.cancel.Cancel();
                this.itr.Wait();

                this.itr.Dispose();
                this.itr = null;

                this.cancel.Dispose();
                this.cancel = null;

                this.Current = null;
            }
        }

        private void Iterate() => this.Visit(this.Owner.Root);
        public override Expression Visit(Expression node)
        {
            if (cancel.IsCancellationRequested)
                cancel.Token.ThrowIfCancellationRequested();

            if (this.Owner.Predicate(node))
            {
                this.isReady = new TaskCompletionSource<bool>();
                this.found.SetResult(node);
                this.isReady.Task.Wait();
            }

            return base.Visit(node);
        }
    }
}

My concern stems from whether or not I am using the Task properly.
Any thoughts?

Just some thoughts:

Not sure why you don't just flatten the expression tree with a visitor and then return the collection of expressions. This leads to simpler code:

class Program
{
    static void Main(string[] args)
    {
        Expression<Func<int, int, int>> expr = (a, b) => ((a + b) * (a - b));

        //Flatten the entire tree.
        foreach (var elem in expr.Flatten())
        {
            Console.WriteLine(elem.NodeType);
        }

        //Use Linq to select what you want.
        foreach (var elem in expr.Flatten().Where(t => t.NodeType == ExpressionType.Parameter))
        {
            Console.WriteLine(elem.NodeType);
        }
        Console.ReadKey();
    }
}

public static class ExpressionExtensions
{
    public static IEnumerable<Expression> Flatten(this Expression expr)
    {
        return Visitor.Flatten(expr);
    }
}

public sealed class Visitor : ExpressionVisitor
{
    private readonly Action<Expression> nodeAction;

    private Visitor(Action<Expression> nodeAction)
    {
        this.nodeAction = nodeAction;
    }

    public override Expression Visit(Expression node)
    {
        nodeAction(node);
        return base.Visit(node);
    }

    public static IEnumerable<Expression> Flatten(Expression expr)
    {
        var ret = new List<Expression>();
        var visitor = new Visitor(t => ret.Add(t));
        visitor.Visit(expr);
        return ret;
    }
}

Even if, for some reason, you absolutely need to have lazy execution, you're better off making your own expression iterator, rather than trying to pause the execution of a class meant to eagerly visit everything.


2D Convex hull exercise I'm reading Real World Haskell, and this is my first try with the language.

This is the result of the exercises of chapter 3:

  Consider three two-dimensional points a, b, and c. If we look at the angle formed by the line segment from a to b and the line segment from b to c, it either turns left, turns right, or forms a straight line. Define a Direction data type that lets you represent these possibilities.
  Write a function that calculates the turn made by three 2D points and returns a Direction.
  Define a function that takes a list of 2D points and computes the direction of each successive triple. Given a list of points [a,b,c,d,e], it should begin by computing the turn made by [a,b,c], then the turn made by [b,c,d], then [c,d,e]. Your function should return a list of Direction.
  Using the code from the preceding three exercises, implement Graham's scan algorithm for the convex hull of a set of 2D points. You can find good description of what a convex hull is, and how the Graham scan algorithm should work.

For short, the Graham scan algorithm is:

find the point \$P\$ with the smallest \$y\$
sort the points \$A\$ according to the angle \$(Ox, PA)\$ and add P at the end
in the sorted list, form the turns \$(A_{i-1}, A_i, A_{i+1})\$ and
remove the points \$A_i\$ for which it is a "turn right".

Now my code is the following:

import Data.List
-- 9
data Direction = TurnLeft
               | TurnRight
               | StraightLine
                 deriving (Show, Eq)

-- 10
data Point = Point {
      x :: Float
    , y :: Float
    } deriving (Show, Eq)

turn :: Point -> Point -> Point -> Direction
turn a b c
      | z > 0     = TurnLeft
      | z < 0     = TurnRight
      | otherwise = StraightLine
    where
      bax = x a - x b
      bay = y a - y b -- coordinates of b->a
      bcx = x c - x b
      bcy = y c - y b -- coordinates of b->c
      z   = bax * bcy - bcx * bay

-- 11
turns :: [Point] -> [Direction]
turns []         = []
turns [_]        = []
turns [_,_]      = []
turns (x:y:z:zs) = (turn x y z) : (turns (y:z:zs))

-- 12
angle :: Point -> Point -> Point -> Float
angle a b c = - (bax * bcx + bay * bcy) /
              (sqrt ((bax * bax + bay * bay) * (bcx * bcx + bcy * bcy)))
    -- more efficient than acos for the algorithm and is the same for sorting
    where
      bax = x a - x b
      bay = y a - y b -- coordinates of b->a
      bcx = x c - x b
      bcy = y c - y b -- coordinates of b->c

argmin :: Ord b => (a -> b) -> [a] -> a
argmin _ []  = error "empty list"
argmin f (x:xs)
    | null xs = x
    | (f x) < (f argminrest) = x
    | otherwise              = argminrest
    where argminrest = argmin f xs

hull :: [Point] -> [Point]
hull pts =
    origin : ((map snd (filter keepPt results)) ++ [origin])
     where origin  = argmin y pts
           oxaxis  = Point (1 + x origin) (y origin)
           oxangle = angle oxaxis origin
           compare_angle pt1 pt2 = compare (oxangle pt1) (oxangle pt2)
           list    = reverse (sortBy compare_angle pts)
           -- origin is the first element of the list
           results = zip (turns (list ++ [origin])) (drop 1 list)
           keepPt (dir, _) = dir /= TurnRight

It works, at least according to the following unit test:

hull [(Point (-3) 1),(Point (-4) 1),(Point (-1) 4),(Point 0 0),(Point 2 2),(Point (-1) 3),(Point (-1) 2),(Point 1 0),(Point 3 (-1)),(Point (-1) (-1))]

which gives

[Point {x = -1.0, y = -1.0},Point {x = -3.0, y = 1.0},Point {x = -1.0, y = 2.0},Point {x = -1.0, y = 3.0},Point {x = -1.0, y = 4.0},Point {x = 2.0, y = 2.0},Point {x = 3.0, y = -1.0},Point {x = -1.0, y = -1.0}]

Is it an idiomatic code? How would you improve it?

Terminology

In your hull function, you use the name origin to indicate the chosen point with the minimum y coordinate.  That's confusing, as the term usually means the point (0, 0) in the Cartesian plane.  For the rest of this review, I'm going to refer to the chosen point as the pivot instead.

Wrong result

The test result that you quoted in your own question shows that the algorithm is incorrect!

Furthermore, when I ran your code with the suggested test case, I got a totally different result than what you claimed, which makes it hard for me to explain exactly what went wrong.  (The code produces results in clockwise order, contrary to your claimed answer which lists them in counterclockwise order.  I seriously doubt that you posted the question correctly.)  I can, however, point to four issues:

(drop 1 list) was responsible for removing (-4, 1) from consideration.
A correct traversal involves backtracking whenever a right turn occurs.  Therefore, you must filter the candidate points while you traverse the list.  You cannot simply traverse the list and keep just the vertices where a left turn occurred, since a left turn that occurs at an interior point doesn't mean that it is a vertex of the convex hull.
Reporting points that lie collinearly on the convex hull (but not at a vertex) is a difficult task with this algorithm, since it is hard to determine in advance the order in which to consider such points such that they will be guaranteed to be part of a left-turn-only tour.
Degenerate cases are poorly handled.  hull of a single point lists that point twice.  hull of a triangle can also list the pivot twice.

Implementation

Stuff like this is hard to follow:

angle :: Point -> Point -> Point -> Float
angle a b c = - (bax * bcx + bay * bcy) /
              (sqrt ((bax * bax + bay * bay) * (bcx * bcx + bcy * bcy)))
    -- more efficient than acos for the algorithm and is the same for sorting
    where
      bax = x a - x b
      bay = y a - y b -- coordinates of b->a
      bcx = x c - x b
      bcy = y c - y b -- coordinates of b->c

A remedy is to use a vector package to allow you to think at a more abstract level.

angle a b c :: Vector2 -> Vector2 -> Vector2 -> Double
angle a b c = (ab `vdot` bc) / ((vmag ab) * (vmag bc))
  where
    ab = b - a
    bc = c - b

In the implementation below, I've rewritten the function further, restricting it to only compare a single vector against \$\mathbf{\hat{x}}\$, and renaming it to cosAngleX to be more honest.

You don't really need to define the argmin function.  argmin y pts could just be written as minimumBy (comparing y) pts, using support from Data.List.

Suggested solution

import Data.List (minimumBy, sortBy)
import Data.Ord (comparing)

-- https://hackage.haskell.org/package/AC-Vector
import Data.Vector.Class (vdot, vmag)
import Data.Vector.V2 (Vector2(..), v2x, v2y)
import Data.Vector.V3 (Vector3(..), v3z, vcross)

data Direction = TurnLeft
               | TurnRight
               | StraightLine
                 deriving (Show, Eq)

-- Direction of the turn when travelling from a to b to c
turn :: Vector2 -> Vector2 -> Vector2 -> Direction
turn a b c
  | z > 0     = TurnLeft
  | z < 0     = TurnRight
  | otherwise = StraightLine
  where
    ba = a - b
    bc = c - b
    promote23 (Vector2 x y) = Vector3 x y 0
    z = v3z ((promote23 bc) `vcross` (promote23 ba))

-- Cosine of the angle that a vector forms with the X axis.
-- We can sort by this instead of sorting by the angle as long as all vectors
-- have a nonnegative y coordinate (which is the case, since we picked a point
-- with the minimum y coordinate as the pivot).
-- For (Vector2 0 0), the result is Infinity
cosAngleX :: Vector2 -> Double
cosAngleX v
  | norm == 0  = 1/0
  | otherwise  = (v `vdot` xHat) / norm
  where
    xHat = Vector2 1 0
    norm = vmag v

giftWrap :: [Vector2] -> [Vector2]
giftWrap vs = result
  where
    -- Decides whether to keep or reject vertex b.
    -- Vertex b is provisionally kept if a left turn occurs there; the result
    -- is finalized only when a closed left-turn-only tour is completed.
    giftWrap' (a:b:c:vs)
      | vs == [] && dir == TurnLeft  = (True, [b, c])
      | vs == []                     = (False, [c])
      | dir == TurnLeft && final     = (True, (b:gw))
      | dir == TurnLeft              = giftWrap' (a:gw)
      | otherwise                    = (False, (a : c : vs))
      where
        dir = turn a b c
        (final, gw) = giftWrap' (b:c:vs)
    (_, result) = giftWrap' (vs ++ [head vs])

-- Chooses the point with the smallest y coordinate (breaking ties by smallest
-- x coordinate), then presents the points by the angle between the x axis,
-- the pivot, and each point.  The pivot will be the last element of the
-- resulting list.
chain :: [Vector2] -> [Vector2]
chain pts = sortBy (comparing byAngleX) pts
  where
    comparing2 primaryKey secondaryKey a b
      | firstCmp == EQ  = comparing secondaryKey a b
      | otherwise       = firstCmp
      where firstCmp = comparing primaryKey a b
    pivot      = minimumBy (comparing2 v2y v2x) pts
    byAngleX v = -cosAngleX (v - pivot)

-- Convex hull in some counter-clockwise order
hull :: [Vector2] -> [Vector2]
hull (a:[])    = [a]
hull (a:b:[])  = [a, b]
hull vs        = giftWrap $ chain vs

The test case:

*Main> hull [(Vector2 (-3)   1),  (Vector2 (-4) 1),   (Vector2 (-1)  4),
             (Vector2   0    0),  (Vector2   2  2),   (Vector2 (-1)  3),
             (Vector2 (-1)   2),  (Vector2   1  0),   (Vector2   3 (-1)),
             (Vector2 (-1) (-1))]
[Vector2 {v2x = 3.0, v2y = -1.0}, Vector2 {v2x = 2.0, v2y = 2.0},
 Vector2 {v2x = -1.0, v2y = 4.0}, Vector2 {v2x = -4.0, v2y = 1.0},
 Vector2 {v2x = -1.0, v2y = -1.0}]


Simple ES6 Truncate method for character, word, and sentence limits Simple truncating method for characters, words, and sentences for a personal utility library I've been working on.

Improvements & criticism welcomed! Especially around default param usage, as I've not utilized it much to date.

const truncate = ((
  value = '',
  int = 0,
  elipsis = '\u2026', /* ... */
  prune = (val, num, at) => val.split(at).splice(0, num).join(at)
) => {
  const sentences = (val = value, num = int, end = elipsis) => prune(val, '.', num) + end;
  const words = (val = value, num = int, end = elipsis) => prune(val, ' ', num) + end;
  const characters = (val = value, num = int, end = elipsis) => val.substring(0, num) + end;
  return {sentences, words, characters};
})();

console.clear();
console.log([
  truncate.sentences("This is a sentence. There are many like it but you won't see the 2nd one", 1, '.'),
  truncate.words("These are words but you won't see what's after this because it'll be hidden", 10),
  truncate.characters("This won't exceed 31 characters so we cutting off the ending", 31, '!')
]);

The parameters of sentences and words appear to be out of order when passed to prune(). Not sure why the parameters passed to prune are hard-coded at the example, though still passed to prune(). Since words does not pass a parameter for at, 10 is used, which is not the expected result, though can be remedied by defining the parameter at at words and sentences functions, given that each function call expects all three parameters, and at is not defined at any of the functions at the code at the question; instead num is set to int.

Adjusted body of prune to include an immediately invoked arrow function to handle the resulting array of .split() where delimiter character ! is not contained in string by checking if the element at index 0 of array is equal to val, if true spread val to array else use existing array to chain .splice() to, then concatenate an empty string or at following .join() call. At which point the same function can be substituted for sentences, words and characters.

const truncate = ((
  value = '',
  int = 0,
  elipsis = '\u2026', /* ... */
  prune = (val, at, num) =>
            ((s, k = s[0] === val) =>
              `${(k ? [...val] : s)
                 .splice(0, num)
                 .join(k ? '' : at)}${k ? at : ''}`)
            (val.split(at))
) => {
  const sentences = (val = value, at, num = int, end = elipsis) => prune(val, at, num) + end;
  const words = (val = value, at, num = int, end = elipsis) => prune(val, at, num) + end;
  const characters = (val = value, at, num = int, end = elipsis) => prune(val, at, num) + end;
  return {sentences, words, characters};
})();

console.clear();
console.log([
  truncate.sentences("This is a sentence. There are many like it but you won't see the 2nd one", '.', 1),
  truncate.words("These are words but you won't see what's after this because it'll be hidden", ' ', 10),
  truncate.characters("This won't exceed 31 characters so we cutting off the ending", '!', 31)
]);

Alternatively, though not consistent with the sentences, words can be composed with at being set as a default parameter

const words = ({val = value, at = ' ', num = int, end = elipsis} = {}) => prune(val, at, num) + end;

which would be called with

truncate.words({val: "These are words but you won't see what's after this because it'll be hidden", num: 10})

providing the ability to call the function without explicitly setting and passing at as a parameter.

Substituting a single function for sentences, words and characters

const truncate = (
  value = '',
  at = '',
  num = 0,
  elipsis = '\u2026', /* ... */
) => ((val, k = val[0] === value) =>
       `${(k ? [...value] : val).splice(0, num)
          .join(k ? '' : at)}${k ? at : ''}${elipsis}`)
     (value.split(at));

console.clear();
console.log([
  truncate("This is a sentence. There are many like it but you won't see the 2nd one", '.', 1),
  truncate("These are words but you won't see what's after this because it'll be hidden", ' ', 10),
  truncate("This won't exceed 31 characters so we cutting off the ending", '!', 31)
]);


Find prime factors in C++ Please review this code.

#include <iostream>
#include <vector>

bool is_prime(int x)
{
    int flag = 1;
    for (int i = 2; i <= x/2; i++)
    {
        if (x % i == 0)
        {
            flag = 0;
            break;
        }
    }
    if (flag == 1)
    {
        return true;
    }
    else if (flag == 0)
    {
        return true;
    }
}

void find_prime_factors(int n, std::vector<int>& vec)
{
    int val = n;
    for (int i = 2; i <= n; i++)
    {
        if (is_prime(i))
        {
            while (val % i == 0 && val != 1)
            {
                vec.push_back(i);
                val = val/i;
            }
            if (val == 1)
            {
                break;
            }
        }
    }
}

int main()
{
    int n;
    std::cout << "Enter number\n";
    std::cin >> n;
    std::vector<int> prime_factors;
    find_prime_factors(n, prime_factors);
    std::cout << "Prime Factors of " << n << ":\n";
    for (int i = 0; i < prime_factors.size(); i++)
    {
        std::cout << prime_factors[i] << " ";
    }
    std::cout << "\n";
}

Your program has a bug. is_prime returns true in all possible return situations. You don't notice that because your prime factors already use a nice property of prime factors which we inspect later. Here's a short list of improvements first:

return condition instead of if condition return true; else return false;
return early.
Use appropriate return types.
Modify algorithms.

Now let's focus on the bug first.

is_prime

First, the obvious: both return statements only return true. However, there are some improvements we can apply. First, if two conditions are exclusive and cover the whole range of possible conditions use if/else without a second if:

if (flag == 1)
{
    return true;
}
else // no if here!
{
    return true;
}

Note that this still contains your bug above. This brings us to our next improvement: instead of

if (condition) {
    return true;
} else {
    return false;
}

just return condition:

return (flag == 1);

Note that this completely removes the bug already. But we can go further. flag itself introduces a source for possible bugs. We could accidentally use flag = 3 (which can be mediated by bool flag) or forget to set flag (which can be checked by statical analysis).

But we don't need flag. Either we break the loop (and therefore flag = 0) and we return false, or we won't and return true. This is a perfect opportunity to use early returns:

bool is_prime(int x)
{
    for (int i = 2; i <= x/2; i++)
    {
        if (x % i == 0)
        {
            return false;
        }
    }
    return true;
}

There are two optimizations that are left for exercise. First, we don't need to check every i, but only every second. If x % 2 != 0, then x % i != 0 for all even i. Also, for any pair of factors \$ab=x\$ holds \$a\le b\$ and therefore \$a\le \sqrt{x}\$. Both optimizations are left as an exercise.

find_prime_factors

We now have a look at 3., "use appropriate return types". Your function's result is a vector. Nothing in its interface prevents a user to supply an already filled vector, e.g.:

std::vector<int> example = {1,2,3,4,5};
find_prime_factors(10, example); // whoops!

So instead have find_prime_factors return its result:

std::vector<int> find_prime_factors(int n)
{
    int val = n;
    std::vector<int> result;
    for (int i = 2; i <= n; i++)
    {
        if (is_prime(i))
        {
            while (val % i == 0 && val != 1)
            {
                result.push_back(i);
                val = val/i;
            }
            if (val == 1)
            {
                break;
            }
        }
    }
    return result;
}

Next, we'll focus on the algorithm. As you noticed, find_prime_factors worked, even though is_prime is broken. Why?

When you divide a number by its smallest prime factor, the next number that will divide the new number must be a prime factor. Let's try it by hand:

$$
\begin{align}
420 &= 2\cdot 2 \cdot 105 &\text{ the next factor is } 3 \\
&= 2\cdot 2 \cdot 3 \cdot 35 &\text{ the next factor is } 5 \\
&= 2\cdot 2 \cdot 3 \cdot 5 \cdot 7 &\text{ the next factor is } 7 \\
&= 2\cdot 2 \cdot 3 \cdot 5 \cdot 7 \cdot 1
\end{align}
$$
We don't need the is_prime check at all:

std::vector<int> find_prime_factors(int n)
{
    int val = n;
    std::vector<int> result;
    for (int i = 2; i <= n; i++)
    {
        while (val % i == 0 && val != 1)
        {
            result.push_back(i);
            val = val/i;
        }
        if (val == 1)
        {
            break;
        }
    }
    return result;
}

Also, we can stop as soon as i > val, because at that point val == 1.
 In fact, we can get rid of val altogether and just modify n:

std::vector<int> find_prime_factors(int n)
{
    std::vector<int> result;
    for (int i = 2; i <= n; i++)
    {
        while (n % i == 0)
        {
            result.push_back(i);
            n /= i;
        }
    }
    return result;
}

At some point n == i and n /= i will yield n == 1, so we don't have to worry about an infinite loop. This algorithm is also known as trial division. Note that we can also apply the optimization for even numbers here (left as another exercise).

There are other optimizations that one can apply:

reserve memory beforehand (a number \$N\$ can have at most \$\log_2 N\$ factors, so std::vector::reserve can be used)
use methods that yields both quotient and divisor at the same time (very platform specific).

For a fun exercise, you can rewrite it with iterators in mind:

template <typename OutputIt> OutputIt(int n, OutputIt out) {
    // exercise
}

Note that this is somewhat an overkill, since n will contain at most 64 prime factors if your int uses 64 bits.

Bottom line

Check all your functions. is_prime contained a nasty bug. Other than that your code is nicely structured, doesn't use using namespace and was easy to read.


Function to split full name into first & last In angular, I have an input field for a user's full name. And a function called splitName which extracts the first / last name from the field. Is there a way to improve this logic?

<input type="text" name="fullName" ng-model="data.full_name" />

On the backend, on form submit I do a POST which requires both a first_name and last_name in the body.

    scope.splitName = function(data, fullName) {
      var formData = angular.copy(data),
          nameArr,
          _lastName;

      if (fullName) {
        nameArr = fullName.split(' ');

        if (nameArr.length > 2) {
          _lastName = nameArr.pop();
          formData.first_name = nameArr.join(' ');
          formData.last_name = _lastName;
        } else {
          formData.first_name = nameArr[0];
          formData.last_name = nameArr[nameArr.length - 1];
        }
      }

      // remove full name as its not needed for backend
      delete formData.full_name;

      // return the copy
      return formData;
    };

Therefore, these are some examples.

scope.data = {
   full_name: 'Joe Middle Name Smith',
   first_name: '',
   last_name: '',
}

var example = scope.splitName(scope.data, scope.data.full_name);

//- which should return
{
  first_name: 'Joe Middle Name',
  last_name: 'Smith'
}

First of all, you should be aware that "first name" and "last name" are very tricky concepts. An example in that linked Wikipedia article is José Luis Rodríguez Zapatero. José Luis is the first name, though it's in two words. Rodríguez Zapatero are both surnames (paternal and maternal). Or you have cultures where "name" means surname first and then given name, i.e. the opposite of Western tradition. Example in the linked article is Zhang Wei, Zhang being the family name and Wei being the given name.

Heck, royalty and aristocracy don't even have regular surnames, really (or they're almost never used). They're just "of" some place; Elizabeth II of England, for example. Or take someone like Albert Maria Lamoral Miguel Johannes Gabriel, 12th Prince of Thurn and Taxis (yes, that's the guy's full "name" though it's part-title and honorific). Rarely something you need to worry about of course, but just to show that names aren't simple.

Hence the most common - and most robust - solution is to simply use two text fields: First name and last name. Trying to split things in code is nigh impossible because there's no single, standard naming scheme for everyone, everywhere.

Even Facebook, which certainly has the brains and computing power to attempt something clever, just uses two separate input fields. It's just easier.

So short answer: Don't try. Just make two inputs. Especially as the backend needs two separate values anyway.

But hey, code review:

I don't see the need to pass in the fullName separately. It's already in the data object.
I'm not sure why _lastName has an underscore in it. There's (as far as I can tell) nothing special about that variable.
I'm also not sure why it's there to begin with. You can just assign to formData.last_name directly; no need to to store it in a local variable first.
There's no need for the if (nameArr.length > 2) branching. Given an array of exactly two words, the first branch would do the same as the else branch does, just via a different route. So, really, the pop and join strategy covers both cases already.
... what it doesn't cover is the case where there's only 1 word. If fullName is just "John", then that will (via the else branch) become formData.first_name. But formData.last_name will just undefined. If you only use the pop and join strategy, you'd get "John" as the last name, and empty string as the first name. Either way, it's not optimal.
When you split, you'll split twice on double whitespace and split on leading/trailing whitespace, too. So given a full name like " John  Smith ", you get nameArr = ["", "John", "", "Smith", ""].
I believe Angular can/will automatically trim leading/trailing whitespace, though. If not, you can use String.trim. However, doubled whitespace will remain, so split with a regular expression like /\s+/ instead.

I'd do this:

var nameArr = formData.full_name.split(/\s+/);
formData.first_name = nameArr.slice(0, -1).join(" ");
formData.last_name = nameArr.pop();

That's pretty much it. You'll still want to copy the formData, and perhaps delete the full_name property, but otherwise that's the meat of it. It'll still be weird if full_name is just "John", because you'd get "John" as both first and last name, so you should probably have some more validation somewhere.

Still, though: Just use two fields.


Counting dashes in numbers I have written my very first Haskell module and I feel that the code can be improved based on the simplicity of the problem I am solving. Do you have any suggestions?

Problem statement:

You are given a String code containing a message composed entirely of decimal digits ('0'-'9'). Each digit consists of some number of dashes (see diagram below). A "check function" of a message is defined as the total number of dashes in the message. Return the value of the check function for the message represented in code.

Definition

Class:  CheckFunction
Method: newFunction
Parameters: String
Returns:    int
Method signature:   int newFunction(String code)
(be sure your method is public)

Notes
-   0 consists of 6 dashes, 1 consists of 2 dashes, 2 consists of 5 dashes, 3 consists of 5 dashes, 4 consists of 4 dashes, 5 consists of 5 dashes, 6 consists of 6 dashes, 7 consists of 3 dashes, 8 consists of 7 dashes, 9 consists of 6 dashes.

Constraints
-   code will contain between 1 and 50 characters, inclusive.
-   Each character in code will be a digit ('0'-'9').

Solution:

module Main where

import System.IO()
import Data.Char

-- Problem statement: https://community.topcoder.com/stat?c=problem_statement&pm=4788
-- Method signature: int newFunction(String code)

newFunction :: String -> Int
newFunction input =
    let arr = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
        x = [arr !! digitToInt (input !! x) | x <- [0..length input - 1]]
        in sum x

assert :: String -> Int -> String
assert s i = if newFunction s == i
then "test passed" else "test failed"

main :: IO()
main = do
  putStrLn $ show $ assert "13579" 21
  putStrLn $ show $ assert "868177" 28
  putStrLn $ show $ assert "8571" 17
  putStrLn $ show $ assert "3" 5
  putStrLn $ show $ assert "73254370932875002027963295052175" 157

Take items directly from the thing, without indexing:

x = [arr !! digitToInt i | i <- input]

And prefer where over let: (where is so much more common than let, it is easier to read as you see the general picture before the details.)

newFunction input = sum [arr !! digitToInt i | i <- input]
  where
    arr = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]

arr is a bad name, I would prefer dashesInDigits

assert should be more general (take f as argument) and written using guards.


Array's reverse vs simple arithmethic I was asked to print numbers from 100 to 1 in a for loop with the index starting from 1. I came up with this solution:

var a = [];

for(var i = 1; i <= 100; i++) {
    a.push(i);
}

console.log(a.reverse());

I was thinking of a better way of doing this after the interview and came up with this

for(var i = 1; i <= 100; i++) {
    console.log((100-i)+1);
}

Now what blows my mind is, jsperf.com's test indicates the former is faster. How is this even possible? Creating an array, pushing something into it and reversing it before printing definitely seems slower than simple arithmetic. Could anyone help me understand this?

It turns out accessing console take's more time than pushing a value in an array. Console.log is indeed implemented as a synchronous function (next print starts only after last print finishes).
Meaning, there is no buffering system. The program goes to blocking state until console.log() finish printing, everytime.
Performance difference in above two cases is due to the difference in the number of console.log() call.


Miller-Rabin Prime test (Speed is the main goal) The code below is for testing Primes.

testPrime(100000);
testPrime(1000000);
testPrime(10000000);
testPrime(100000000);

Now my goal is to make the code super fast at finding prime number, min-max, close prime.
Are there any improvements that can be done to the code below to improve the speed for IsPrime?

import java.util.ArrayList;
import java.math.*;

class Primes {

    private static long[] as = {2, 7, 61};

    private static long modpow(long x, long c, long m) {
        long result = 1;
        long aktpot = x;
        while (c > 0) {
            if (c % 2 == 1) {
                result = (result * aktpot) % m;
            }
            aktpot = (aktpot * aktpot) % m;
            c /= 2;
        }
        return result;
    }

    private static boolean millerRabin(long n) {
        outer:
        for (long a : as) {
            if (a < n) {
                long s = 0;
                long d = n - 1;
                while (d % 2 == 0) {
                    s++;
                    d /= 2;
                }

                long x = modpow(a, d, n);
                if (x != 1 && x != n - 1) {
                    for (long r = 1; r < s; r++) {
                        x = (x * x) % n;
                        if (x == 1) {
                            return false;
                        }
                        if (x == n - 1) {
                            continue outer;
                        }
                    }
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean IsPrime(long num) {
        if (num <= 1) {
            return false;
        } else if (num <= 3) {
            return true;
        } else if (num % 2 == 0) {
            return false;
        } else {
            return millerRabin(num);
        }
    }
    public static int[] primes(int min, int max) {
           ArrayList<Integer> primesList = new ArrayList<Integer>();

           for( int i=min; i<max; i++ ){
                if( IsPrime(i) ){
                   primesList.add(i);
                }
           }

           int[] primesArray = new int[primesList.size()];
           for(int i=0; i<primesArray.length; i++){
               primesArray[i] = (int) primesList.get(i);
           }

           return primesArray;
        }

    public static String tostring (int [] arr){
        String ans="";
        for (int i=0; i<arr.length;i++){
            ans= ans+arr[i]+ " ";
        }
        return ans;
    }
     public static int closestPrime(int num) {
            int count=1;
            for (int i=num;;i++){

                int plus=num+count, minus=num-count;
                if (IsPrime(minus)){

                    return minus;

                }

                if (IsPrime(plus)) {
                    return plus;

                }
                count=count+1;
            }
        }

    }

//end class

You could use the Sieve of Eratosthenes for numbers less than 10 million (you are only going up to 100 million).

I think that  checking the low bit (num & 1) == 0 is quicker than checking the remainder num % 2 == 0.  Similarly, bit shifting is quicker for division or multiplication by 2: d /= 2 could be d >> 1.

You might experiment with doing an initial check for division by a few low primes (3, 5, 7, 11) in your IsPrime method and see if that makes a difference.

Finally, for your "random" numbers, you might want to choose products of primes, e.g. 3*5*7*11*13..., or maybe that plus 1.  Maybe that's crazy.  But some "random" numbers might provide richer test cases than others, and cause a faster elimination of non-primes.


jQuery code to detect whether form fields have the default value when a checkbox is unchecked How could I rewrite this jquery code to compact it in a more elegant form:

$(document).ready(function(){
     $('input[name="table_exist"]').click(function(){
      if($('input[name="table_name"]').val()=='users' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="table_name"]').val('');
   }
   else if($('input[name="table_name"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="table_name"]').val('users');
   }

   if($('input[name="user_id"]').val()=='user_id' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_id"]').val('');
   }
   else if($('input[name="user_id"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_id"]').val('user_id');
   }

   if($('input[name="user_name"]').val()=='user_name' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_name"]').val('');
   }
   else if($('input[name="user_name"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_name"]').val('user_name');
   }

   if($('input[name="user_email"]').val()=='user_email' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_email"]').val('');
   }
   else if($('input[name="user_email"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_email"]').val('user_email');
   }

   if($('input[name="user_pass"]').val()=='user_pass' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_pass"]').val('');
   }
   else if($('input[name="user_pass"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_pass"]').val('user_pass');
   }

   if($('input[name="joining_date"]').val()=='joining_date' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="joining_date"]').val('');
   }
   else if($('input[name="joining_date"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="joining_date"]').val('joining_date');
   }
     });
 });

<form method="POST">

DB Table

     Activate the slider if you already have your own database table created!

     <input type="checkbox" name="table_exist" />

     Edit here only if you have your own predifined table header names!

     <input type="text" name="table_name" value="users" required />
     Table Name

     <input type="text" name="user_id" value="user_id" required />
     User ID

     <input type="text" name="user_name" value="user_name" required />
     User Name

     <input type="text" name="user_email" value="user_email" required />
     User E-mail

     <input type="text" name="user_pass" value="user_pass" required />
     User Password

     <input type="text" name="joining_date" value="joining_date" required />
     User Added Date

    <button type="submit" name="btn-install">
     Install
    </button>

   </form>

The whole process is to identify if the fields have the default values when a checkbox is unchecked. If the state is changed to checked then empty all fields to input custom information/values. If unchecked again it returns the initial values.

There're multiple ways to do that. You should use a loop.

I've wrote a small script, that would do the job. I do not know if the if block is correct but you should easily fix that with this base.

$(document).ready(function(){
$('input[name="table_exist"]').click(function(){
 var table_exist_checked = $('input[name="table_exist"]').is(':checked');

 var fields = [
  'table_name',
  'user_id',
  'user_name',
  'user_email',
  'user_pass',
  'joining_date',
 ]; // Your field names

 // iterate over all fieldnames
 for(var index of fields) {
  var fieldName = fields[index]; // extract current fieldName
  var $elem = $('input[name="' + fieldName + '"]'); // save current element so we do not need to repeat

  // This is ur if-else. I do not exactly know if this is correct
   if($elem.val() == fieldName && table_exist_checked){
   $elem.val('');
  } else if($elem.val()=='' && !table_exist_checked){
   $elem.val(fieldName);
  }
 }

}); });


Utilizing std::map and std::array for displaying a modulus grid I've written a modulus-type program (using std::vector).  The user inputs a number, and the program displays a modulus grid pertaining to that number.

This is what it looks like (example program output with 12):

(0)  12 24  36  48  60  72  84  96  108  120
(1)  13  25  37  49  61  73  85  97  109  121
(2)  14  26  38  50  62  74  86  98  110  122
(3)  15  27  39  51  63  75  87  99  111  123
(4)  16  28  40  52  64  76  88  100  112  124
(5)  17  29  41  53  65  77  89  101  113  125
(6)  18  30  42  54  66  78  90  102  114  126
(7)  19  31  43  55  67  79  91  103  115  127
(8)  20  32  44  56  68  80  92  104  116  128
(9)  21  33  45  57  69  81  93  105  117  129
(10)  22  34  46  58  70  82  94  106  118  130
(11)  23  35  47  59  71  83  95  107  119  131
(12)  24  36  48  60  72  84  96  108  120  132

Now, I've decided to make it nicer by using std::map and std::array.  I get the same output as before, but with the same alignment issues (fixing those could complicate my display function).

Is this an effective use of these containers (and am I using them correctly)?  If not, what other containers could be used instead?  I'm using std::array instead of std::vector here because I'm keeping the number of columns (array size) at 10.

#include <iostream>
#include <map>
#include <array>

const unsigned NUM_ARR_ELEMS = 10;

std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> getModGrid(unsigned);
void displayModGrid(const std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>>&);

int main()
{
    std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> modGrid;
    unsigned mod;

    std::cout << "\n\n> Mod: ";
    std::cin >> mod;

    std::cout << std::endl << std::endl;
    modGrid = getModGrid(mod);
    displayModGrid(modGrid);

    std::cout << std::endl << std::endl;
    std::cin.ignore();
    std::cin.get();
}

std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> getModGrid(unsigned mod)
{
    std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> modRow;
    std::array<unsigned, NUM_ARR_ELEMS> modValues;

    for (unsigned modIter = 0; modIter <= mod; ++modIter)
    {
        for (unsigned arrIter = 0; arrIter < NUM_ARR_ELEMS; ++arrIter)
            modValues[arrIter] = modIter + (mod * (arrIter+1));

        modRow[modIter] = modValues;
    }

    return modRow;
}

void displayModGrid(const std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> &modGrid)
{
    for (auto rowIter = modGrid.cbegin(); rowIter != modGrid.cend(); ++rowIter)
    {
        std::cout << "  (" << rowIter->first << ")  ";

        for (auto colIter = rowIter->second.cbegin(); colIter != rowIter->second.cend(); ++colIter)
        {
            std::cout << *colIter << "  ";
        }

        std::cout << std::endl;
    }
}

main() can be defined lastly, so that the function prototypes can be removed.  This will also allow NUM_ARR_ELEMS to be initialized within main().  The size of either the inner or outer structure can still be accessed via size().
For simple input like this, a command line argument is another option:

int main(int argc, char *argv[])
{
    unsigned int mod;

    // only argument being the file name
    if (argc < 2)
    {
        std::cin << mod;
    }
    // more than the file name, where only the second is used
    else
    {
        mod = std::atoi(argv[1]);
    }
}

Warning: std::atoi() returns an int, but mod is an unsigned int.  As this is a mismatch (and should be reported by the compiler), something else should be changed.  Either the return value of std::atoi() should be cast to an unsigned int, or mod should just be changed to an int (and adjusted elsewhere).  The latter may be a better option here, and the extra unsigned bit really isn't important.  Input validation (to avoid a negative value) can be done as well.
This type is quite long to copy in different places:

std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>>

so it can become a typedef:

typedef std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> Grid;

Prefer "\n" over std::endl for just a newline.  The latter also flushes the buffer.