Android Compound View Usage I have 2 buttons for Terms and Conditions in my project, that I need to implement in multiple activities. I created the following class:

public class TermsAndConditionsView extends LinearLayout implements View.OnClickListener {
    private Context context;

    public TermsAndConditionsView(Context context) {
        super(context);
        this.context = context;
    }

    public TermsAndConditionsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        setUpLayout();
    }

    private void setUpLayout() {
        LinearLayout container = (LinearLayout) this.getChildAt(1);
        Button terms1 = (Button) container.findViewById(R.id.terms1);
        Button terms2 = (Button) container.findViewById(R.id.terms2);
        terms1.setOnClickListener(this);
        terms2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.terms1) {
            String url = "myUrl1";
            ActivityUtil.openBrowser((Activity) context, url);
        } else if (v.getId() == R.id.terms2) {
            String url = "myUrl2";
            ActivityUtil.openBrowser((Activity) context, url);
        }
    }
}

And the terms.xml file:

 <?xml version="1.0" encoding="utf-8"?>
<com.example.TermsAndConditionsView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">

<TextView
    android:id="@+id/hosted_by_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textColor="@color/title_grey"
    style="@style/text1"/>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <Button
        android:id="@+id/terms1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Terms 1"
        style="@style/Link2"/>

    <Button
        android:id="@+id/terms2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="Terms 2"
        style="@style/Link2"/>
</LinearLayout>
</com.example.TermsAndConditionsView>

Is this a good way of reusing a group of views?

My colleagues say that it's not ok to use an XML which can be modified easily because I should modify in the code also (for example changing the order of the views) and if I am not careful the app might crash and it might take some time to figure out from where the problem comes from.

So, what's the best way of reusing this group of Terms and Conditions buttons?

Usually I use this approach when I want to create custom views but I don't implement actions inside the view, instead I am using a callback like the click listener :).

Also another minor thing is that there is no need to do getChildAt() so you can find a specific view from a child view if you don't happen to have id's with the same names. Instead you can call findViewById directly on this(the root view).


Pangrams implementation using Linq This is a continuation of my LINQ stories from Pangrams-Hackerrank. Similarly, this challenge has been asked before in python Pangrams python Implementation but I have tried to accomplish this challenge using LINQ.

Here is a summary of the question

  Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.)

  After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams.

  Given a sentence , tell Roy if it is a pangram or not.

  Input Format

  Input consists of a string .

  Constraints

  Length of  can be at most 103(1≤|s|≤103) and it may contain spaces, lower case and upper case letters. Lower-case and upper-case instances of a letter are considered the same.

  Output Format

  Output a line containing pangram if  is a pangram, otherwise output not pangram.

Sample Input

Input #1

We promptly judged antique ivory buckles for the next prize

Input #2

We promptly judged antique ivory buckles for the prize

Sample Output

Output #1

pangram

Output #2

not pangram

Explanation

In the first test case, the answer is pangram because the sentence contains all the letters of the English alphabet.

Here is my implementation

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.IO;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */

            string pangramInput = Console.ReadLine();
            var alphabet = Enumerable.Range(97, 26).Select((x) => (char)x);
            var pangramCheck = pangramInput.Replace(" ", "").ToLower().OrderBy((letter) => letter).Distinct().SequenceEqual(alphabet);
            string answer = pangramCheck ? "pangram" : "not pangram";
            Console.WriteLine(answer);
    }
}

Thoughts

I know this is a simple exercise and can be achieved without LINQ but the main idea is to know how to use LINQ functions.

Is the use of LINQ right? are there other simpler alternatives?

First a review...

Long extension chains

With lengthy linq chains it's a good idea to break them into multiple lines. Especially here on CR so that we don't have to scroll horizontally.

String interpolation

string answer = pangramCheck ? "pangram" : "not pangram";

We could optimize it as:

var answer = $"{(pangramCheck ? string.Empty : "not ")}pangram";

or you can make it even prettier by encapsulating this logic in an extension:

public static string Negate(this string value, bool negate)
{
    return $"{(negate ? string.Empty : "not ")}{value}";
}

so you then have:

Console.WriteLine("pangram".Negate(isPangram));

Consistency

string text
string answer

Don't you like var for strings because you already use for the other two variables? ;-)

Magic numbers

Enumerable.Range(97, 26)

This would be easier to understand if you used constants:

const string alphabetLength = z - a + 1;
Enumerable.Range('a', alphabetLength)

Not LINQ

.Replace(" ", "").ToLower()

This two kill the linq idea of your question. Consider this instead:

text
    .Select(char.ToLower)
    .Where(char.IsLetter)

Alternative solution

Then an alternative version...

If using a HashSet<char> is still linq-ish enougth then I replaced the Distinct with the Aggregate that uses one and makes it na O(n) solution for the English aphabet:

const int alphabetLength = 'z' - 'a' + 1;
var isPangram =
    text
    .Select(char.ToLower)
    .Where(char.IsLetter)
    .Aggregate(new HashSet<char>(), (acc, next) => { acc.Add(next); return acc; })
    .Count == alphabetLength;

UPDATE

Well, I forgot that we don't have to scan the entire string. As soon as we have the required chars we can stop. So this improved version should be faster for long texts:

const int alphabetLength = 'z' - 'a' + 1;
var chars = new HashSet<char>();

var testedChars = text
    .Select(char.ToLower)
    .Where(char.IsLetter)
    .TakeWhile(x => { chars.Add(x); return chars.Count != alphabetLength; })
    .Count();

var isPangram = chars.Count == alphabetLength;


Simple Python hangman game I've created a little hangman game. It's pretty simple, and not to exciting but I want to know if there's a way I could turn this little game into something more extravagant and more exciting. How can I take this delicate piece of crap machinery into something a little more fun and a bit more complicated? For example:

Can I turn the list that is shown into a single string?
Is there a better way to use a random word?
Am I using the for and while loop in the correct syntax?

Source:

from random import randint

WORD_LIST = {
    'rand_word_1': 'sergeanty',
    'rand_word_2': 'amphipneustic',
    'rand_word_3': 'hypochil',
    'rand_word_4': 'grus',
    'rand_word_5': 'depressed',
    'rand_word_6': 'distortedly',
    'rand_word_7': 'unselected',
    'rand_word_8': 'crakow',
    'rand_word_9': 'preendorsing',
    'rand_word_10': 'convenient'
}

HANGMAN = (
    """
    x-------x
    """,
    """
    x-------x
    |
    |
    |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |       |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |      /
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |      / \\
    |
    GAME OVER
    """
)

MAX = len(HANGMAN) - 1
num = randint(1, 10)
num_string = str(num)
words = 'rand_word_{}'.format(num_string)
WORD_TO_GUESS = WORD_LIST[words]
HIDDEN = ['_'] * len(WORD_TO_GUESS)
LETTERS_GUESSED = []

def begin_game():
    hang_size = 0
    print "\tHANGMAN!"
    word_arr = list(WORD_TO_GUESS)

    while hang_size < MAX:
        print str(HIDDEN)
        user_guess = raw_input('Guess a letter dude: ')

        if user_guess in LETTERS_GUESSED:
            print 'You already guessed that.. PAY ATTENTION!'
            user_guess = raw_input('Guess a letter dude: ')

        if user_guess in word_arr:
            print "Yeah yeah.. We're all impressed.. It's in the word woohoo.."

            for num in range(len(word_arr)):
                if user_guess == word_arr[num]:
                    HIDDEN[num] = user_guess
                    if HIDDEN.count('_') == 0:
                        print 'You win! Finally you did something right!'
                        quit()

        else:
            print "{}.. Really? That's the best you can do.. Not in my word..".format(user_guess)
            hang_size += 1
            print HANGMAN[hang_size]

begin_game()

Overview

I can see that you are a beginner and that is totally fine! Some of the points I will be making might, sound a bit harsh and go over your head. If they do try to improve the parts of the code you do understand, and instead post a follow up question.

LMGTFY / RTFM

Asking a question on a SE, site is a great way to learn. However another is searching for answers beforehand. In fact all three questions in your bullet list could be googled / found in the manual.

Turn a list into a string Python
How do I randomly select an item from a list using Python?
When to use for and while loop

As you know CodeReview has it's own hangman tag -- since you tagged your own question with the tag. This means people have asked hangman related questions earlier, and you could have browsed these questions before posting your own. As an example, even I have asked a question about hangman. Here is another very similar question.

This is not to discredit you for asking, however drawing suggestions and inspiration from similar problems is a fantastic way to learn.

PEP 8 - Style Guide for Python Code

As to pick the lowest hanging fruits. Consistency is a key part of programming, as it greatly increases readability. It also tells a bit about the coders eye for detail. Lets' look at how you have named your global constants:

MAX
num
num_string
words
WORD_TO_GUESS
HIDDEN
LETTERS_GUESSED

Do you see the inconsistency? Pep 8 recommends the following naming-conventions:

CAPITALIZED_WITH_UNDERSCORES for constants
UpperCamelCase for class names
lowercase_separated_by_underscores for other names

General structure

A very rough sketch of how a standard python program should look like is as follows

import

global CONSTANTS
global VARIABLES

functions

classes

if __name__ == '__main__':

    main()

All of your code should be split into short simple functions, which each serve a single purpose. You should in general have as little code as possible floating around that is not part of a function. This includes minimizing the need for global variables and constants. There are some exceptions to this rule, however your code is not one of them.

Some more pointers

As earlier answers stated you can change your dictionary word list into

WORD_LIST = [
    'sergeanty',
    'amphipneustic',
    'hypochil',
    'grus',
    'depressed',
    'distortedly',
    'unselected',
    'crakow',
    'preendorsing',
    'convenient'
]

As mentioned earlier you use too many global variables. This

MAX = len(HANGMAN) - 1
num = randint(1, 10)
num_string = str(num)
words = 'rand_word_{}'.format(num_string)
WORD_TO_GUESS = WORD_LIST[words]
HIDDEN = ['_'] * len(WORD_TO_GUESS)
LETTERS_GUESSED = []

can be shortened into

MAX = len(HANGMAN) - 1
word_to_guess = random.choice(WORD_LIST)
hidden = ['_'] * len(word_to_guess)
letters_guessed = set()

Where I have used the choice function from the random module. For an example of use see below

   >>> import random
   >>> a = ["Stack", "Overflow", "rocks"]
   >>> print(random.choice(a))
   rocks

for a more detailed explanation see the second bullet point at the start.

You might also have noticed that some of the variables are not CAPITALIZED that is because they do not need to be global variables, and can be moved into the main function.

def play_hangman():
    hang_size = 0
    word_to_guess = random.choice(WORD_LIST)

    hidden = ['_'] * len(word_to_guess)
    letters_guessed = set()

Note how I also conveniently changed the name of your main() function. Naming variables, functions and classes in programming is one of the more difficult things to do. A general rule of thumb is that the names should be clear, distinct and succinct in that order. As others have pointed out main() only achieves the third, which should be the last thing to worry about.

Handling user input

Jokes aside as a rule you should never except the user to use the correct input syntax. Instead you should build in checks, exceptions to handle these errors.

For an example your code only checks once if I have tried the letter before.

if user_guess in LETTERS_GUESSED:
    print 'You already guessed that.. PAY ATTENTION!'
    user_guess = raw_input('Guess a letter dude: ')

One way to fix this is using a while loop instead

while user_guess in LETTERS_GUESSED:
    print 'You already guessed that.. PAY ATTENTION!'
    user_guess = raw_input('Guess a letter dude: ')

What happens if i decide to try the letter banana or the letter ? Your function does nothing to handle it. What If I try the more common mistake to try A then a? All of this can be fixed by putting the get_user_input into it's own function

ALPHABETH = 'abcdefghijklmnopqrstuvwxyz'

def guess_letter(letters_guessed):
    while True:
        guess = raw_input('Guess a letter dude: ').lower()
        if guess not in ALPHABETH:
            print guess, 'is like totally not in the alphabet dude, try again!'
        elif guess in letters_guessed:
            print 'You already guessed {}.. PAY ATTENTION!'.format(guess)
        else:
            return guess

Do note that I did not have to convert ALPHABETH into a list. Python can compare strings just as well as lists. Also notice how I used Python string lower() method to ensure that the user input was all lowercase.

Continuing on

The next bit of your code could then be written as

while hang_size < MAX:
    print str(hidden)
    user_guess = guess_letter(letters_guessed)
    letters_guessed.add(user_guess)
    if user_guess in word_to_guess:

Where we again used that Python can compare strings just fine. The add is used instead of append since letters_guessed is now a set and not a list. Why am I using sets, you ask?

  When you want to store some values which you'll be iterating over,
  Python's list constructs are slightly faster. However, if you'll be
  storing (unique) values in order to check for their existence, then
  sets are significantly faster.

For words as short as your the difference is negligible, however it is a good practice nevertheless.

for num in range(len(word_arr)):

This can be improved using Pythons enumerate() function that adds a counter to an iterable.

    for i, letter in enumerate(word_to_guess):
        print i, letter
        if user_guess == letter:
            hidden[i] = letter
    if hidden.count('_') == 0:
        print 'You win! Finally you did something right!'
        return

I really see no point in turning the for-loop into a zip list. Yes, it is shorter. However for a novice it is much harder to understand what is going on.

Winning condition and return

The statement

if HIDDEN.count('_') == 0:
    print 'You win! Finally you did something right!'
    quit()

Is weird. The if HIDDEN.count('_') == 0: is cryptic at best. A good practice is to check what you really want to check.. You are not interested in how many _'s are left, but rather if the user has guessed the correct word. This can be checked as follows

user_guessed_word_spaced = ' '.join(hidden)
word_to_guess_spaced = ' '.join(word_to_guess)
if user_guessed_word_spaced == word_to_guess_spaced:

At a first glance this might seem convoluted. However in the actual code word_to_guess_spaced = ' '.join(hidden) is only declared once. Secondly using a spaced string ' '.join() instead of ''.join() allows us to directly print the output at the start of the while-loop.

Your way to exit the function is very intuitive for a beginner, however it should be avoided like the plague for a beginner. A more natural way is to use return instead.

  quit raises the SystemExit exception behind the scenes.

  Furthermore, if you print it, it will give a message:

>>> print (quit)
Use quit() or Ctrl-Z plus Return to exit
>>>

  This functionality was included to help people who do not know Python.
  After all, one of the most likely things a newbie will try to exit
  Python is typing in quit.

  Nevertheless, quit should not be used in production code. This is
  because it only works if the site module is loaded. Instead, this
  function should only be used in the interpreter.

I have made some adjustments to accommodate for this. This includes having only a single return statement, as well as some better handling of printing the winning conditions.

There are more things to nitpick, which I did not try to fix/improve

You should always comment your code. You can never be sure you will understand your code 6months down the road. A common way to do this is with PEP 257 -- Docstring Conventions.
Your creation of strings could be improved.
Your list of words is short, and a simple fix is to use a larger list from the internet.
You could also make a short menu to congratulate the user, or ask if one wants to play again.

Code

Using all of these small improvements leads to the following code.

import random

WORD_LIST = [
    'sergeanty',
    'amphipneustic',
    'hypochil',
    'grus',
    'depressed',
    'distortedly',
    'unselected',
    'crakow',
    'preendorsing',
    'convenient'
]

HANGMAN = (
    """
    x-------x
    """,
    """
    x-------x
    |
    |
    |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |       |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |      /
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |      / \\
    |
    """
)

MAX = len(HANGMAN) - 1
ALPHABETH = 'abcdefghijklmnopqrstuvwxyz'

def guess_letter(letters_guessed):
    while True:
        guess = raw_input('Guess a letter dude: ').lower()
        if guess not in ALPHABETH:
            print guess, 'is like totally not in the alphabet dude, try again!'
        elif guess in letters_guessed:
            print 'You already guessed {}.. PAY ATTENTION!'.format(guess)
        else:
            return guess

def play_hangman():
    hang_size = 0
    word_to_guess = random.choice(WORD_LIST)
    word_to_guess_spaced = ' '.join(word_to_guess)

    hidden = ['_']*len(word_to_guess)

    letters_guessed = set()
    user_guessed_word_spaced = ' '.join(hidden)

    print "HANGMAN!"

    while hang_size < MAX:

        print
        print user_guessed_word_spaced

        user_guess = guess_letter(letters_guessed)
        letters_guessed.add(user_guess)

        if user_guess in word_to_guess:

            print "\nYeah yeah.. We're all impressed.. {} is in the word woohoo..".format(user_guess)

            for i, letter in enumerate(word_to_guess):
                if user_guess == letter:
                    hidden[i] = letter

            user_guessed_word_spaced = ' '.join(hidden)
            if user_guessed_word_spaced == word_to_guess_spaced:
                print
                print word_to_guess
                break

        else:
            print "{}.. Really? That's the best you can do.. Not in my word..".format(user_guess)
            hang_size += 1
            print HANGMAN[hang_size]

    return user_guessed_word_spaced == word_to_guess_spaced

if __name__ == '__main__':

    is_winner = play_hangman()
    if is_winner:
        print '\nYou win! Finally you did something right!'
    else:
        print '\nGAME OVER'


Class for generating PDF documents Following is a chunk of code from my class which generates PDF documents. I am refactoring my code and in the process I have created short methods. But I have to pass 'table i.e PdfPTable' to my methods again and again. How can I avoid this?

PdfPTable orgTable = new PdfPTable(2);
PdfPCell cell = null;
string orgName = dr["OrganizationName"].ToString();
cell = new PdfPCell(new Phrase(orgName, Heading1)) {Colspan = 2, BackgroundColor = BckColor, HorizontalAlignment = Element.ALIGN_CENTER };
orgTable.AddCell(cell);

AddOrganizationProfile(document, dr, orgTable);
OrganizationHeadOffice(document, dr, orgTable);
OrganizationContacts(document, orgTable, orgId);

private void OrganizationHeadOffice(Document document, DataRow dr, PdfPTable table)
{
    AddTitle("Office Contact & Information:", table);

    // How to avoid passing table variable again and again here.
    AddLegend("Address:", table);
    AddDataValue(dr["address"].ToString(), table);
    AddLegend("Contact Number:", table);
    AddDataValue(phone1, table);
}

private void AddTitle(string title, PdfPTable table)
{
    table.AddCell(new PdfPCell(new Phrase(title, TableFontCaption)) { Colspan = 2, BackgroundColor = BckColor });
}

private void AddLegend(string legend, PdfPTable table)
{
    table.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER, Phrase = new Phrase(legend, TableFontCaption) });
}

private void AddDataValue(string dataValue, PdfPTable table)
{
    table.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER, Phrase = new Phrase(dataValue, TableFont) });
}

Make PdfPTable a property of the class and set it in the constructor.


replace a text from emacs buffer to insert it vertically with emacs lisp script I just found this post with vim (https://stackoverflow.com/questions/704130/can-i-transpose-a-file-in-vim) and i just wanted to do the same thing with elisp by creating a little script to reordenate all the characters from a buffer text into a vertical position.

As the post said, the original buffer might be:

THE DAY WAS LONG
THE WAY WAS FAST

and it would become:

TT
HH
EE

DW
AA
YY

WW
AA
SS

LF
OA
NS
GT

I write this little emacs script to first read each buffer lines in a list (removing spaces), and after using a zip function to transpose each characters between lists, and at the end iterate my list to print it in x columns.

(require 'subr-x)
(defun read-buffer-lines (buf)
  (let ((lines '()))
    (with-current-buffer buf
      (save-excursion
        (goto-char (point-min))
        (while (not (eobp))
          (if (not (string-equal "" (buffer-substring (point) (point-at-eol))))
              (push
               (delete " " (delete "" (split-string
                                       (string-trim (buffer-substring (point) (point-at-eol)))
                                       "")))
                  lines)
              )
            (beginning-of-line 2))
        (erase-buffer) ;; clean buffer
        (nreverse lines)
        ))))

(defun zip_list (lst)
  (let ((res))
    (while (-none? 'null lst)
      (setq res (cons (mapcar 'car lst) res))
      (setq lst (mapcar 'cdr lst)))
    (nreverse res)
    ))

(let* ((buf "*scratch*")
       (a (zip_list (read-buffer-lines buf))))
  (with-current-buffer buf
    (while a
      (progn
        (insert (mapconcat 'identity (car a) ""))
        (newline)
        (setq a (cdr a))))))

Few general points about your code:

(while condition &body) form already treats &body as an implicit progn. There's no reason to wrap it in a progn.
insert accepts multiple arguments.  So, you could write (insert (mapconcat ...) "\n") instead of calling (insert ...) followed by (newline).
Traditionally, Lisp functions use - when the name of the function consists of multiple words, so, it would be better to call zip-list, not zip_list.
(let (res) ...) is exactly the same as (let ((res)) ...) but shorter.
(setq ...) can handle multiple assignments, they are executed in order they are written, so (setq a b c a) will assign b to c.  No reason to write (setq a b) (setq c a).
split-string has argument OMIT-NULLS that controls whether empty strings are included in the results.  It would be better to rely on this argument than to post-process the results.
As mentioned in the comments, there's an easier, more idiomatic way to obtain all lines of text from the buffer: (split-string (buffer-string) "\n").

Finally, unless only for the sake of an exercise in writing the zip-list function, the transpose operation calls for something like vector, not a list.  Below is a possible alternative which uses vectors to perform this operation:

(defun wvxvw/transpose-buffer ()
  (interactive)
  (let* ((lines (split-string (buffer-string) "\n"))
         (max-length
          (cl-loop for line in lines
                   maximize (max (length line))))
         (src (cl-coerce lines 'vector))
         (dst (cl-loop with matrix = (make-vector max-length nil)
                       with len = (length src)
                       for i below max-length do
                       (aset matrix i (make-vector len ?\ ))
                       finally (cl-return matrix))))
    (cl-loop for i upfrom 0
             for line across src do
             (cl-loop for j upfrom 0
                      for c across line do
                      (aset (aref dst j) i c)))
    (erase-buffer)
    (cl-loop for line across dst do
             (insert (cl-coerce line 'string) "\n"))))


Functional way to have two toggles that turn each other off I have two sets of toggles that need to "uncheck" each other. This is my current solution which is working.  Can it somehow get more functional/elegant?

let unscheduledLayerToggles = [unscheduledLayerToggle, unscheduledLayerToggleToolbar];
let availableLayerToggles = [availableLayerToggle, availableLayerToggleToolbar];

flipToggles(firstToggles, secondToggles)
flipToggles(secondToggles, firstToggles)

function flipToggles(firstToggles, secondToggles) {
    firstToggles.forEach(function (toggle) {
        on(toggle, "change", function () {
            secondToggles.forEach(function(element) {
                element.checked = false
            })
        })
    })
}

The logic itself is simple enough. I see that you are using ECMAScript 6, with it there are some things you could do to simplify the code and make it more robust.
const
You are using let for unscheduledLayerToggles and availableLayerToggles, which is fine, but in the case that you will not be reassigning different values/arrays to those names, you could simply use const instead of let. Note that this will not make the arrays immutable, so you can still manipulate their contents, it only disallows assigning something different to them.
flipToggles function
In the same manner as you can use const to declare function (in the style of var foo = function () { ... }). It helps to make the intentions clear that the function will not change.
Arrow functions
ES6 provides a great way to both shorten/simplify function declarations, as well as isolate their scope better: Arrow Functions.
The syntax is explained well on MDN like I provided. In the case of your flipToggles function, we could write the code this way and eliminate all the unnecessary function() declarations.

const unscheduledLayerToggles = [unscheduledLayerToggle, unscheduledLayerToggleToolbar];
const availableLayerToggles = [availableLayerToggle, availableLayerToggleToolbar];

flipToggles(firstToggles, secondToggles)
flipToggles(secondToggles, firstToggles)

const flipToggles = (firstToggles, secondToggles) => {
  firstToggles.forEach(toggle => {
    on(toggle, "change", () => {
      secondToggles.forEach(element => {
        element.checked = false
      })
    })
  })
}

(mind the indentation, which is a personal preference of mine for 2 spaces indent instead of 4)


Custom encoding for BinaryReader I have a file that seems to mix encoding in it. It seems like a Unicode encoded file, but the character length string is encoded like a UTF8 or similar. Here is an example:

05 41 00 72 00 69 00 61 00 6C 00
5  A  .  r  .  i  .  a  .  l  .

In this example it stores the string like Unicode, using the extra character, but the length of the string is half of what it should be, 05 instead of 0A, as if it were encoded as UTF8.

If I use:

using (var reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.Unicode))
{
  temp = reader.ReadString();
}

When I run this then temp = "Ar"

I have this code that works. But is there a better way?

using (var reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.Unicode))
{
  tempByte = reader.ReadByte();
  var length = Convert.ToInt32(tempByte) * 2;
  byteArray = reader.ReadBytes(length);
  for (var ww = 0; ww < length; ww = ww + 2)
  {
    tempString = tempString + (char)byteArray[ww];
  }
}

BinaryReader.ReadString() expects the string prefixed with the number of bytes to read, not the number of characters (I think this is because of variable-length encodings, especially UTF-8, but also UTF-16).

So, you can't use ReadString() directly, but you also don't have to convert the characters byte by byte like you do (which wouldn't work for non-ASCII characters anyway).

For this, you can use ReadChars(), which takes as a parameter the number of characters (not bytes) to read.

You also need to figure out what format is the number of bytes saved in. It could be a simple single-byte number (which means the string can have at most 255 characters), or it could be VLQ-encoded, which you can read using Read7BitEncodedInt(). Though that method is protected, so I'm going to assume the former for simplicity.

So, the code could look like this:

using (var reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.Unicode))
{
    int characterCount = reader.ReadByte();
    char[] characters = reader.ReadChars(characterCount);
    return new string(characters);
}


Structuring a master page I have a small Coldfusion section of our site that all uses similar JavaScript and CSS files and page design. The code is currently repeated for each file, and I'd like to factor it out and set something up using a master page and templates.

Master.cfm page:

<cfinclude template="_lockedPage.cfm" />

<!DOCTYPE HTML>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>#title#</title>
        ... all script and css links here ...

        ... etc ...

                Back

<cfoutput>#title#</cfoutput>

                Home

                <cfinclude template="#pageName#.cfm" />

Then a page example would be something like this. CustomerSearch.cfm:

<cfscript>
    title = "Customer Search";
    pageName = "_customer-search";
    include "Master.cfm";
</cfscript>

And then I would need a _customer-search.cfm page that would include all the body content for the page.

This means that I would need 2 files for every page that we currently have - the outer page that defines the variable and includes the master page, and the template page that has the individual page content.

Is this a good logical design? Is there anyway to improve it?

My ColdFusion is a little rusty, but why would you not have the setting of the master dependent variables and the call to the master page both contained within the same page? Other than that, sure, you're implementing this the same way everyone does unless it's specifically built into the language.


VBA - create separate spreadsheets from a filtered table The task is relatively simple and until now it was always performed by some poor admin soul.  There is a large table that needs to be filtered based on a simple criteria and each view has to be saved as a new spreadsheet.
The code is as simple as the task (and as my coding skills) so I would love to get some feedback about any tricks I might have missed to make it more robust or "best practices" advice.
Option Explicit

Sub SplitWorksheet()

    Dim d As Long
    Dim dctList As Object
    Dim varList As Variant
    Dim varName As Variant
    Dim wkb As Workbook
    Dim wks As Worksheet
    Dim rng As Range
    Dim wkbNew As Workbook
    Dim strPath As String

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

    Set wkb = ThisWorkbook
    Set wks = wkb.Sheets("Data")
    Set rng = wks.Range("A1").CurrentRegion

    strPath = Application.ThisWorkbook.Path & "\Distribution\"

    Set dctList = CreateObject("Scripting.Dictionary")
    dctList.CompareMode = vbTextCompare

    With wks

        varList = .Range(.Cells(6, "H"), .Cells(Rows.Count, "H").End(xlUp)).Value2

        For d = LBound(varList) To UBound(varList)
            dctList.Item(varList(d, 1)) = vbNullString
        Next

        For Each varName In dctList
            .Range("a1").CurrentRegion.AutoFilter Field:=8, Criteria1:="=" & varName, Operator:=xlFilterValues

            Set wkbNew = Workbooks.Add
            .Range("A1").CurrentRegion.SpecialCells(xlCellTypeVisible).Copy _
                Destination:=wkbNew.Sheets(1).Range("A1")
            wkbNew.SaveAs strPath & varName & ".xlsx"
            wkbNew.Close

        Next

        .Range("a1").CurrentRegion.AutoFilter

    End With

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

    MsgBox "All done, individual spreadsheets have been saved", vbOKOnly, "Great success!"

End Sub

I think Power Query (aka Get & Transform) could do this much more straightforwardly. Two queries one filtering for one thing another for the other they could live in the same or two different workbooks - refresh and save as, done. You could VBA the bit that saves them into separate books and names them in various ways I guess.


Simplify & Reduce steps in the IsDistinct function Because I often have to deal with two Variants that may or may not be Null, we need a null-safe equality test, so I came up with IsDistinct which works but I have some issues with the code:

When I tried to keep it terse, the readability was harmed.
When I tried to expand the logic for readability, it still makes for some thinking.
I looked for potentials to short-circuit or otherwise result the number of steps to arrive at a result. In this case, it all takes 2 evaluations, unless both sides are non-null, in which case we have 3 evaluations.1

Can we do better?

Public Function IsDistinct(LeftValue As Variant, RightValue As Variant) As Boolean
    If IsNull(LeftValue) Then
        If IsNull(RightValue) Then
            IsDistinct = False
        Else
            IsDistinct = True
        End If
    Else
        If IsNull(RightValue) Then
            IsDistinct = True
        Else
            IsDistinct = Not (LeftValue = RightValue)
        End If
    End If
End Function

Inputs & Expected Outputs

LeftValue RightValue Result
 1         1          False
 1         0          True
 Null      1          True
 0         Null       True
 Null      Null       False
 ""        ""         False
 ""        Null       True

Note that it doesn't have to be just 0 and 1; it could be text, dates, or numbers. It's more important that when either inputs are Null, it should automatically be True since Null will always be "distinct" from any non-Null values. However, when both inputs are Null, then it's always False because we are considering them "equal" in this situation.2

The special case of an empty string and a Null is arguably problematic. I've swung both ways; sometimes I want empty string to be considered "equal" to a Null, sometimes I don't. In the IsDistinct as defined, they are not considered equal.3

1) In one of iterations, I considered starting with Result = (LeftValue = RightValue) and doing additional evaluation if the Result was Null, signaling that either or both inputs were Null. But IIRC, I found that it made for more steps since I had to evaluate each inputs with IsNull to determine whether both were Null and thus not distinct.

2) As a matter of fact, when I look at the first 3 lines:

If IsNull(LeftValue) Then
    If IsNull(RightValue) Then
        IsDistinct = False

My instinct is to go "wait, that's not right.", thinking about it and realize it IS correct. The fact that I stumble on that even more than once tells me that it's quite hard to read. Boo.

3) Thanks to @Ryan Wildry for pointing this blind spot out!

You have no idea how excited I am about this.  Years after learning about the Xor operator and I finally get to use it!!

VBA - Logical Operators: Xor Operator

  Called Logical Exclusion. It is the combination of NOT and OR Operator. If one, and only one, of the expressions evaluates to be True, the result is True.

The Xor seems like a great fit because both the parameters need to be tested for nulls and the values can not equal one another.

My Version

Public Function NotEquals(LeftValue As Variant, RightValue As Variant) As Boolean
    If IsNull(LeftValue) Xor IsNull(RightValue) Then
        NotEquals = True
    ElseIf LeftValue <> RightValue Then
        NotEquals = True
    End If
End Function

Results

Crude Tests

Option Explicit
Public Const Repetitions = 10000000

Public Function IsDistinct(LeftValue As Variant, RightValue As Variant) As Boolean
    If IsNull(LeftValue) Then
        If IsNull(RightValue) Then
            IsDistinct = False
        Else
            IsDistinct = True
        End If
    Else
        If IsNull(RightValue) Then
            IsDistinct = True
        Else
            IsDistinct = Not (LeftValue = RightValue)
        End If
    End If
End Function

Public Function NotEquals(LeftValue As Variant, RightValue As Variant) As Boolean
    If IsNull(LeftValue) Xor IsNull(RightValue) Then
        NotEquals = True
    ElseIf LeftValue <> RightValue Then
        NotEquals = True
    End If
End Function

Sub CompareResults()
    Dim SumOfTime As Double
    Debug.Print "Number of Repetitions: "; FormatNumber(Repetitions, 0)

    Debug.Print
    Debug.Print "IsDistinct Test"
    Debug.Print "Left"; Tab(8); "Right"; Tab(16); "Time"; Tab(24); "Result"
    SumOfTime = TestIsDistinct(1, 1)
    SumOfTime = SumOfTime + TestIsDistinct(1, 0)
    SumOfTime = SumOfTime + TestIsDistinct(Null, 1)
    SumOfTime = SumOfTime + TestIsDistinct(0, Null)
    SumOfTime = SumOfTime + TestIsDistinct(Null, Null)
    Debug.Print "Total Time for All IsDistinct Test: "; SumOfTime

    Debug.Print
    Debug.Print "NotEquals Test"
    Debug.Print "Left"; Tab(8); "Right"; Tab(16); "Time"; Tab(24); "Result"
    SumOfTime = TestNotEquals(1, 1)
    SumOfTime = SumOfTime + TestNotEquals(1, 0)
    SumOfTime = SumOfTime + TestNotEquals(Null, 1)
    SumOfTime = SumOfTime + TestNotEquals(0, Null)
    SumOfTime = SumOfTime + TestNotEquals(Null, Null)
    Debug.Print "Total Time for All NotEquals Test: "; SumOfTime

End Sub

Function TestIsDistinct(LeftValue As Variant, RightValue As Variant) As Double
    Dim t As Double
    t = Timer
    Dim Result As Boolean
    Dim n As Long
    For n = 1 To Repetitions
        Result = IsDistinct(LeftValue, RightValue)
    Next

    Dim SumOfTime As Double
    SumOfTime = Round(Timer - t, 4)

    Debug.Print LeftValue; Tab(8); RightValue; Tab(16); SumOfTime; Tab(24); Result

    TestIsDistinct = SumOfTime
End Function

Function TestNotEquals(LeftValue As Variant, RightValue As Variant) As Double
    Dim t As Double
    t = Timer
    Dim Result As Boolean
    Dim n As Long
    For n = 1 To Repetitions
        Result = NotEquals(LeftValue, RightValue)
    Next

    Dim SumOfTime As Double
    SumOfTime = Round(Timer - t, 4)

    Debug.Print LeftValue; Tab(8); RightValue; Tab(16); SumOfTime; Tab(24); Result

    TestNotEquals = SumOfTime
End Function


regex to extract version info I have written a small Python function to extract version info from a string.
Input is of format:

v{Major}.{Minor}[b{beta-num}]

Eg: v1.1, v1.10b100, v1.100b01
Goal is to extract Major, Minor and beta numbers.

import re
def VersionInfo(x):
    reg = re.compile('^v([0-9]+)([.])([0-9]+)(b)?([0-9]+)?$')
    return reg.findall(x)
if __name__ == '__main__':
    print(VersionInfo('v1.01b10'))
    print(VersionInfo('v1.01'))
    print(VersionInfo('v1.0'))

Output:

[('1', '.', '01', 'b', '10')]
[('1', '.', '01', '', '')]
[('1', '.', '0', '', '')]

Question is:

Is it sufficient to cover all cases?
Better regex?

^v([0-9]+)([.])([0-9]+)(b)?([0-9]+)?$

Not much to say but:

seems a bit strange to capture the . since that's the only value that could be there. Also [.] could be written mode simply as \..
also seems a bit strange to capture the b, unless v1.1b is specifically allowed. And you're trying to find that last digit group even if b isn't present - not a bug, but could be made clearer.

To address the second point, make the whole beta part optional:

^v([0-9]+)\.([0-9]+)(?:(b)([0-9]+)?)?$

If beta with no number isn't allowed, this can be simplified (and drop capturing b also in this case):

^v([0-9]+)\.([0-9]+)(?:b([0-9]+))?$

(The (?:...) construct is a non-capturing group.)


Convert size_t to big endian on Linux I see that on Linux there are various built-in functions to convert endianness for specific integer width types, and they are probably faster than anything one can write and compile on their own.  But I want to write a size_t (under Linux in C), which does not have a specified width, to big-endian array of bytes, as fast as possible.

Is this the fastest way?

#include <limits.h>

// write "from" to array of bytes "to" in big-endian fashion
void big_endian_size(unsigned char to[], size_t from) {

    unsigned char *p = to + (sizeof(size_t) - 1);

    while (1) {
        *p = from;

        if (to == p)
            break;

        p--;
        from >>= CHAR_BIT;
    }
}

If you're looking for performance then you should, at least, provide a specialized version for the most common cases:

void big_endian_size(uint8_t to[], size_t from) {
#if UINT32_MAX == SIZE_MAX
    // Specialization for 4 bytes size_t
#elif UINT64_MAX == SIZE_MAX
    // Same as above but for 8 bytes size_t
#else
    // Your current implementation...
#endif
}

Specialized versions may simply reuse this:

to[3] = from & 0x000000FF);
to[2] = (from & 0x0000FF00) >> 8;
// And so on...

Note that you may also simply return another size_t (instead of an array) with its bytes rotated. This will be considerably faster (also if implemented with a plain for to go through all bytes).

Also note that if you extract the 32 bit swap code into a separate function then you can use it both for 32 bit and 64 bit sizes (for example see byteswap.h for an implementation).

Do you need more? Assembly. For example on X86/X64 assembly you have BSWAP that does it in one instruction (I remember also ARM has but I don't remember the mnemonic), just check for target architecture to provide more and specialized versions.

Notes: Why &? Because truncation (let's imagine uint8_t val = 0xffffffff >> 8) is platform specific.


Replacing an F# loop over a mutable variable by an immutable approach Consider:

        let mutable m' = m
        while m' % i = 0L do
            m' <- m' / i

I've refactored it into:

        let m' =
            let rec exhaust m =
                if m % i = 0L then exhaust (m/i)
                else m
            exhaust m

but it's pretty obvious to me that the original code was way more concise and clear than this last one. Is there anything simple and clear that I'm missing regarding this refactor?

The full algorithm:

(* Calculates all the prime factors of a given integer *)
let primeFactors x =
    let rec primeFactors' = function
        | (m, _, r) when m = 1L -> r
        | (m, i, r) ->
            let mutable m' = m
            while m' % i = 0L do
                m' <- m' / i
            primeFactors' (m', (i+1L), (if m <> m' then i::r else r))
    List.rev (primeFactors' (x, 2L, []))

I would write it this way

let rec exhaust m i =
    match m % i with
    | 0L -> exhaust (m / i) i
    | _ -> m

Not a huge improvement, but I think it's idiomatic. Now let's look at primeFactors:

let primeFactors x =
    let rec primeFactors' = function
        | (m, _, r) when m = 1L -> r
        | (m, i, r) ->
            let m' = exhaust m i
            primeFactors' (m', (i+1L), (if m <> m' then i::r else r))
    List.rev (primeFactors' (x, 2L, []))

Let's get rid of the when:

let primeFactors x =
    let rec primeFactors' = function
        | (1L, _, r) -> r
        | (m, i, r) ->
            let m' = exhaust m i
            primeFactors' (m', (i+1L), (if m <> m' then i::r else r))
    List.rev (primeFactors' (x, 2L, []))

And tidy up a little

let primeFactors x =
    let rec primeFactors' = function
        | 1L, _, r -> r
        | m, i, r ->
            let m' = exhaust m i
            primeFactors' (m', i + 1L, if m <> m' then i::r else r)
    primeFactors' (x, 2L, []) |> List.rev

I know the style in F# is for short variable names, and I'm all for that for the most part, but I think in this case we can/should make them a bit clearer.

let rec exhaust n factor =
    match n % factor with
    | 0L -> exhaust (n / factor) factor
    | _ -> n

let rec primeFactors' = function
    | 1L, _, factors -> factors
    | n, factor, factors ->
        let m = exhaust n factor
        primeFactors' (m, factor + 1L, if n <> m then factor::factors else factors)

let primeFactors n =
    primeFactors' (n, 2L, []) |> List.rev


Summing all numbers that can be formed from a list of integers Following a challenge on HackerRank, I want to find the sum of all numbers that have no more than x 4's, y 5's, and z 6's module 10^9 + 7. I'd like to know how I could improve this code below both for style and performance. Also, what's the canonical way to get unique permutations of a list that can include repeated elements?

import itertools
import sys
import collections

#create initial list based on input
x, y, z = map(int, sys.stdin.readline().split(' '))
permute_list = [4]*x + [5]*y + [6]*z

# collect iterators to permutations of all possible lengths
permuted = []
for i in range(1,(x+y+z+1)):
    permuted.append(itertools.permutations(permute_list, i))

# collect unique permutations from iterators
# there will be many repeats, anyway to avoid this inefficiency?
dynamic_table = collections.defaultdict(lambda: 0)
mod_var = (10**9 + 7)
for it in permuted:
    for i in it:
        new_sum = ''.join(map(str, i))
        if not dynamic_table[new_sum]:
            dynamic_table[new_sum] = int(new_sum)

print(sum(dynamic_table.values()) % mod_var)

I tried a few ways of doing this. What most surprised me is that implementing with a dictionary, as above, seems to beat a set implementation by about 30%, time-wise. Why is this? Also, what are some better ways to implement this and/or tweaks to the above code?

Imagine you had to do the same with 4 distinct digits, a, b, c and d, and lets forget for now about numbers with less than 4 digits. There are 4! arrangements of these 4 digits, of which 3! each will have the a in the first, second, third and fourth positions. So the contribution of the digit a to the overall sum will be a * 3! * 1111, and the total sum of all numbers generated from these four digits ends up being (a + b + c + d) * 3! * 1111. It is easy to check that this works comparing to a brute-force solution:

from itertools import  permutations

def sum_them_quick(a, b, c, d):
    return (a + b + c + d) * 3 * 2 * 1 * 1111

def sum_them_slow(a, b, c, d):
    total = 0
    for digits in permutations([a, b, c, d], 4):
        total += int(''.join(str(d) for d in digits))
    return total

If you test this, you will find that, while they both produce the same result, the performance is already 100x faster for this small example:

>>> sum_them_quick(4, 5, 6, 7) ==  sum_them_slow(4, 5, 6, 7)
True
>>> %timeit sum_them_quick(4, 5, 6, 7)
1000000 loops, best of 3: 349 ns per loop
>>> %timeit sum_them_slow(4, 5, 6, 7)
10000 loops, best of 3: 54.9 µs per loop

Your case is not that simple, because you have to handle the repeats, but it isn't that much harder either. If you have x 4's, y 5's and z 6's, there are (x + y + z)! / x! / y! / z! different arrangements of those digits to form unique numbers. And similarly to the previous case, a 4 will show up in any given position x / (x + y + z) of the times. So similarly, the following function will compute the total sum in constant time:

from math import factorial

def sum_them_456(x, y, z):
    total = 0
    for j in range(x + y + z):
        total *= 10
        total += 1
    print(total)
    total *= 4*x + 5*y + 6*z
    total *= factorial(x + y + z - 1)
    total //= factorial(x) * factorial(y) * factorial(z)
    return total

There are cleverer ways of computing a quotient of factorials, but that is left as exercise.

You also have to handle all the possible permutations with less than the full x + y + z possible digits. There may be a better way of not having to brute-force your way through this, but I'm out of cleverness right now, so I am going to go with something very unsophisticated:

def sum_them_all_456(x, y, z):
    n = x + y + z
    total = 0
    trials = set()
    trials.add((x, y, z))
    while n > 0:
        new_trials = set()
        for trial in trials:
            total += sum_them_456(*trial)
            for idx in range(len(trial)):
                if trial[idx] > 0:
                    new_trial = trial[:idx] + (trial[idx] - 1,) + trial[idx+1:]
                    new_trials.add(new_trial)
        trials = new_trials
        n -= 1
    return total

It still manages to handle values of x, y or z in the tenths in the blink of an eye, but there has to be a better way for this.


Generation of a  in React without  wrapping elements In React, the render method must have one and exactly one child (although that child may have many more children). As a result, it becomes difficult to render elements that intrinsically need multiple elements as children without wrapping them in an unsemantic - and in the case of
, forbidden -
 element.

As I result, I wrote the following code to help generate a definition list from a model. I'd like to know what you guys think. Its being used in my company's application at the moment and I was wondering if there was anything I could improve on.

'use strict'
import React from 'react'
import createFragment from 'react-addons-create-fragment'
import isArray from 'lodash.isarray'

/**
 * Creates a
 element using React from the given map.
 * @param  {Map<string, any|Array<any>>} map A map of name-value pairs. The keys of the map are used as labels for definitions, so they should be legible. The values are used as the value of the definition. If there are multiple values to a definition (i.e, an array), then multiple
 elements will be created for the resultant
.
 * @return {ReactElement} A React element encapsulating the
.
 */
export default function createDefinitionList(map) {
  const labels = Object.keys(map)

  return

    {labels.map((label) => createDefinitionFragment(label, map[label]))}

}

/**
 * Creates a
 with associated
s inside of a React fragment. Fragments are keyed.
 * @param  {string} label A human-readable description of the definition
 * @param  {any|Array<any>} value a value, or a set of values. If given a set of values, multiple
 elements will be generated; these elements will be keyed using their array index.
 * @return {ReactElement} A definition list in React element form.
 */
function createDefinitionFragment(label, value) {
  return createFragment({
    definition:
{label}
,
    value: createDefinitionValueFragments(value)
  })
}

/**
 * Creates a React
 fragment for the given value. If value is an array, a fragment will be created which encapsulates all values.
 * @param  {any|Array<any>} value A singular value will return a react fragment containing just the one value encapsulated in a
. Otherwise, a Fragment will be returned that contains many
.
 * @return {ReactElement} A React fragment contain the definition values
 */
function createDefinitionValueFragments(value) {
  if (isArray(value)) {
    return value.map(function (val) {
      return
{val}

    })
  }

  return
{value}

}

Here is an example of the usage. This is basically how we use it now, except this model is retrieved via Ajax, and that's a lot of code for me to paste in a CR question. So, for sake of example, here's a finished call from one of those AJAX calls.

// Example of usage
const keyPerformanceIndicators = {
  'Calls': 0,
  'Tickets': 1,
  'Demos': [0, 10]
}

const definitionList = createDefinitionList(keyPerformanceIndicators)
React.render(definitionList, document.body)

The expected output ends up looking like this (data-reactid omitted for brevity)

Calls

0

Tickets

1

Demos

0

10

I intend to release this as a general-purpose library as this is a niche I don't think has yet been filled in React (surprisingly). I'd like any suggestions on improving it before doing so.

as of React 16 version you can use

<React.Fragment>

Term

Definition

</React.Fragment>

React.Fragment will not render any DOM, but it'll act as a container.
You can also use a short hand for React.Fragment as <>

<>

Term

Definition

</>

It works in the same way, except that it doesn't support any attributes or key.

https://reactjs.org/docs/fragments.html


Python Brainf*ck interpreter What do you think of my Brainf*ck interpreter?
What else can be done to increase speed?

#!/usr/bin/env python3

class InfiniteArray:
    def __init__(self):
        self.pstack, self.nstack = [], []
    def __getitem__(self, index):
        s = self.pstack if index >= 0 else self.nstack
        i = index if index >= 0 else -index + 1
        if i >= len(s):
            return 0
        return s[i]
    def __setitem__(self, index, value):
        s = self.pstack if index >= 0 else self.nstack
        i = index if index >= 0 else -index - 1
        if i >= len(s):
            s.extend([0 for _ in range(len(s), i+1 + 100)])
        s[i] = value
    def __str__(self):
        return str(list(reversed(self.nstack))) + ' | ' + str(self.pstack)

class StateMachine:
    def __init__(self, code, jump_table, debug=False):
        self.arr = InfiniteArray()
        self.pointer = 0
        self.i = 0
        self.code = code
        self.jt = jump_table
        self.debug = debug
        self.instrcount = 0

    def putc(self):
        from sys import stdout
        stdout.write(chr(self.arr[self.pointer]))
        stdout.flush()

    def getc(self):
        from sys import stdin
        c = stdin.read(1)
        self.arr[self.pointer] = ord(c)

    def plus1(self):
        self.arr[self.pointer] += 1

    def minus1(self):
        self.arr[self.pointer] -= 1

    def mvright(self):
        self.pointer += 1

    def mvleft(self):
        self.pointer -= 1

    def matchl(self):
        if not self.arr[self.pointer]:
            self.i = self.jt[self.i]

    def matchr(self):
        if self.arr[self.pointer]:
            self.i = self.jt[self.i]

    def nextcell(self):
        self.i += 1
        self.instrcount += 1

    def __str__(self):
        return str(self.arr) + '\n\n' + ''.join(map(str, self.code))

    def run(self):
        import datetime as dt
        ops = {'+': self.plus1,
               '-': self.minus1,
               '>': self.mvright,
               '<': self.mvleft,
               '.': self.putc,
               ',': self.getc,
               '[': self.matchl,
               ']': self.matchr }
        start = dt.datetime.now()
        while self.i < len(self.code):
            c = self.code[self.i]
            ops[c]()
            self.nextcell()
            if self.debug:
                print(self)
        end = dt.datetime.now()
        print(int(self.instrcount/(end-start).microseconds * 10**6), "instr/second")

def extract(file):
    code = []
    for c in file.read():
        if c in '><+-.,[]':
            code.append(c)
    jump_table = dict()
    stack = []
    count = 0
    for i, c in enumerate(code):
        if count < 0:
            raise SyntaxError("2muh ]")
        if c == '[':
            stack.append(i)
            count += 1
        if c == ']':
            jump_table[i] = stack[-1]
            jump_table[stack[-1]] = i
            stack.pop()
            count -= 1
    if count > 0:
        raise SyntaxError("unmatched [ at positions " + ', '.join(map(str, stack)))

    return code, jump_table

def main():
    from sys import argv
    options = {'debug': False}
    for i, name in enumerate(argv[1:]):
        print('no. {}: {}'.format(i+1, name))
        try:
            if name == '-':
                f = open('/dev/stdin')
            elif name.startswith('-'):
                if name == '-debug':
                    options['debug'] = True
                continue
            else:
                f = open(name)
        except:
            print("Error: no such file :<")
            continue
        try:
            code, mt = extract(f)
            f.close()
        except SyntaxError as e:
            print("Error:", e)
        finally:
            s = StateMachine(code, mt, debug=options['debug'])
            s.run()

if __name__ == '__main__':
    main()

This looks really nice to me, I have just a few minor remarks.

Imports buried in the code

Many imports are buried in some functions,
for example in putc and getc,
and I don't see a good reason for that.
It would be better to import the required modules at the top.

Complicated command line argument parsing

The command line argument parsing in the main function looks a bit complicated. I think it should be possible to refactor that to make it easier to read, and using a context manager for the input file handling.

Mutually exclusive if statements

The second if here should be an elif:

if c == '[':
    stack.append(i)
    count += 1
if c == ']':
    jump_table[i] = stack[-1]
    jump_table[stack[-1]] = i

Don't repeat yourself

The assignment of s and i are almost identical in these two functions:

def __getitem__(self, index):
    s = self.pstack if index >= 0 else self.nstack
    i = index if index >= 0 else -index + 1
    # ...

def __setitem__(self, index, value):
    s = self.pstack if index >= 0 else self.nstack
    i = index if index >= 0 else -index - 1
    # ...

I would add some helper functions to reduce the duplication.

Too dense formatting

It would be easier to read the code with a blank line between functions.


Add optional distance range to function I have a simple brute-force search function:

function run_query(search_data::Vector{Float64}, query::Vector{Float64}, search_f::Function)::Tuple{Float64, Int}
    current_best = Inf
    loc = -1
    q_len = length(query)

    for d_i in 1:(length(data) - q_len)

        dist = search_f(data[d_i:d_i+q_len-1], query)
        if dist < current_best
            current_best = dist
            loc = d_i
        end
    end

    return current_best, loc
end

I have an alternative version of the function which also returns the maximum distance found while searching to data:

function run_query_max(search_data::Vector{Float64}, query::Vector{Float64}, search_f::Function)::Tuple{Float64, Int, Float64}
    current_best = Inf
    loc = -1
    q_len = length(query)
    max_dist = 0.

    for d_i in 1:(length(data) - q_len)

        dist = search_f(data[d_i:d_i+q_len-1], query)

        if dist > max_dist
            max_dist = dist
        end

        if dist < current_best
            current_best = dist
            loc = d_i
        end
    end

    return current_best, loc, max_dist
end

This can be tested as follows:

function simple_dist(data::Vector{Float64}, query::Vector{Float64})::Float64
    return sum((data .- query) .^ 2)
end

data = [0., 0., 1., 2.,
        3., 1.1, 3., 3.,
        1., 0., 0., 1.,
        0., 0., 1., 4.5,
        2., 1., 0., 0.]

query = [1., 2., 3., 1.]
val, idx = run_query(data, query, simple_dist)
@assert (idx == 3)
@assert isapprox(val, 0.01, atol=0.001)

val, idx, max_dist = run_query_max(data, query, simple_dist)
@assert (idx == 3)
@assert isapprox(val, 0.01, atol=0.001)
@assert isapprox(max_dist, 21.25, atol=0.001)

This pattern of:

Basic search function
Add keeping track of maximum distance in search function

Occurs in multiple places in my code. What is a reasonable way to refactor it out?

I think this depends a lot on your motivation for separating these into two methods.

One simple option I would consider first is to just have 1 version of each of these functions to avoid the duplication in the first place.
The caller can just ignore the max_dist value if they don't need it.

If performance is an issue and max_distcalculation could be a bottleneck, you could add a Boolean argument to the single function to indicate if max_dist should be calculated or not.

If the logic for max_dist is complex enough to hurt the readability of the basic search, I think you may be better off going with the duplication instead of doing something more complex.  It could be done, but not in a way I would consider reasonable in most cases.


Calling a function from a dynamically loaded DLL (version 2) Please, have a look at the previous (bad) implementation and the review here.

After reading the suggested article at HowTo: Export C++ classes from a DLL, I have decided to use a plain C function approach. However, I want to use C++ code inside the DLL later. Anyway, the exported one will be a plain C function with the const char * argument.

In my earlier attempt, I tried to pass reference to the vector<string> argument, which is not possible or at least safe. The vector of strings was the result of parsing the line from a text file. Now, I am passing the line itself, and the parsing is done inside the DLL. The code of the caller and the type of the called function look like this:

typedef __declspec(dllimport) int (__cdecl *CONVERTPROC)(const char *);

int call_convert_from_dll(const std::string & dllname, const char * line)
{
    HINSTANCE hinstLib;
    CONVERTPROC convert;
    BOOL fRunTimeLinkSuccess = FALSE;

    // Get a handle to the DLL module.
    hinstLib = LoadLibrary(dllname.c_str());

    // If the handle is valid, try to get the function address.
    if (hinstLib != nullptr)
    {
        convert = (CONVERTPROC)GetProcAddress(hinstLib, "convert");

        // If the function address is valid, call the function.
        if (convert != nullptr)
        {
            fRunTimeLinkSuccess = TRUE;
            (convert)(line);
        }
        else {
            DWORD err = GetLastError();
            if (err == ERROR_PROC_NOT_FOUND)
                cerr << "procedure convert() was not found" << endl;
            else
                cerr << "runtime link failed: " << err << endl;
        }
        // Free the DLL module.
        FreeLibrary(hinstLib);
    }

    // If unable to call the DLL function, use an alternative.
    if (!fRunTimeLinkSuccess) {
        cerr << "Failed when using '" << dllname << "' library." << endl;
        return 1;
    }

    return 0;
}

The name of the called function (from the DLL) is passed as a string. Because of that, the extern "C" must be used to avoid identifier mangling.

The mentioned article also says that no exception should cross the boundary of the DLL module (if it is not the special case when both parts are written in C++ and compiled by the same version of the compiler). Because of that, the try/catch wraps the body of the called function. Any exception is transformed to the error code equal to 1:

extern "C" {          // we need to export the C interface

__declspec(dllexport) int __cdecl convert(const char * line)
{
    int err = 0;
    try {
        cout << "my.dll: '" << line << "'" << endl;
        vector<string> vs;
        StringTok(vs, line, " \t\n");
        err = xmain(vs);
    }
    catch (...) {
        return 1;
    }
    return err;
}

} // extern "C"

Can you see any other flaw in the code?

Certainly a better approach that the original. Only one 'flaw' that I noticed:

You ignore the return value from your convert function.

But I do have a couple of comments:

You may want to consider making line a const char * const (with associated other changes).
Put the type declaration next to the first use. i.e., rather than

HINSTANCE hinstLib;
// several lines
hinstLib = LoadLibrary(dllname.c_str());

do

HINSTANCE hinstLib = LoadLibrary(dllname.c_str());

Since you're in C++, use bool \ false etc rather than BOOL.
Depending on how frequently this would be called, you may want to adopt a RAII approach similar to Windows DLL Module Class. This could lead to some simplifications in the main flow of the code.
LoadLibrary and GetProcAddress are documented as returning NULL rather than std::nullptr. It may be totally silly, but I'd stick with the documentation.
You don't deal with the error case of LoadLibrary failing, with respect to GetLastError and giving a sensible error.
Consider using a reinterpret_cast<CONVERTPROC> rather than (CONVERTPROC).
You only return 1 or 0 from call_convert_from_dll - should it have a bool or enumerated return type?
Depending on what the effect of failure is, you may want to consider using exceptions, catching them further up the chain rather than handling failure in this function.

For your convert function:

The code implies the use of using namespace std. Please don't.
Rather than using an err variable, you could return immediately. The function is short enough to be understandable.
If any exceptions are likely to be thrown by inner code, catch them separately in the catch block and give details rather than 'catch all and dump'. Perhaps something like:

catch (const std::exception& e) {
    std::cerr << "Convert exception: " << e.what() << std::endl;
    return 1;
}
catch (...) {
    std::cerr << "Convert unspecified exception" << std::endl;
    return 1;
}


Find binary sequence in NumPy binary array As part of creating a software defined receiver and decoder, I want to find sync pulses in weather satellite data.  The data is first digitized to a 0-1 array.

The code below is working. The convolution method is sufficiently fast. The slow method is not.

I was wondering if there was a more efficient or "Pythonic" way to do it.

def findPulseSlow(data, pulse):
    # find indexes of occurrences of pulse in data
    # data and pulse are numpy arrays of 0-1 elements
    # tolerate up to 3 incorrect values
    # takes 2 minutes per Mb on AMD FX8150
    maxerr=3
    return np.fromiter( \
        ( i for i in range(0,len(data)-len(pulse)) \
            if sum(np.logical_xor(data[i:(i+len(pulse))], pulse))<=maxerr ),\
        np.int)

def findPulseConvolve2(data,pulse):
    maxerr=3
    required = len(pulse)-maxerr
    doubleConvolution = np.convolve(data,pulse[::-1])+\
                        np.convolve(1-data,1-pulse[::-1])
    return 1-len(pulse)+np.where(doubleConvolution>=required)[0]

Here is a complete test framework:

testPulse.py

import numpy as np

NOAAsyncA=np.concatenate( ([4*[0],7*[1,1,0,0],8*[0]]) )

def getFixedTestData():
    data = np.zeros(1000)
    syncL = len(NOAAsyncA)
    data[12:(12+syncL)]=NOAAsyncA
    data[257:(257+syncL)]=NOAAsyncA
    data[900:(900+syncL)]=NOAAsyncA
    return ([12,257,900], data)

def getRandomTestData():
    # create random 1 Megabit data, insert 10 NOAA sync pulses in data
    # return correct pulse start locations, data
    global NOAAsyncA
    data = np.random.randint(2, size=1000000)
    # make an ascending list of random spots to insert the pulse
    insertAidx = np.sort(np.random.randint(1000000, size=10))
    # insert the pulses
    for l in insertAidx:
        data[l:(l+len(NOAAsyncA))]=NOAAsyncA
    # return the pulse locations and the data
    return (insertAidx, data)

def findPulseSlow(data, pulse):
    # find indexes of occurrences of pulse in data
    # data and pulse are numpy arrays of 0-1 elements
    # tolerate up to 3 incorrect values
    # takes 2 minutes per Mb on AMD FX8150
    maxerr=3
    return np.fromiter( \
        ( i for i in range(0,len(data)-len(pulse)) \
            if sum(np.logical_xor(data[i:(i+len(pulse))], pulse))<=maxerr ),\
        np.int)

def findPulseConvolve1(data, pulse):
    # tests for locations of 1's only. Bad idea.
    # max error count
    maxerr=0
    required = sum(pulse)-maxerr
    return 1-len(pulse)+np.where(np.convolve(data,pulse[::-1])>=required)[0]

def findPulseConvolve2(data,pulse):
    maxerr=3
    required = len(pulse)-maxerr
    doubleConvolution = np.convolve(data,pulse[::-1])+\
                        np.convolve(1-data,1-pulse[::-1])
    return 1-len(pulse)+np.where(doubleConvolution>=required)[0]

def Test(name,generator,finder):
    global NOAAsyncA
    (correctLocations, data) = generator()
    syncAidx = finder(data, NOAAsyncA)
    passedTest = False
    if len(syncAidx)==len(correctLocations):
        if (syncAidx==correctLocations).all():
            passedTest = True
    print "Test: "+name
    print "Test Result: "+str(passedTest)
    print "found syncA at: "+str(syncAidx)
    print "should be at: "+str(correctLocations)
    return passedTest

Test("fixed findPulseConvolve1", getFixedTestData, findPulseConvolve1)
Test("fixed findPulseConvolve2", getFixedTestData, findPulseConvolve2)
Test("random findPulseConvolve1", getRandomTestData, findPulseConvolve1)
Test("random findPulseConvolve2", getRandomTestData, findPulseConvolve2)

Before I get to your specific question, here are some general comments:

Since you are working with binary data, you should tell NumPy that your dtype is bool everywhere that you can.  That will lower memory requirements and speed up certain operations.  For example, data = np.zeros(1000) in getFixedTestData() should become data = np.zeros(1000, dtype=bool).  The default NumPy dtype is float which is not what you want.
The python convention for naming functions is snake_case i.e. all lowercase with underscores, not camelCase.  So findPulseSlow should be find_pulse_slow etc.
The right approach for optimizing your currently too-slow function is to use line profiling.  I really like the line_profiler module.  If you use IPython you can use it very easily as an inline magic function.
Doing #3 will mean unpacking that formidable iterator comprehension you wrote!  Instead of squeezing it all on one line, I'd define a generator function for the iterator, and try to be extremely explicit so that every line has only one function call, like this:

def yield_convolve(arr_1, arr_2):
    """Yields indices of arr_1 where arr_2 nearly matches."""
    MAX_ERR = 3
    len_1, len_2 = len(arr_1), len(arr_2)  # I assume arr_2 is always shorter than arr_1
    min_matches = len_2 - MAX_ERR
    num_windows = len_1 - len_2
    for idx in xrange(num_windows):
        arr_1_window = arr_1[idx:(idx+len_2)]
        summand = np.equal(arr_1_window, arr_2)
        sum_ = np.count_nonzero(summand)
        condition = sum_ >= min_matches
        if condition:
            yield idx

def find_pulse_slow_revised(arr_1, arr_2):
    return np.fromiter(yield_convolve(arr_1, arr_2), dtype=int)

I was probably overly expressive in the function I made -- it could be cleaned up by avoiding assigment to so many temporary variables but when doing line profiling this style really helps isolate the slow steps.

Watch out for places where you are inadvertently causing interconversion of NumPy data types and native Python data types.  For example, sum(np.logical_xor(...) should be np.sum(np.logical_xor(...)
I thought the np.logical_xor part you did was clever, but to my eyes at least it was a bit easier to grok using len(pulse) - maxerr as a criterion and using np.equal instead of np.logical_xor, so that is what I did in my example above.
I did a few timing tests with my revised function and it was at least ~20-30x faster than your findPulseSlow().  Using np.sum instead of sum was responsible for most of the speedup.  Using np.count_nonzero instead of np.sum gave an additional 2× or so.  Here's an example of some code from my IPython notebook, along with some output from the line profiler.

_, fixed_dat = getFixedTestData()

%timeit findPulseSlow(fixed_dat, NOAAsyncA)

%timeit find_pulse_slow_revised(fixed_dat, NOAAsyncA)

%lprun -f find_pulse_slow_revised -f yield_convolve find_pulse_slow_revised(fixed_dat, NOAAsyncA)

10 loops, best of 3: 54 ms per loop
1000 loops, best of 3: 1.43 ms per loop

Timer unit: 1e-06 s

Total time: 0.004039 s
File: <ipython-input-95-5e22e2fbabc9>
Function: yield_convolve at line 1

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           def yield_convolve(arr_1, arr_2):
     2                                               """Yields indices of arr_1 where arr_2 nearly matches."""
     3         1            1      1.0      0.0      MAX_ERR = 3
     4         1            1      1.0      0.0      len_1, len_2 = len(arr_1), len(arr_2)  # I assume arr_2 is always shorter than arr_1
     5         1            0      0.0      0.0      min_matches = len_2 - MAX_ERR
     6         1            0      0.0      0.0      num_windows = len_1 - len_2
     7       961          407      0.4     10.1      for idx in xrange(num_windows):
     8       960          579      0.6     14.3          arr_1_window = arr_1[idx:(idx+len_2)]
     9       960         1511      1.6     37.4          summand = np.equal(arr_1_window, arr_2)
    10       960          642      0.7     15.9          sum_ = np.count_nonzero(summand)
    11       960          476      0.5     11.8          condition = sum_ >= min_matches
    12       960          422      0.4     10.4          if condition:
    13         3            0      0.0      0.0              yield idx

Total time: 0.006642 s
File: <ipython-input-95-5e22e2fbabc9>
Function: find_pulse_slow_revised at line 15

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    15                                           def find_pulse_slow_revised(arr_1, arr_2):
    16         1         6642   6642.0    100.0      return np.fromiter(yield_convolve(arr_1, arr_2), dtype=int)

Using the built-in np.convolve solution is definitely the way to go and is still way faster than even the improved "slow" method.


Python string clean up function with optional args I've got a function that I mainly use while web scraping. It gives me the ability to throw in a multi line address and clean it or a name field with unwanted characters and clean those, etc.

Below is the code and I would like to know if this is the best approach. If I should switch to recursive or stick with the while loop. Or if I should look at some other completely different approach. Examples of I/O commented in the code.

def clean_up(text, strip_chars=[], replace_extras={}):
    """
    :type text str
    :type strip_chars list
    :type replace_extras dict
    *************************
    strip_chars: optional arg
    Accepts passed list of string objects to iter through.
    Each item, if found at beginning or end of string, will be
    gotten rid of.
    example:
    text input: '       ,  ,      , .,.,.,.,,,......test, \t  this\n.is.a\n.test...,,,         , .'
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^------^^^^----^^-----^^-----^^^^^^^^^^^^^^^^^^
    strip_chars arg: [',', '.']
    output: 'test, this .is.a .test'
    *************************
    replace_extras: optional arg
    Accepts passed dict of items to replace in the standard
    clean_up_items dict or append to it.
    example:
    text_input: ' this is one test\n!\n'
                 ^--------^^^-----^^-^^
    replace_extras arg: {'\n': '', 'one': '1'}
    output: 'this is 1 test!'
    *************************
    DEFAULT REPLACE ITEMS
    ---------------------
    These can be overridden and/or appended to using the replace_extras
    argument.
    replace item      |   with
    <\\n line ending> - <space>
    <\\r line ending> - <space>
    <\\t tab>         - <space>
    <  double-space>  - <space>
    <text-input>      - <stripped>
    *************************
    """

    clean_up_items = {'\n': ' ', '\r': ' ', '\t': ' ', '  ': ' '}
    clean_up_items.update(replace_extras)

    text = text.strip()

    change_made = True
    while change_made:
        text_old = text
        for x in strip_chars:
            while text.startswith(x) or text.endswith(x):
                text = text.strip(x).strip()

        for key, val in clean_up_items.items():
            while key in text:
                text = text.replace(key, val)

        change_made = False if text_old == text else True

    return text.strip()

Substitution in multiple passes

Your function is slightly buggy in a non-deterministic way, due to the way you perform substitutions in multiple passes.  Performing string substitutions in multiple passes is usually a bad idea.  Here is another instance of such a bug.  The problem is that the result could vary depending on the iteration order through replace_extras.

Take this example:

>>> clean_up('acetone', replace_extras={
...     'one': '1',
...     'acetone': '(CH3)2CO',
...     'CO': 'carbon monoxide',
...     'C': 'carbon',
...     'CH3': 'methane'
... })

What will be the result?  If the 'one' substitution is done first, then it becomes 'acet1'.  If the 'acetone' substitution is done first, followed by the 'CO' substitution and the 'C' substitution, then it becomes '(carbonH3)2carbon monoxide'.  If it's 'acetone', then 'C', then 'CO', then it becomes '(carbonH3)2carbonO'.  Another possible outcome is '(methane)2carbon monoxide'.  All kinds of results are possible!

Therefore, I recommend doing substitutions in a single pass wherever possible, using regular expressions.  Regular expressions will always look for the leftmost longest match.1  With a regex substitution, the result will not be fed back for further processing.

Documentation and function design

You wrote a very long docstring, which is nice, but nowhere did you actually state the purpose of the function.

What is the purpose of the function?  There is a strip_chars phase, followed by a replace_extras phase.  By the single-responsibility principle, consider splitting the function into two functions, or at least writing it as a composition of two helper functions.

If you have specific examples of inputs and their corresponding outputs, it would be a good idea to write them as doctests instead.

Suggested solution

import re

def clean_up(text, strip_chars=[], replace_extras={}):
    r"""
    Remove all occurrences of strip_chars and whitespace at the beginning
    and end of each line, then perform string substitutions specified by
    the replace_extras dictionary (as well as normalizing all whitespace
    to a single space character), and then strip whitespace from the
    beginning and end.

    >>> clean_up('       ,  ,      , .,.,.,.,,,......test, \t  this\n'
    ...     '.is.a\n'
    ...     '.test...,,,         , .', strip_chars=',.')
    'test, this .is.a .test'

    Any consecutive whitespace is normalized to a single space, but
    you can override these implicit substitutions in replace_extras.

    >>> clean_up(' this is one test\n!\n', replace_extras={'\n': '', 'one': '1'})
    'this is 1 test!'
    """
    # Handle strip_chars
    strip_items = '|'.join(re.escape(s) for s in strip_chars)
    strip_re = r'^(?:{}|\s)+|(?:{}|\s)+$'.format(strip_items, strip_items)
    text = re.sub(strip_re, '', text, re.MULTILINE)

    # Normalize whitespace and handle replace_extras
    replace_keys = list(replace_extras.keys())
    replace_keys.sort(key=len, reverse=True)
    replace_re = '|'.join([re.escape(s) for s in replace_keys] + [r'\s+'])
    return re.sub(
        replace_re,
        lambda match: replace_extras.get(match.group(), ' '),
        text
    ).strip()


Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded Given the mapping a = 1, b = 2, ... z = 26, and an encoded message,
  count the number of ways it can be decoded.

  For example, the message '111' would give 3, since it could be decoded
  as 'aaa', 'ka', and 'ak'.

  You can assume that the messages are decodable. For example, '001' is
  not allowed.

class DailyCodingProblem7 {

    public static void main(String args[]) {
        String message = "11111111";
        int n=message.length();
        Integer[] ways=new Integer[n+1];
        int res = solution(message,n,ways);
        System.out.println(res);

    }

    private static int solution(String message,int k,Integer[] ways) {
        int n=message.length();
        if(k==0)
        {
            return 1;
        }
        if((int)message.charAt(n-k)==0)
        {
            return 0;
        }

        if(ways[k]!=null)
        {
            System.out.println(k+" : " +ways[k]);
            return ways[k];
        }
        ways[k]=solution(message,k-1,ways);
        if(k>=2 && Integer.valueOf(message.substring(n-k,n-k+2))<26)
        ways[k]+=solution(message,k-2,ways);
        return ways[k];

    }

}

If you observe the flow, we can notice ways[k] only needs the most recent 2 values this ways[k-1] and ways[k-2]. Should I use a Hashmap or there is a better approach?

1 : 1
2 : 2
3 : 3
4 : 5
5 : 8
6 : 13
34

Houston, you have some bugs

The algorithm counts incorrectly in some cases involving zeros.
For example, there's only one way to make "10" or "20", not 2.

A different problem is the overly strict condition <26,
which excludes "26" even it can be decoded to z.

Beware of string slicing

String.substring creates a new string.
This could become expensive when repeated often.
If you change the logic to work with a char[] instead of a String,
then you can check if the first digit is '1',
or the first digit is '2' and the second digit is <= '6'.

Unnecessary code

This condition will never be true:

if((int)message.charAt(n-k)==0)

The characters in the input are in the range of '0'..'9',
therefore their int values are in the range of 48..57.

Unnecessary Integer[]

You could safely replace Integer[] with int[],
and use a condition on zero value instead of null value.


Word counter for text files I've made a program that works, but i want to make it reusable. This code reads in a dictionary object created in another class (that i made), as well as read in a text file to put in said dictionary object. The code then loads in another text file, compares it with the dictionary, updates its frequency values and outputs to a vector. Everything works, but as i said i'm looking to make it reusable. What i mean by this is once the values have been stored in the vector, i'd like the dictionaries frequency values to reset back to 0, ready for the next text document to be compared with the dictionary, then output that to a different vector - this process will be repeated 10-12 times.

String Counter

public class StringCounter {

private LinkedList<Integer> list = new LinkedList<>();

public StringCounter(LinkedList<Integer> list) {
    this.list = list;
}

public static void main(String[] args) {

    HashMap<String, Integer> dictionary = new HashMap<String, Integer>();

    List<String> textFileList = Arrays.asList("Test.txt", "Test2.txt");

    try {

        Dictionary reader = new Dictionary(dictionary);

        for (String text : textFileList) {
            reader.fileScanner(text);
        }

        Scanner textFile = new Scanner(new File("Test4.txt"));
        ArrayList<String> file = new ArrayList<String>();

        while(textFile.hasNext()) {
            file.add(textFile.next().trim().toLowerCase());
        }

        for(String word : file) {
            Integer dict = dictionary.get(word);
            if (!dictionary.containsKey(word)) {
                    dictionary.put(word, 1);
            } else {
                    dictionary.put(word, dict + 1);
            }
        }

        textFile.close();

        } catch(FileNotFoundException e){
            e.printStackTrace();
        }

    Vector<Integer> vec1 = new Vector<>(dictionary.values());

    for (Integer count : vec1) {
        System.out.println(count);
    }
}
}

Dictionary

public class Dictionary {
    // Declare set in a higher scope (making it a property within the object)
    private HashMap<String, Integer> dictionary = new HashMap<String, Integer>();

    // Assigns the value of the parameter to the field of the same name
    public Dictionary(HashMap<String, Integer> dictionary) {
        this.dictionary = dictionary;
    }

    // Gets input text file, removes white spaces and adds to dictionary object
    public void fileScanner(String textFileName) {
        try {

            Scanner textFile = new Scanner(new File(textFileName));

            while (textFile.hasNext()) {
                 dictionary.put(textFile.next().trim(), 0);
            }

            textFile.close();

        } catch (FileNotFoundException e) {
             e.printStackTrace();
        }
    }

    public void printDict(HashMap<String, Integer> dictionary) {
        System.out.println(dictionary.keySet());
    }
}

Usage of interfaces

HashMap<String, Integer> dictionary = ...

Try to use interfaces on the lefthand side as a best practice: Map, List,  ... as it will make you independent of hashmap, linkedhashmap,...

also try not to use vector unless really necessary (https://stackoverflow.com/questions/2986296/what-are-the-differences-between-arraylist-and-vector)

Naming

HashMap<String, Integer> dictionary = new HashMap<String, Integer>();
...
Dictionary reader = new Dictionary(dictionary);

There is a class dictionary, a map with the same name and when initalizing an instance of Dictionary, then it is called "reader". This is confusing

reader.fileScanner(text)

This method name does not really indicate an action. reader.scanFile(text) would be better.

Reusing dictionary data

you could make the counting of the words a method of the dictionary where you build a new map with only a count for the words encountered in the new text file(s) and return that map.

Comments

avoid comments like

// Assigns the value of the parameter to the field of the same name

as they describe what you do in the code, which you can see by reading the code. When putting a comment then at least tell why some piece of code is implemented as such (specific issue, specific algorithm, ...)

Error handling

e.printstacktrace is by preference replaced by a logging framework (log4j2, logback, slf4j as façade, ...)
Perhaps you can make the method throw ioException and make the calling code handle this?


Weather Forecast Web Application I've made a Python Flask app and I have some questions about the structure of the main module (equivalent of index.py).
Here is what it looks like:
from flask import Flask, render_template

import database as db
import weather_forecast as wf
import os

app = Flask(__name__)

@app.route("/")
@app.route("/home")
def home():
    return render_template('home.html',
                       sites=db.create_site_list_sqlite(),
                       api_key=os.environ.get('GOOGLE_MAPS_JS_API_KEY'))

@app.route("/contact")
def contact():
    return render_template('contact.html')

@app.route("/weather_forecast/<climbing_area>/<city_id>/<lat>/<lon>/<weather_site>")
#creates url using climbing area name, city id, lat, lon, and location of weather site
def weather_forecast(climbing_area, city_id, lat, lon, weather_site):

    return render_template('weather_forecast.html',
                       climbing_area=climbing_area,
                       city_id=city_id,
                       daily_forecast=wf.format_daily_forecast(city_id),
                       extended_forecast=wf.format_extended_forecast(city_id),
                       historical_forecast=wf.get_historical_weather(lat, lon),
                       dates=wf.get_date_range(),
                       lat=lat,
                       lon=lon,
                       weather_site=weather_site,
                       sites=db.create_site_list_sqlite(),
                       api_key=os.environ.get('GOOGLE_MAPS_JS_API_KEY'),
                       image_url=wf.image_choice(lat, lon, city_id))

if __name__ == '__main__':
    app.run(debug=True)

I have three pages in my application, home, contact, and a dynamically created weather_forecast url.
Basically, when the home() function runs and renders the home page template, it runs this line: sites=db.create_site_list_sqlite()
The create_site_list_sqlite() function returns a bunch of data from an SQLite database, which is used to populate some a href hyperlinks. When a user clicks on one of those links, it goes to a weather forecast page, created by the def weather_forecast() route. That same data is then used to populate the URL in the proceeding weather forecast page.
My reason for doing this is, it was the best way I could figure out to run the create_site_list_sqlite() function. I could have populated the weather_forecast url by re-running that function but it seemed redundant.
Is this good practice to run the create_site_list_sqlite() function (or any others) as few times as possible?
Also, because I needed several pieces of data from what that function returns (climbing_area, city_id, lat, lon, and weather_site), the url for a weather forecast page is rather long. I personally think its fine but is there some reason to tighten this up if possible, just as an example, here is what one of the weather forecast page URLs looks like:
http://localhost:5000/weather_forecast/Ibex/5538080/38.881/-113.461/Delta

Thank you for any input.

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


Wrapping an asynchronous generator in Python Since Python 3.6 and PEP 525 one can use asynchronous generator:

import asyncio

async def asyncgen():
    yield 1
    yield 2

async def main():
    async for i in asyncgen():
        print(i)

asyncio.run(main())

I created a function which is able to wrap any asynchronous generator, the same way you would wrap a basic function using @decorator.

def asyncgen_wrapper(generator):

    async def wrapped(*args, **kwargs):
        print("The wrapped asynchronous generator is iterated")

        gen = generator(*args, **kwargs)

        try:
            value = await gen.__anext__()
        except StopAsyncIteration:
            return

        while True:
            to_send = yield value

            try:
                value = await gen.asend(to_send)
            except StopAsyncIteration:
                return

    return wrapped

Wrapping an asynchronous generator seems quite complicated compared to wrapping a basic generator:

def gen_wrapper(generator):
    def wrapped(*args, **kwargs):
        return (yield from generator(*args, **kwargs))
    return wrapped

I mainly concerned about correctness of my wrapper. I want the wrapper to be as transparent as possible regarding the wrapped generator. Which leads me to have two questions:

Is there a more straightforward way to implement a decorator for asynchronous generators?
Does my implementation handle all possible edge cases (think to asend() for example)?

"Correct" is nebulous. If it were to mean here something like "the semantics of any wrapped generator through the public API is the same as if it were not wrapped, apart from a print statement before the generator is created", then, no, the code isn't correct since it doesn't preserve the effects of raising an exception or closing the generator. For example,

import asyncio

class StopItNow( Exception ):
    pass

async def f():
    try:
        yield 0
    except StopItNow:
        yield 1

async def g( f ):
    x = f()
    print( await x.asend( None ) )
    print( await x.athrow( StopItNow ) )

asyncio.run( g( f ) )
asyncio.run( g( asyncgen_wrapper( f ) ) )

. I think it would be a non-trivial undertaking to "correctly" implement a wrapper. Interestingly, in the same PEP (525) that you've linked in your question,

  While it is theoretically possible to implement yield from support for asynchronous generators, it would require a serious redesign of the generators implementation.

https://www.python.org/dev/peps/pep-0525/#asynchronous-yield-from

. You might find that it's a whole lot easier to implement some sort of injection or parameterise the generator itself to accept callables.

Otherwise, from my experimentation and taking hints from PEP 380, there are implementation details that are omitted from PEP 525 that would be necessary to emulate the behaviour of an unwrapped generator.

This is the result of some toying around:

import functools
import sys

def updated_asyncgen_wrapper( generator ):

    @functools.wraps( generator )
    async def wrapped( *args, **kwargs ):
        print( "iterating wrapped generator" )

        gen = generator( *args, **kwargs )
        to_send, is_exc = ( None, ), False

        while True:
            try:
                do = gen.athrow if is_exc else gen.asend
                value = await do( *to_send )
            except StopAsyncIteration:
                return
            try:
                to_send, is_exc = ( (yield value), ), False
            except GeneratorExit:
                await gen.aclose()
                raise
            except:
                to_send, is_exc = sys.exc_info(), True

    return wrapped

. This isn't "correct" either, since it doesn't disambiguate between an attempt to close the generator and an explicit throw of an instance of GeneratorExit, which is, though, marked distinctly for usage by the former case. This might be good enough for internal use.


Kadane's Algorithm Variant (Start Index and End Index with Sub Array returned even for all negative numbers) Here is an attempt to extend the Kadane's Algorithm to return the sub array itself instead of the sum of maximum sub array.  This must work irrespective of the original array having all positive or negative numbers.

public class MaxSubArray {

    public static void main(String[] args) {
        int array[] = {10, -9, 4, 5, 90, -19, 19}; // Max sum is 100
        //int array[] = {4, -3, 6}; // Max Sum is 7
        //int array[] = {-1, -2, -3}; // Max Sum is -1
        //int array[] = {1, -2, -3}; // Max Sum is 1
        //int array[] = {-4, -3, -6}; // Max Sum is -3
        //int array[] = {-6, 0, 5}; // Max Sum is 5
        //int array[] = {0, 0, 0}; // Max Sum is 0
        int[] maxSubArray = getMaxSubArray(array);
        System.out.println(Arrays.toString(maxSubArray));
    }

    // Kadane's Alorithm Variant (Start Index and End Index of Sub Array even for all negative numbers)
    private static int[] getMaxSubArray(int[] array) {
        if (array == null || array.length == 0) {
            return array;
        } else {
            int startIndex = 0, endIndex = 0;
            int maxSoFar = array[0], maxEndingHere = array[0];
            for (int i = 1; i < array.length; i++) {
                if(maxSoFar < array[i] && array[i] >= maxEndingHere + array[i]) {
                    maxEndingHere = array[i];
                    startIndex = i;
                    endIndex = i;
                } else {
                    maxEndingHere += array[i];
                }
                if(maxEndingHere > maxSoFar) {
                    maxSoFar = maxEndingHere;
                    endIndex = i;
                }
            }
            return Arrays.copyOfRange(array, startIndex, endIndex + 1);
        }
    }
}

It will fail in the case 8, -19, 5, -4, 20. The startIndex and endIndex will not update until 20, but the start should be 5.