text:
Q: No buttons/labels/anything will re-appear after I set alpha back to 1.0 What I want: After the Viewcontroller is called, I want to fade in all my elements in this Viewcontroller, except for the background. The background must stay.
What goes wrong: As you see in my code, for something to fade in, it first needs to be removed. The remove part is doing great. But, when I want it to re-appear, nothing happens. When I use the print function to see the alpha of a random label, it is set to 1.0. I can not figure out what I am doing wrong.
This is my code:
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    Removeeverything()
    Fadein()
}

func Removeeverything() {
    for view in self.view.subviews as [UIView] {
        if let btn = view as? UIButton {
            UIView.animateWithDuration(0.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {

                btn.alpha = 0.0

                }, completion: nil)
        }
    }
    for view in self.view.subviews as [UIView] {
        if let btn = view as? UILabel {
            UIView.animateWithDuration(0.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {

                btn.alpha = 0.0

                }, completion: nil)
        }
    }
    for view in self.view.subviews as [UIView] {
        if let btn = view as? UIImageView {
            UIView.animateWithDuration(0.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {

                btn.alpha = 0.0

                }, completion: nil)
        }
    }
}

func Fadein() {
    Backgrond.alpha = 1.0
    for view in self.view.subviews as [UIView] {
        if let btn = view as? UIButton {
            UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {

                btn.alpha = 1.0

                }, completion: nil)
        }
    }
    for view in self.view.subviews as [UIView] {
        if let btn = view as? UILabel {
            UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {

                btn.alpha = 1.0

                }, completion: nil)
        }
    }
    for view in self.view.subviews as [UIView] {
        if let btn = view as? UIImageView {
            UIView.animateWithDuration(0.7, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {

                btn.alpha = 1.0

                }, completion: nil)
        }
    }

}

A: Just a thought, have you tried setting the alpha to something unrecognizably low like 0.01 rather than removing them entirely? You could also try matching the color of the button to the background and then fading it back in that way.
You may also need to call self.background.alpha or view.background.alpha
Also, you should really camel-case your function names.

A: I'd say that the problem is that UIView.animateWithDuration is executed asynchronous (that is - your fadeIn() function will execute before the animations in removeEverything() are complete).
Simply remove the UIView.animateWithDuration operations from your Removeeverything(). Since you've set the duration argument to 0.0 nothing will really change (except that the code should now work)
func removeEverything() {
    for v in view.subviews.filter({ $0 is UIButton || $0 is UILabel || $0 is UIImageView }) {
        v.alpha = 0
    }
}

func fadeIn() {
    // Background.alpha = 1.0
    UIView.animateWithDuration(1.0, delay: 0, options: .CurveEaseIn, animations: {
        for v in view.subviews.filter({ $0 is UIButton || $0 is UILabel }) {
            v.alpha = 1
        }
    }, completion: nil)
    UIView.animateWithDuration(0.7, delay: 0, options: .CurveEaseIn, animations: {
        for v in view.subviews.filter({ $0 is UIImageView }) {
            v.alpha = 1
        }
    }, completion: nil)
}

That code snippet should work as expected. I used the filter function on the array and got rid of a couple of unnecessary casts to make the code more readable. Hope it helps!


text:
Q: Rearranging a string based on specific requirements Hi there so I am looking to build this python function with simple things like def, find etc. so far I know how to get the first part of the code.
Given a string such as "HELLODOGMEMEDOGPAPA", I will need to return a list that gives me three things:
Everything before the word dog which i will denote as before_dog
The word dog until dog appears again dog_todog
Everything after the second time dog appears will be denoted by after_todog
The list will be in the form [before_dog,dog_todog,after_todog].
so for example given ("HELLODOGMEMEDOGPAPADD") this will return the list
("HELLO","DOGMEME","DOGPAPADD")
another example would be ("HEYHELLOMANDOGYDOGDADDY") this would return the list
("HEYHELLOMAN","DOGY","DOGDADDY")
but if I have ("HEYHELLODOGDADDY")
the output will be ("HEYHELLO","DOGDADDY","")
also if dog never appears ("HEYHELLOYO") then the output will be ("HEYHELLOYO,"","")
This is what I have so far:
def split_list(words):
    # declare the list
    lst = []
    # find the first position
    first_pos=words.find("DOG")
    # find the first_pos
    before_dog = words [0:first_pos]
    lst.append(before_dog)
    return lst

A: Funny function split_2_dogs() with re.findall() function:
import re

def split_2_dogs(s):
    if s.count('DOG') == 2:   # assuring 2 dogs are "walking" there
        return list(re.findall(r'^(.*)(DOG.*)(DOG.*)$', s)[0])

print(split_2_dogs("HELLODOGMEMEDOGPAPADD"))
print(split_2_dogs("HEYHELLOMANDOGYDOGDADDY"))

The output:
['HELLO', 'DOGMEME', 'DOGPAPADD']
['HEYHELLOMAN', 'DOGY', 'DOGDADDY']

Alternative solution with str.index() and str.rfind() functions:
def split_2_dogs(s):
    if 'DOG' not in s: return [s,'']
    pos1, pos2 = s.index('DOG'), s.rfind('DOG')
    return [s[0:pos1], s[pos1:pos2], s[pos2:]]

A: Splitting at DOG is the key!! This code will for all the cases that you have mentioned.
from itertools import izip_longest

words = 'HEYHELLODOGDADDY'
words = words.split("DOG")
words = ['DOG'+j if i>0 else j for i,j in enumerate(words)]
# words = ['HEYHELLO', 'DOGDADDY']
ans = ['','','']
# stitch words and ans together
ans = [m+n for m,n in izip_longest(words,ans,fillvalue='')]

print ans

Output :
['HEYHELLO', 'DOGDADDY', '']

A: This is pretty easy to do using the split function. For example, you can split any string by a delimiter, like dog, as so:
>>> chunks = 'HELLODOGMEMEDOGPAPA'.split('DOG')
>>> print(chunks)
['HELLO', 'MEME', 'PAPA']

You could then use the output of that in a list comprehension, like so:
>>> dog_chunks = chunks[:1] + ["DOG" + chunk for chunk in chunks[1:]]
>>> print(dog_chunks)
['HELLO', 'DOGMEME', 'DOGPAPA']

The only slightly tricky bit is making sure you don't prepend dog to the first string in the list, hence the little bits of slicing.

A: Split the string at 'DOG' and use conditions to get the desired result
s = 'HELLODOGMEMEDOGPAPADD'
l = s.split('DOG')
dl = ['DOG'+i for i in l[1:]]
[l[0]]+dl if l[0] else dl

Output:
['HELLO', 'DOGMEME', 'DOGPAPADD']

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does code format affect performance? I think I have came across a few times when I reformat some segment of code, it performed the way I wanted it to other than the other poorly formatted segment of code? Does code format affect performance? Or is that a myth?

A: To the compiler/interpreter it matters very little how well formatted and/or commented your code is. It only increases the parsing time by a very tiny amount because the parser has more characters to process (and mostly skip).
In most languages, the compiler/interpreter would be perfectly happy if you present your code as a single long line without any comments at all.
On the other hand, for human readers (including you in a few months time) it makes a world of difference if the code is well-formatted, well-commented and easily readable.
With well-written code, you can usually glance over it to get an idea of what the code is doing. If the code has poor or no formatting,then you really have to pay attention to understand the code which takes significantly more time and energy.

A: In a compiled language, any superfluous whitespaces, comments or other elements without syntactical meaning do not survive the tokenization step of the compilation, so it doesn't make a difference at all for the resulting binary (at least for the executable parts - some compilers might embed original sourcecode in the generated binary for debugging purposes, but those parts of the binary aren't executed).
In purely interpreted languages, the interpreter needs to parse all whitespaces. So formating can actually slow down the interpreter a tiny bit. But more advanced* interpreters usually compile the code in-memory to an optimized representation ("bytecode") before they execute it . In this step, whitespaces are usually also stripped, so it shouldn't matter for runtime either.
*in this case "more advanced" means "anything you would use in a 2014 production environment".

A: The only time I think format matters is with dynamically downloaded code - ie things like javascript where huge blocks of comments and/or very long variable names will slow down the download, but even then this does not affect the compile time. (and the download time can be fixed by minimising the javascript file).
For compiled files, the source is just a collection of symbols separated by whitespace. The compile doesn't care how these are formatted, a single long line would be just as good as a nicely formatted source file, as far as the compiler is concerned (admittedly some languages would care, eg Python that relies on formatting, particularly new line indentation, but even that doesn't affect the speed of compilation).
Formatting is for people, not for computers. Its important for that reason.


text:
Q: git lfs fails to track a file after I rename it I keep running into this issue where I rename a file that is being tracked under git lfs, and when I push up the change to my repo, the file is no longer being tracked by git lfs.
Does anyone know how to resolve this?

A: Apparently git add --renormalize . resolves this issue.

A: I erased the line of the file from .gitattributes and then ran git lfs track <new_file_path>


text:
Q: Converting Lat/Long coordinates to ESRI format Currently I have a CSV file which has Lat/Long coordinates which I got from the batch geocoding site, http://www.findlatitudeandlongitude.com/batch-geocode/#.VkWv97fNy70.
I believe these are obtained from Google maps. I would like to map these coordinates. However, when I try to use Layer>Add Delimited Text layer, and select my Long and Lat coordinates all I get is errors.
For reference the coordinates in my CSV file are as such.

51.494738 -9.720526

While when I upload my map into QGIS and zoom in to a region the coordinates which appear on the bottom of the screen are as such;

152930,309827

How do I go about either converting my coordinates in my CSV so they can be read in QGIS or can I change the coordinates of my Shapefile?


text:
Q: Rails Kaminari - How to Show Pagination Links at the Top and Bottom of the Page? The title pretty much says it all.  I don't want the user to have to scroll back to the top before they can select the next page.
I can pull out the query string and write my own logic to build the appropriate links, but I can't believe this isn't built in.

A: So far, this is the quickest way I've seen to do it.
Kaminari creates this already at the top of the page:

So I added, at the bottom of the page:

Then added the following javascript to the page:
$(function(){
    $('.pagination').clone().appendTo('.bottomPageLinks');
});

If someone knows a native Kaminari route that avoids the added complication, I'd still like to know about that.

A: <%= paginate @your_model %>

Should go at the bottom, outside of your ul/form.


text:
Q: Slow response from autocomplete I have applied an auto-complete functionality to two textFields.  For this I used AutocompleteDecorator.  I have observed it slowing down to the point where I am unable to even enter a single character.  Any solution for this?
Thanks
   JTextArea textArea = main.getEditor();
   String content = textArea.getText();

    try {
        if (content.length() > 0) {
            String[] lines = content.split("\n");
            String txt1 = null;
            String txt2 = null;

            for (String line : lines) {
                txt1= line.substring(0, 10);
                txt2 = line.substring(11, 15);

                listTxt1.add(txt1);
                listTxt2.add(txt2);
            }
            AutoCompleteDecorator.decorate(txtField1, listTxt1, false);
            AutoCompleteDecorator.decorate(txtField2, listTxt2, false);
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }

A: From my comment I decided to verify this.
I added 1000 random alphabetic Strings via to my dictionary via:
for (int i = 0; i < 1000; i++) {
    words.add(generateString(r, "abcdefghijklmnopqrstuvwxyz", 10));
}

...

public static String generateString(Random rng, String characters, int length) {
    char[] text = new char[length];
    for (int i = 0; i < length; i++) {
        text[i] = characters.charAt(rng.nextInt(characters.length()));
    }
    return new String(text);
}

and is no visible slow down at all.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JWindow;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 * @author David
 */
public class Test {

    Random r = new Random();

    public Test() {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTextField f = new JTextField(10);

        //create list for dictionary this in your case might be done via calling a method which queries db and returns results as arraylist
        ArrayList<String> words = new ArrayList<>();

        for (int i = 0; i < 1000; i++) {
            words.add(generateString(r, "abcdefghijklmnopqrstuvwxyz", 10));
        }

        AutoSuggestor autoSuggestor = new AutoSuggestor(f, frame, words, Color.WHITE.brighter(), Color.BLUE, Color.RED, 0.75f);

        JPanel p = new JPanel();

        p.add(f);

        frame.add(p);

        frame.pack();
        frame.setVisible(true);
    }

    public static String generateString(Random rng, String characters, int length) {
        char[] text = new char[length];
        for (int i = 0; i < length; i++) {
            text[i] = characters.charAt(rng.nextInt(characters.length()));
        }
        return new String(text);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test();
            }
        });
    }
}

class AutoSuggestor {

    private final JTextField textField;
    private final Window container;
    private JPanel suggestionsPanel;
    private JWindow autoSuggestionPopUpWindow;
    private String typedWord;
    private final ArrayList<String> dictionary = new ArrayList<>();
    private int currentIndexOfSpace, tW, tH;
    private DocumentListener documentListener = new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent de) {
            checkForAndShowSuggestions();
        }

        @Override
        public void removeUpdate(DocumentEvent de) {
            checkForAndShowSuggestions();
        }

        @Override
        public void changedUpdate(DocumentEvent de) {
            checkForAndShowSuggestions();
        }
    };
    private final Color suggestionsTextColor;
    private final Color suggestionFocusedColor;

    public AutoSuggestor(JTextField textField, Window mainWindow, ArrayList<String> words, Color popUpBackground, Color textColor, Color suggestionFocusedColor, float opacity) {
        this.textField = textField;
        this.suggestionsTextColor = textColor;
        this.container = mainWindow;
        this.suggestionFocusedColor = suggestionFocusedColor;
        this.textField.getDocument().addDocumentListener(documentListener);

        setDictionary(words);

        typedWord = "";
        currentIndexOfSpace = 0;
        tW = 0;
        tH = 0;

        autoSuggestionPopUpWindow = new JWindow(mainWindow);
        autoSuggestionPopUpWindow.setOpacity(opacity);

        suggestionsPanel = new JPanel();
        suggestionsPanel.setLayout(new GridLayout(0, 1));
        suggestionsPanel.setBackground(popUpBackground);

        addKeyBindingToRequestFocusInPopUpWindow();
    }

    private void addKeyBindingToRequestFocusInPopUpWindow() {
        textField.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
        textField.getActionMap().put("Down released", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {//focuses the first label on popwindow
                for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
                    if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
                        ((SuggestionLabel) suggestionsPanel.getComponent(i)).setFocused(true);
                        autoSuggestionPopUpWindow.toFront();
                        autoSuggestionPopUpWindow.requestFocusInWindow();
                        suggestionsPanel.requestFocusInWindow();
                        suggestionsPanel.getComponent(i).requestFocusInWindow();
                        break;
                    }
                }
            }
        });
        suggestionsPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
        suggestionsPanel.getActionMap().put("Down released", new AbstractAction() {
            int lastFocusableIndex = 0;

            @Override
            public void actionPerformed(ActionEvent ae) {//allows scrolling of labels in pop window (I know very hacky for now :))

                ArrayList<SuggestionLabel> sls = getAddedSuggestionLabels();
                int max = sls.size();

                if (max > 1) {//more than 1 suggestion
                    for (int i = 0; i < max; i++) {
                        SuggestionLabel sl = sls.get(i);
                        if (sl.isFocused()) {
                            if (lastFocusableIndex == max - 1) {
                                lastFocusableIndex = 0;
                                sl.setFocused(false);
                                autoSuggestionPopUpWindow.setVisible(false);
                                setFocusToTextField();
                                checkForAndShowSuggestions();//fire method as if document listener change occured and fired it

                            } else {
                                sl.setFocused(false);
                                lastFocusableIndex = i;
                            }
                        } else if (lastFocusableIndex <= i) {
                            if (i < max) {
                                sl.setFocused(true);
                                autoSuggestionPopUpWindow.toFront();
                                autoSuggestionPopUpWindow.requestFocusInWindow();
                                suggestionsPanel.requestFocusInWindow();
                                suggestionsPanel.getComponent(i).requestFocusInWindow();
                                lastFocusableIndex = i;
                                break;
                            }
                        }
                    }
                } else {//only a single suggestion was given
                    autoSuggestionPopUpWindow.setVisible(false);
                    setFocusToTextField();
                    checkForAndShowSuggestions();//fire method as if document listener change occured and fired it
                }
            }
        });
    }

    private void setFocusToTextField() {
        container.toFront();
        container.requestFocusInWindow();
        textField.requestFocusInWindow();
    }

    public ArrayList<SuggestionLabel> getAddedSuggestionLabels() {
        ArrayList<SuggestionLabel> sls = new ArrayList<>();
        for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
            if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
                SuggestionLabel sl = (SuggestionLabel) suggestionsPanel.getComponent(i);
                sls.add(sl);
            }
        }
        return sls;
    }

    private void checkForAndShowSuggestions() {
        typedWord = getCurrentlyTypedWord();

        suggestionsPanel.removeAll();//remove previos words/jlabels that were added

        //used to calcualte size of JWindow as new Jlabels are added
        tW = 0;
        tH = 0;

        boolean added = wordTyped(typedWord);

        if (!added) {
            if (autoSuggestionPopUpWindow.isVisible()) {
                autoSuggestionPopUpWindow.setVisible(false);
            }
        } else {
            showPopUpWindow();
            setFocusToTextField();
        }
    }

    protected void addWordToSuggestions(String word) {
        SuggestionLabel suggestionLabel = new SuggestionLabel(word, suggestionFocusedColor, suggestionsTextColor, this);

        calculatePopUpWindowSize(suggestionLabel);

        suggestionsPanel.add(suggestionLabel);
    }

    public String getCurrentlyTypedWord() {//get newest word after last white spaceif any or the first word if no white spaces
        String text = textField.getText();
        String wordBeingTyped = "";
        if (text.contains(" ")) {
            int tmp = text.lastIndexOf(" ");
            if (tmp >= currentIndexOfSpace) {
                currentIndexOfSpace = tmp;
                wordBeingTyped = text.substring(tmp);
            }
        } else {
            wordBeingTyped = text;
        }
        return wordBeingTyped.trim();
    }

    private void calculatePopUpWindowSize(JLabel label) {
        //so we can size the JWindow correctly
        if (tW < label.getPreferredSize().width) {
            tW = label.getPreferredSize().width;
        }
        tH += label.getPreferredSize().height;
    }

    private void showPopUpWindow() {
        autoSuggestionPopUpWindow.getContentPane().add(suggestionsPanel);
        autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textField.getWidth(), 30));
        autoSuggestionPopUpWindow.setSize(tW, tH);
        autoSuggestionPopUpWindow.setVisible(true);

        int windowX = 0;
        int windowY = 0;

        windowX = container.getX() + textField.getX() + 5;
        if (suggestionsPanel.getHeight() > autoSuggestionPopUpWindow.getMinimumSize().height) {
            windowY = container.getY() + textField.getY() + textField.getHeight() + autoSuggestionPopUpWindow.getMinimumSize().height;
        } else {
            windowY = container.getY() + textField.getY() + textField.getHeight() + autoSuggestionPopUpWindow.getHeight();
        }

        autoSuggestionPopUpWindow.setLocation(windowX, windowY);
        autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textField.getWidth(), 30));
        autoSuggestionPopUpWindow.revalidate();
        autoSuggestionPopUpWindow.repaint();

    }

    public void setDictionary(ArrayList<String> words) {
        dictionary.clear();
        if (words == null) {
            return;//so we can call constructor with null value for dictionary without exception thrown
        }
        for (String word : words) {
            dictionary.add(word);
        }
    }

    public JWindow getAutoSuggestionPopUpWindow() {
        return autoSuggestionPopUpWindow;
    }

    public Window getContainer() {
        return container;
    }

    public JTextField getTextField() {
        return textField;
    }

    public void addToDictionary(String word) {
        dictionary.add(word);
    }

    boolean wordTyped(String typedWord) {

        if (typedWord.isEmpty()) {
            return false;
        }
        //System.out.println("Typed word: " + typedWord);

        boolean suggestionAdded = false;

        for (String word : dictionary) {//get words in the dictionary which we added
            boolean fullymatches = true;
            for (int i = 0; i < typedWord.length(); i++) {//each string in the word
                if (!typedWord.toLowerCase().startsWith(String.valueOf(word.toLowerCase().charAt(i)), i)) {//check for match
                    fullymatches = false;
                    break;
                }
            }
            if (fullymatches) {
                addWordToSuggestions(word);
                suggestionAdded = true;
            }
        }
        return suggestionAdded;
    }
}

class SuggestionLabel extends JLabel {

    private boolean focused = false;
    private final JWindow autoSuggestionsPopUpWindow;
    private final JTextField textField;
    private final AutoSuggestor autoSuggestor;
    private Color suggestionsTextColor, suggestionBorderColor;

    public SuggestionLabel(String string, final Color borderColor, Color suggestionsTextColor, AutoSuggestor autoSuggestor) {
        super(string);

        this.suggestionsTextColor = suggestionsTextColor;
        this.autoSuggestor = autoSuggestor;
        this.textField = autoSuggestor.getTextField();
        this.suggestionBorderColor = borderColor;
        this.autoSuggestionsPopUpWindow = autoSuggestor.getAutoSuggestionPopUpWindow();

        initComponent();
    }

    private void initComponent() {
        setFocusable(true);
        setForeground(suggestionsTextColor);

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent me) {
                super.mouseClicked(me);

                replaceWithSuggestedText();

                autoSuggestionsPopUpWindow.setVisible(false);
            }
        });

        getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "Enter released");
        getActionMap().put("Enter released", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                replaceWithSuggestedText();
                autoSuggestionsPopUpWindow.setVisible(false);
            }
        });
    }

    public void setFocused(boolean focused) {
        if (focused) {
            setBorder(new LineBorder(suggestionBorderColor));
        } else {
            setBorder(null);
        }
        repaint();
        this.focused = focused;
    }

    public boolean isFocused() {
        return focused;
    }

    private void replaceWithSuggestedText() {
        String suggestedWord = getText();
        String text = textField.getText();
        String typedWord = autoSuggestor.getCurrentlyTypedWord();
        String t = text.substring(0, text.lastIndexOf(typedWord));
        String tmp = t + text.substring(text.lastIndexOf(typedWord)).replace(typedWord, suggestedWord);
        textField.setText(tmp + " ");
    }
}

Even took it up to 50000 random Strings and even than only a tiny pause can be seen/felt


text:
Q: Nginx redirect https://www to https:// Thanks Richard for the Answer!
I have just set up my SSL certificates from Comodo on a Digitalocean Ubuntu rails server with Nginx.
At the moment http:// www.mydomain and http:// mydomain
redirect to
https:// mydomain
I also want https:// www.mydomain to redirect to https:// mydomain
I am very new to this and this is the current setup, I have 2 /etc/nginx/sites-enabled/ files( a .com and a .com.ssl file):
.com file
server {
        listen 80;
        server_name dspencer-webdesign.com;
        return 301 https://dspencer-webdesign.com$request_uri;
    }

server {
    listen 80;
    server_name dspencer-webdesign.com;

    passenger_enabled on;
    rails_env production;
    root /home/abfahren/david/current/public;

    error_page 500 502 503 504  /50x.html;
    location = /50.x.html {
        root html;
      }
    }

.com.ssl file
server {
        server_name www.dspencer-webdesign.com;
        return 301 $scheme://dspencer-webdesign.com$request_uri;
    }
    server {
        listen 443 ssl;
        server_name dspencer-webdesign.com;

        ssl_certificate /etc/ssl/ssl-bundle.crt;
        ssl_certificate_key /etc/ssl/dspencer-webdesign.com.key;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers AES256+EECDH:AES256+EDH:!aNULL;

        passenger_enabled on;
        rails_env production;
        root /home/abfahren/david/current/public;

        error_page 500 502 503 504  /50x.html;
        location = /50.x.html {
        root html;
      }
    }

I am not sure how to get the functioning https:// www to redirect to https://dspencer-webdesign.com
Any help would be greatly appreciated
Cheers

A: Your configuration is a little confusing. You have three non-SSL server containers, two of which have the same server_name. #1 redirects to SSL, #2 is never used, and #3 redirects to #1.
Your 4th server container is your one and only SSL server container, which makes it your default server for any connections to port 443.
I haven't tested this, but if you place this near the top of the SSL server block it should redirect https://www.d-w.c to https://d-w.c:
server {
  listen 443 ssl;
  server_name dspencer-webdesign.com;
  if ($server_name ~* \.dspencer-webdesign.com$) {
    return 301 $scheme://dspencer-webdesign.com$request_uri;
  }
  ...
}


text:
Q: Oracle VirtualBox - Hangs when installing a guest O/S Work laptop.  Had OVB 5 working perfectly.
Rebuilt after hardware failure.
Installed OVB 6.0.8
My config:
+ enable I/O APIC
+ Hardware clock in UTC
+ Enable nested PAE/NX
2 CPUs
Hyper-V
+ Enable VT-x/AMD-V
+ Enable Nested paging

I have tried installing all of these:
Import an exisitng OVA
linuxmint-19.1-xfce-32bit.iso
Core-current.iso
ubuntu-18.04.2-live-server-amd64.iso
linuxmint-19.1-cinnamon-32bit.iso

They all hang.  Only Core-current.iso made it to the live state after waiting 4 hours, but when I tried to permanently install it - it also hangs.
Here is my laptop config:
WindowsBuildLabEx                                       :
17763.1.amd64fre.rs5_release.180914-1434
WindowsCurrentVersion                                   : 6.3
WindowsEditionId                                        : Enterprise
WindowsProductName                                      : Windows 10
Enterprise
WindowsVersion                                          : 1809
OsForegroundApplicationBoost                            : Maximum
OsTotalVisibleMemorySize                                : 8261208
OsFreePhysicalMemory                                    : 3564040
OsTotalVirtualMemorySize                                : 11905864
OsFreeVirtualMemory                                     : 5553108
OsInUseVirtualMemory                                    : 6352756
OsMaxNumberOfProcesses                                  : 4294967295
OsMaxProcessMemorySize                                  : 137438953344
OsMuiLanguages                                          : {en-US}
OsNumberOfProcesses                                     : 221
OsArchitecture                                          : 64-bit
OsLanguage                                              : en-US
OsPrimary                                               : True
OsProductType                                           : WorkStation
HyperVisorPresent                                       : True
HyperVRequirementDataExecutionPreventionAvailable       :
HyperVRequirementSecondLevelAddressTranslation          :
HyperVRequirementVirtualizationFirmwareEnabled          :
HyperVRequirementVMMonitorModeExtensions                :


text:
Q: How to create columns from specific row in Tableau I'm practising my Tableau - well learning - skills and trying to visualise an old csv dataset.
I want to crop the top two rows and assign the columns to the top row. How do I do that?
I'd then like to filter out the data rows in two ways. One would be to just select regional totals, and a second filter by local authority. Need to learn as these are basics in Pandas.
Table as_16_q: Asylum seekers in receipt of Section 95 support, by local authority, as at end of quarter
Back to contents
Quarter Region                   Local Authority    Total supported under Section 95    In receipt of subsistence only  In dispersed accommodation  Disbenefited

 2003 Q4    *Total                   *Total             80,123                    30,362                            47,148                          2,613

2003 Q4     East Midlands *Total     East Midlands      4,524   1,027                           3,465                       32
2003 Q4     East of England *Total   East of England    1,944   1,216                           655                         73
2003 Q4     London  *Total           London             24,916  22,017                          746                         2,153
2003 Q4     North East  *Total           North East         5,172   216
                        4,930                       26

...
And then on to local authorities...
    2003 Q4     Scotland                 Aberdeen           17
17                              0                           0
    2003 Q4     East Midlands            Amber Valley       1        1                              0                           0

A: Try the Data Interpreter for cropping the top rows and Data Source filters for reducing the amount of data in the data source.


text:
Q: Django Rest Framework cache_page I am trying to integrate caching with the Django rest framework. I came across cache_page module from django.views.decorators.cache. Can someone please tell me how can I can see the data stored in this method.
Reference link here

A: Django can be setup with different cache storage options, for example memchached or using your database. Depending on your cache storage selection, you can check that storage for the cached data.
For example, if you were to use a database, you would create a table and add the following to settings.py:
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}

See Django cache docs for how to setup cache
For a Django Rest Framework implementation:

*

*APIView and ViewSet  see the docs:

*caching querysets (ListAPIView), this has already been addressed here: How to cache Django Rest Framework API calls?


text:
Q: php's-`mysql_fetch_array()`-like actions in node.js? I guess node.js' mysql drivers are async, but I'm not really sure what that means, so... The npm module for node.js allows for rows to "stream" or be "gathered up all at once".
Can someone show me where streaming and gathering are applied, and can someone show me how a mysql_fetch_array()-like (from php) operation would be done in node.js?

A: "Streaming" means that you get a callback for each row, with an argument that's an object corresponding to the row. The other option gives you a callback after all the rows have been fetched, with an argument that's an array of objects, each element corresponding to one row. Which one to use depends on how your application logic is structured.
The latter one sounds like what you're looking for, though (again depending on your application logic) it might or might not be the best way to do it.


text:
Q: How to have permanent cached data in IIS6 I have an application in C# (FrameWork 4.0) running on IIS6.
I'd like to have cached data data (class at foot) permanently,
but an event or something similar removes this cached data,
in a short time (15-25 mins).
I configure the IIS only with this option: Recycle worker processes (in minutes) 1740.
Any ideas to preserve the data cached?
Is the filetime of a static variable is the same as the application lifetime?
public class CacheUsers
{
        static object objlock;
        private static List<Users> usersList { get; set; }
        private static DateTime lastUpdate;

        public CacheUsers()
        {
            if (objlock == null)
            {
                objlock = new object();
            }
            lock (objlock)
            {
                if (usersList == null || usersList.Count.Equals(0) || (lastUpdate < DateTime.Now.AddHours(-24)))
                {
                    UpdateUserList();
                }
            }
        }

        public static List<Users> ListaCacheada
        {
            get
            {
                if (usersList == null || usersList.Count.Equals(0) || (lastUpdate < DateTime.Now.AddHours(-24)))
                {
                    UpdateUserList();
                }
                return usersList;
            }
        }

        /// <summary>
        /// Refresh the user list
        /// </summary>
        private static void UpdateUserList()
        {
            usersList = GetUsers();
            lastUpdate = DateTime.Now;
        }

}

A: Edit: How long objects can survive -
There is technically no way for CLR objects in an AppDomain can survive restart of that AppDomain (i.e. in ASP.Net it can caused by change in web.config), as result no way of surviving AppPool recycle (process shutdown). Native objects will not be able to survive AppPool recycle either.
Recycle of an AppPool not necessary will create process again (it actually will not), only first request to a site served by this AppPool will launch process.
So if your goal is strictly "my CLR objects must be in some sort of cache immediately after AppPool recycle" the closest would be to re-cache objects in your Application_Start (or equivalent method in a module).  Note that static objects are not guaranteed to be created at assembly load time, so if you want to use static objects for caching you still need to trigger the creation i.e. by accessing them in Application_Start.
If you need objects to live beyond the AppPool's lifetime - you need a separate service. Such systems have to keep objects outside of the process (and sometimes the machine), so you'll pay the cost of remotely accessing such objects.
You may be interested in distributed caching (like memcachd) to see if it fits your needs.

Normal "caching" usage is to cache objects that are costly to create, it is unclear want to achieve with your "cached" definition.
It is often done by hiding caching logic inside method that provides the object:
MyObject GetMyObject()
{
  MyObject result= cacheProvider.Get("cacheId_MyObject");
  if (result = null)
  {
    result = VerySlowMethodToCreateMyObject();
    cacheProvider.Cache("cacheId_MyObject", result);
  }
  return result;
}

Consider simply using System.Web.Caching.Cache. Its Insert method provides a lot of options. You can even implement "cached forever" items if you provide onRemoveCallback.

A: I've chaged the code, and I use HttpRuntime.Cache, and nothing happens. :-(
The problem is that App Pool should only works only once per day, because:

I configure the IIS only with this option: Recycle worker processes (in minutes) 1740

and seems that something is launching this process a lot of times (aprox, every 15 minutes).
I just want to stop  the App Pool recycler. Who can I do it?
    public class CacheUsers
    {
         static object objlock;
        private static List<Users> usersList { get; set; }

    public CacheUsers()
    {
        if (objlock == null)
        {
            objlock = new object();
        }
        lock (objlock)
        {
            if (usersList == null || usersList.Count.Equals(0))
            {
                UpdateUserList();
            }
        }
    }

    private static void UpdateUserList()
    {
                 usersList = GetList();
                HttpRuntime.Cache.Insert("Key", usersList , null,
                            Cache.NoAbsoluteExpiration,
                            Cache.NoSlidingExpiration,
                            System.Web.Caching.CacheItemPriority.NotRemovable,
                            ReportRemovedCallback
                            );
    }

}

ReportRemovedCallback indicates the cause of this: Removed. But, who does it?


text:
Q: pipe python logging stdout stream output to grep I knew the reason for this a while back but I have since forgotten and 5 mins of googling hasn't revealed the answer.
I have written a python script which has two handlers. One for files and one for streams.
Everything works as I want.
Now, I wanted to quickly grep for something in the output that was being printed to the terminal  but piping the script's output through grep doesn't appear to be working in that all of the output still get's printed to the terminal.
I am using unix and python 2.7
This is probably a duplicate question but I can't find the answer.
Here's my setup of the logging module:
def setup_logger(verbosity):
    #logger = logging.getLogger(regress.app_name)
    logger = logging.getLogger('components')
    logger.setLevel(logging.DEBUG)
    # create file handler which logs even debug messages
    fh = logging.FileHandler(Config.logging_file_name, mode='w')
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel({True:logging.DEBUG, False:logging.INFO}[verbosity])
    # create formatter and add it to the handlers
    file_formatter = logging.Formatter('%(asctime)s - %(pathname)s - %(funcName)s - %(name)s - %(levelname)s - %(lineno)s - %(message)s')

    console_formatter = logging.Formatter('%(filename)s - %(lineno)s - %(levelname)s - %(message)s')
    fh.setFormatter(file_formatter)
    ch.setFormatter(console_formatter)
    # add the handlers to the logger
    logger.addHandler(fh)
    logger.addHandler(ch)

    #logging.abort = abort
    #logging.abort("testing...")
    #logger.info("does this happen?")

    #logging.func = func
    #logging.func()
    #logger.func()

My invocation of the script looks like this:
<script_name> <script args> | grep -i <search_string>

A: As @Blender mentions in the comments below the original question, you just need to redirect stderr.  You can do this by adding a 2>&1 redirect before the pipe.  So, for example,
python main.py 2>&1 | grep INFO

will filter for any INFO lines logged by main.py.


text:
Q: Converting a List within a List from String to Integers After approximately eight hours of searching and attempting to implement solutions, I am still vexed by this problem.
I am attempting to make a dinky ANOVA package that can read data from a text file, count the number of participants based on lines within said file, and then run an ANOVA after a few simple calculations.
However, the one thing that's keeping me from finishing this project is converting everything into a calculable format--from string values to integer values.
Here's what I have so far:
def cond1():
    cond1file=open("condition1.txt","r")
    c1resplist=[]
    line=cond1file.readline()
    while line !='':
        line=line.split()
        c1resplist.append(line)
        line=(cond1file.readline())
    cond1file.close()
    participants=0
    with open("condition1.txt","r") as f:
        for line in f:
            participants+=1

And here's the text from the data file it's reading:

1 2 3 1 2 3
1 2 3 1 2 3
1 2 3 1 2 3
1 2 3 1 2 3
1 2 3 1 2 3
1 2 3 1 2 3
1 2 3 1 2 3
1 2 3 1 2 3
1 2 3 1 2 3
1 2 3 1 2 3

Here's the output generated by the readline portion:
[['1', '2', '3', '1', '2', '3'], ['1', '2', '3', '1', '2', '3'], ['1', '2', '3', '1', '2', '3'], ['1', '2', '3', '1', '2', '3'], ['1', '2', '3', '1', '2', '3'], ['1', '2', '3', '1', '2', '3'], ['1', '2', '3', '1', '2', '3'], ['1', '2', '3', '1', '2', '3'], ['1', '2', '3', '1', '2', '3'], ['1', '2', '3', '1', '2', '3']]

I'd really appreciate any and all guidance. Thanks.

A: Instead of this:
c1resplist.append(line)

use this instead:
c1resplist.append([int(x) for x in line])

This list comprehension iterates over each item in the line list, and changes it to an int. The new list is then appended to your existing c1resplist list.

There are plenty of ways to improve your current code (for example, you are opening and iterating over the file twice), but this should at least get you the data you're looking for.

A: You can use map to convert the strings to ints.
(You seem to have an extra iteration to find the number of participants which can be counted during the first loop)
def cond1_a():
    c1resplist=[]
    participants=0
    with open("condition1.txt","r") as f:
        for line in f:
            c1resplist.append(list(map(int, line.split())))
            participants+=1
    return c1resplist, participants

print(cond1_a())
# ([[1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3]], 10)

You can also use a list comprehension:
def cond1_b():
    with open("condition1.txt","r") as f:
        c1resplist = [list(map(int, line.split())) for line in f]
    return c1resplist, len(c1resplist)

print(cond1_b())
# ([[1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3]], 10)

Or instead of map, use a nested list comprehension:
def cond1_c():
    with open("condition1.txt","r") as f:
        c1resplist = [[int(x) for x in line.split()] for line in f]
    return c1resplist, len(c1resplist)
print cond1_c()
# ([[1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3]], 10)

edit:
As @Padraic Cunningham mentions, python 3 requires using list(map(fn, it)) since map returns map objects.


text:
Q: Why does svnversion call my working copy "modified" although it seems identical to the repository? Can anyone tell me why svn would indicate that a current working copy is modified, although all changes are checked in?
$ svn up
At revision 1520.
$ svn diff
$ svnversion
1520M

A: I dunno if this is your case, but for situations in which the project properties and settings are part of the project in the repository, it might happen that eventual changes to those properties (eventually automatically) on your end, might cause this difference.

A: Usually I see this when the timestamp is modified. Although it can be a number of svn properties.
Assuming you haven't tagged or changed a property of the file such as svn:ignore I'd imagine the most likely senario is you've changed and reverted the change to the file locally.
Common cases where you may do this is adding in some debug code then removing again after debugging has finished.


text:
Q: Frequency array feeds FFT The final goal I am trying to achieve is the generation of a ten minutes time series: to achieve this I have to perform an FFT operation, and it's the point I have been stumbling upon.
Generally the aimed time series will be assigned as the sum of two terms: a steady component U(t) and a fluctuating component u'(t). That is
u(t) = U(t) + u'(t);

So generally, my code follows this procedure:
1) Given data
time = 600 [s];

Nfft = 4096;

L = 340.2 [m];

U = 10 [m/s];

df = 1/600 = 0.00167 Hz;

fn = Nfft/(2*time) = 3.4133 Hz;

This means that my frequency array should be laid out as follows:
f = (-fn+df):df:fn;

But, instead of using the whole f array, I am only making use of the positive half:
fpos = df:fn = 0.00167:3.4133 Hz;

2) Spectrum Definition
I define a certain spectrum shape, applying the following relationship
Su = (6*L*U)./((1 + 6.*fpos.*(L/U)).^(5/3));

3) Random phase generation
I, then, have to generate a set of complex samples with a determined distribution: in my case, the random phase will approach a standard Gaussian distribution (mu = 0, sigma = 1).
In MATLAB I call
nn = complex(normrnd(0,1,Nfft/2),normrnd(0,1,Nfft/2));

4) Apply random phase
To apply the random phase, I just do this
Hu = Su*nn;

At this point start my pains!
So far, I only generated Nfft/2 = 2048 complex samples accounting for the fpos content. Therefore, the content accounting for the negative half of f is still missing. To overcome this issue, I was thinking to merge the real and imaginary part of Hu, in order to get a signal Huu with Nfft = 4096 samples and with all real values.
But, by using this merging process, the 0-th frequency order would not be represented, since the imaginary part of Hu is defined for fpos.
Thus, how to account for the 0-th order by keeping a procedure as the one I have been proposing so far?


text:
Q: Webkit http support I understand webkit allow web browsers to render web pages. So my HTML, CSS and java script code will run on any device which has webkit support. But what about http support. Does webkit has inbuild support for http communication?

A: WebKit renders the content, I can't say whether it fetches content or not.
What I could find so far googling is that ResourceRequest, ResourceHandle, and ResourceResponse are classes that represent HTTP connections.

A: WebKit only manages the rendering and manages the HTTP Requests. When it however comes to accepting other forms of content such as images, jpeg, pdfs etc... WebKit does not handle those the Application developers have to handle that themselfs.
Source: Qt Development

A: May be this will be helpful to other.
I downloaded webkit and ran sample ajax test and they were success
So answer to my question is yes, Webkit support http


text:
Q: Sentry Rate Limiting We have a couple of aws lambda functions which are using the same Sentry Client Key for error reporting. Recently we started to receive rate limiting error.
{
    "errorType": "SentryError",
    "errorMessage": "HTTP Error (429)",
    "name": "SentryError",
    "stack": [
        "SentryError: HTTP Error (429)",
        "    at new SentryError (/var/task/node_modules/@sentry/utils/dist/error.js:9:28)",
        "    at ClientRequest.<anonymous> (/var/task/node_modules/@sentry/node/dist/transports/base/index.js:212:44)",
        "    at Object.onceWrapper (events.js:421:26)",
        "    at ClientRequest.emit (events.js:314:20)",
        "    at ClientRequest.EventEmitter.emit (domain.js:483:12)",
        "    at HTTPParser.parserOnIncomingClient (_http_client.js:601:27)",
        "    at HTTPParser.parserOnHeadersComplete (_http_common.js:122:17)",
        "    at TLSSocket.socketOnData (_http_client.js:474:22)",
        "    at TLSSocket.emit (events.js:314:20)",
        "    at TLSSocket.EventEmitter.emit (domain.js:483:12)"
    ]
}

However, no actual errors occurs in the lambda function. From what we understand Sentry is recording every lambda executions and sending this information as trace. We are using a low tracesSampleRate, but the error still occurs.
AWSLambda.init({
  dsn: process.env.SENTRY_DNS,
  sampleRate: 1.0,
  tracesSampleRate: 0.1,
});

I don't know if this is relevant, but the functions are not inside our VPC, they are using AWS ip address pool.
We tried to find any indication of errors related to rate limiting in the Sentry dashboard, but without success.

Thanks!

A: I started getting this issue in one of our systems around the same time you posted this. Something that stopped it happening was to disable tracing all together (tracesSampleRate: 0). Not truly a fix, but enough to clear our error logs for now while we investigate a proper fix.


text:
Q: Copies to NFS server write to mount point, not to mounted drive I have a drive mounted at /home/ftpuser/uploads, and the /home/ftpuser folder is also exported via NFS. FTP uploads to the uploads folder work as intended. If I unmount the drive, the files disappear, then reappear when I mount the drive.
On another client, I do a cp file /nfsmnt/uploads/subdir (where /nfsmnt is the local mount point and /home/ftpuser is exported on the server.) and it copies to the NFS server. The problem is that NFS copies to the server copy to the mount point on the server, instead of to the drive mounted at the mount point. The files uploaded from FTP are there, but I can't see the NFS copied files until I unmount the drive.
Am I missing some server-side option(s)?
EDIT UPDATE:
User proposed something I had suspected, that NFS server was starting before the secondary disk was mounted and this was causing files to be copied to the mount point instead of the mounted disk. nfs-kernel-server is started pretty early. I looked through some of the scripts in /etc/rc5.d and didn't see any reference to mounting disks.


text:
Q: On Android, how do you get the data from an email address in Firebase, then access the child, and from there you access the other Firebase data? The following file explains better what I really mean. It's a screenshot of data sent from a dummy user in Firebase:

The code:
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
                // ref.addValueEventListener(new ValueEventListener() {
                ref.orderByChild("Email").equalTo("testing3@testing.com").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        for (DataSnapshot datas : dataSnapshot.getChildren()) {
                            String key = datas.getKey();
                            DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(key);
                            Toast.makeText(getApplicationContext(), key, Toast.LENGTH_LONG).show();
                            ref.addValueEventListener(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot snapshot) {
                                    String name = dataSnapshot.child("Name").getValue().toString();
                                    String state = dataSnapshot.child("State").getValue().toString();
                                    String stateRegion = dataSnapshot.child("StateRegion").getValue().toString();
                                    String telephone = String.valueOf(dataSnapshot.child("Telephone").getValue());
                                    nameEditText.setText(name);
                                    stateEditText.setText(state);
                              stateRegionEditText.setText(stateRegion);
                               telephoneEditText.setText(telephone);
                                }
                                @Override
                                public void onCancelled(@NonNull DatabaseError error) {
                                }
                            });
                        }
                    }
                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                    }
                });
            }
        });

Please, can some person help?
More information about data stored in the Firebase:

A: Because I cannot see a more detailed database schema of yours, I assume that all those user objects are direct children under your Users node, and also assuming that you want to find the user that has the Email set to testing3@tesing.com, to display his particular details, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = db.child("Users");
Query queryUsersByEmail = usersRef.orderByChild("Email").equalTo("testing3@testing.com");
queryUsersByEmail.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot ds : task.getResult().getChildren()) {
                String name = ds.child("Name").getValue(String.class);
                Log.d("TAG", name);
                String state = ds.child("State").getValue(String.class);
                Log.d("TAG", state);
                String stateRegion = ds.child("State Region").getValue(String.class);
                Log.d("TAG", stateRegion);
                String telephone = ds.child("Telephone").getValue(String.class);
                Log.d("TAG", telephone);
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

The result in the logcat will be:
Paul SMith
Rio de Janeiro
Rio de Janeiro
(00)00000-0000


text:
Q: getting incorrect answer. what is wrong with this code? x=raw_input('what is your favorite number? ')
n=x*10
print n

If I plug in 5, I don't get 50. I get 5555555
I have tried declaring float(n) and tooling around with it. nothing helped. I realize this is minor league, but I am just starting to teach myself python.
Thanks, Todd

A: You are taking in your number as raw_input, meaning, it is returned to the program as a string. When you multiply a string by an integer and print the result, it just prints the string x times, in your case 10 because you attempted to multiply by 10. To prove this, change, the 10 to 20 and watch what happens.
There are two ways to fix this. The first would be to use input() instead of raw_input(), so that it returns a number as a result.
x=input("Please enter a number here.\n")

The second way would be to reassign x to the integer equivalent of the string, using the function int().
x=int(x) # Will turn "10", which is what you have, into 10

This should solve your problem.
Best of luck, and happy coding!

A: This is because the default data type of raw_input() is string. You have to cast the string input to an integer for achieving the desired result.

A: When you read a value in from user input like this it is as a string.  So x actually equals the string '5' but what you actually want is the number 5.
int(x) * 10


text:
Q: Change attribute value prefixed by a namespace using simplexml I would like to change the value of an attribute prefixed by a namespace using simplexml:
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="16">

These methods are not working:
$usesSDKTag['android:minSdkVersion'] = $minSdkVersion;
$usesSDKTag['minSdkVersion'] = $minSdkVersion;

A: I ended up recreating the node and adding attributes with namespace prefix to it:
if( isset($xmlManifest->{"uses-sdk"}) ) {
     unset($xmlManifest->{"uses-sdk"});
}
$usesSDKTag = $xmlManifest->addChild('uses-sdk');
$usesSDKTag->addAttribute('android:minSdkVersion', $minSdkVersion, 'http://schemas.android.com/apk/res/android');
$usesSDKTag->addAttribute('android:targetSdkVersion', $minSdkVersion, 'http://schemas.android.com/apk/res/android');
$usesSDKTag->addAttribute('android:maxSdkVersion', $maxSdkVersion, 'http://schemas.android.com/apk/res/android');


text:
Q: The constructor TaskLaunchRequest(String, List, null, null) is undefined - Spring Cloud Task I am developing a code for the Spring Cloud with Spring Boot. In this example, I am working in Spring Cloud Tasks. I was using Spring Boot <version>1.4.1.RELEASE</version> then below code was working fine. When I updated <version>2.0.4.RELEASE</version> then I am getting below error.

The constructor TaskLaunchRequest(String, List, null, null) is undefined

TaskProcessor.java
@Component
@EnableBinding(Source.class)
public class TaskProcessor {

    @Autowired
    private Source source;

    public void publishRequest(String payload) {

        //maven://[groupid]:[artifactid]:jar:[version]
        //String url = "maven://pluralsight.demo:pluralsight-springcloud-m3-task:jar:0.0.1-SNAPSHOT";
        String url = "maven://pluralsight.demo:springcloud-m3-tasksink:jar:1.0";

        List<String> input = new ArrayList<String>(Arrays.asList(payload.split(",")));

        TaskLaunchRequest request = new TaskLaunchRequest(url, input, null, null);

        System.out.println("created task launch request ...");

        GenericMessage<TaskLaunchRequest> message = new GenericMessage<>(request);
        this.source.output().send(message);
    }
}

pom.xml
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.SR1</spring-cloud.version>
        <spring-cloud-task.version>2.0.0.RELEASE</spring-cloud-task.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-task</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-task-dependencies</artifactId>
                <version>${spring-cloud-task.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Error Images:

A: I had the same problem and after the following modifications in the pom file it works.

*

*replace your:
<spring-cloud.version>Finchley.SR1</spring-cloud.version>

with:
<spring-cloud.version>Brixton.SR6</spring-cloud.version>

*replace your:
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-task</artifactId>
</dependency>

with:
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-task-starter</artifactId>
  <version>1.0.1.RELEASE</version>
</dependency>


text:
Q: Big query time Spark + Cassandra Ahoi  almighty devs. I'm running some basic analytics in Spark where I'm querying multi node Cassandra. The code I'm running and where I'm dealing with some unlogic is:
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.SQLContext
import org.apache.spark.SparkContext
import com.datastax.spark.connector._

object cassSpark {
  def main(args: Array[String]): Unit = {

val conf = new SparkConf()
  .set("spark.cassandra.connection.host","192.168.56.101")
  .set("spark.cassandra.connection.host","192.168.56.102")
  .set("spark.cassandra.connection.local_dc", "datacenter1")
  .setMaster("local[*]")
  .setAppName("cassSpark")

val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)

time{
val df = sqlContext
 .read
 .format("org.apache.spark.sql.cassandra")
 .options(Map( "table" -> "nth1", "keyspace"->"nth", "cluster" -> "Test Cluster"))
 .load().cache()

df.count()

}

def time[A](f: => A) = {
  val s = System.nanoTime
  val ret = f
  println("time: " + (System.nanoTime - s) / 1e6 + "ms")
  ret
}
 }
}

So, the version of Spark is 1.6.0, Cassandra v3.0.10, connector is also 1.6.0. Keyspace has replication_factor: 1, table has 5 columns and acutally just 1 row in it. There 2 nodes ( virtual macines made in OracleVM) as you can see.
My problem is that when I'm measuring the time of query from spark to cassandra I got as result about 20seconds which is not normal to me beacuse there is just one row in table. Am I missing something, or I'm measuring something wrong, or maybe is up to someting in mine code. Can someone help me, or show me the way how efficiently do this or process it.
[EDIT]
As @Artem Aliev wanted, this is whole info log:
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
16/12/06 12:31:04 INFO SparkContext: Running Spark version 1.6.0
16/12/06 12:31:06 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/12/06 12:31:07 INFO SecurityManager: Changing view acls to: superbrainbug
16/12/06 12:31:07 INFO SecurityManager: Changing modify acls to: Ivan Majnaric
16/12/06 12:31:07 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(superbrainbug); users with modify permissions: Set(superbrainbug)
16/12/06 12:31:12 INFO Utils: Successfully started service 'sparkDriver' on port 62101.
16/12/06 12:31:14 INFO Slf4jLogger: Slf4jLogger started
16/12/06 12:31:14 INFO Remoting: Starting remoting
16/12/06 12:31:15 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkDriverActorSystem@192.168.56.1:62114]
16/12/06 12:31:15 INFO Utils: Successfully started service 'sparkDriverActorSystem' on port 62114.
16/12/06 12:31:15 INFO SparkEnv: Registering MapOutputTracker
16/12/06 12:31:15 INFO SparkEnv: Registering BlockManagerMaster
16/12/06 12:31:15 INFO DiskBlockManager: Created local directory at C:\Users\superbrainbug\AppData\Local\Temp\blockmgr-8b664e71-ead1-4462-b171-bf542a5eb444
16/12/06 12:31:15 INFO MemoryStore: MemoryStore started with capacity 1124.6 MB
16/12/06 12:31:18 INFO SparkEnv: Registering OutputCommitCoordinator
16/12/06 12:31:20 INFO Utils: Successfully started service 'SparkUI' on port 4040.
16/12/06 12:31:20 INFO SparkUI: Started SparkUI at http://192.168.56.1:4040
16/12/06 12:31:20 INFO Executor: Starting executor ID driver on host localhost
16/12/06 12:31:20 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 62136.
16/12/06 12:31:20 INFO NettyBlockTransferService: Server created on 62136
16/12/06 12:31:20 INFO BlockManagerMaster: Trying to register BlockManager
16/12/06 12:31:21 INFO BlockManagerMasterEndpoint: Registering block manager localhost:62136 with 1124.6 MB RAM, BlockManagerId(driver, localhost, 62136)
16/12/06 12:31:21 INFO BlockManagerMaster: Registered BlockManager
16/12/06 12:31:23 WARN NettyUtil: Found Netty's native epoll transport, but not running on linux-based operating system. Using NIO instead.
16/12/06 12:31:24 INFO Cluster: New Cassandra host /192.168.56.101:9042 added
16/12/06 12:31:24 INFO CassandraConnector: Connected to Cassandra cluster: Test Cluster
16/12/06 12:31:27 INFO CassandraSourceRelation: Input Predicates: []
16/12/06 12:31:27 INFO CassandraSourceRelation: Input Predicates: []
16/12/06 12:31:31 INFO SparkContext: Starting job: count at cassSpark.scala:69
16/12/06 12:31:31 INFO DAGScheduler: Registering RDD 7 (count at cassSpark.scala:69)
16/12/06 12:31:31 INFO DAGScheduler: Got job 0 (count at cassSpark.scala:69) with 1 output partitions
16/12/06 12:31:31 INFO DAGScheduler: Final stage: ResultStage 1 (count at cassSpark.scala:69)
16/12/06 12:31:31 INFO DAGScheduler: Parents of final stage: List(ShuffleMapStage 0)
16/12/06 12:31:31 INFO DAGScheduler: Missing parents: List(ShuffleMapStage 0)
16/12/06 12:31:31 INFO DAGScheduler: Submitting ShuffleMapStage 0 (MapPartitionsRDD[7] at count at cassSpark.scala:69), which has no missing parents
16/12/06 12:31:35 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 20.0 KB, free 20.0 KB)
16/12/06 12:31:35 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 9.2 KB, free 29.2 KB)
16/12/06 12:31:35 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on localhost:62136 (size: 9.2 KB, free: 1124.6 MB)
16/12/06 12:31:35 INFO SparkContext: Created broadcast 0 from broadcast at DAGScheduler.scala:1006
16/12/06 12:31:35 INFO DAGScheduler: Submitting 1 missing tasks from ShuffleMapStage 0 (MapPartitionsRDD[7] at count at cassSpark.scala:69)
16/12/06 12:31:35 INFO TaskSchedulerImpl: Adding task set 0.0 with 1 tasks
16/12/06 12:31:35 INFO TaskSetManager: Starting task 0.0 in stage 0.0 (TID 0, localhost, partition 0,ANY, 20008 bytes)
16/12/06 12:31:35 INFO Executor: Running task 0.0 in stage 0.0 (TID 0)
16/12/06 12:31:35 INFO CacheManager: Partition rdd_4_0 not found, computing it
16/12/06 12:31:36 INFO GenerateUnsafeProjection: Code generated in 395.192925 ms
16/12/06 12:31:39 INFO MemoryStore: Block rdd_4_0 stored as values in memory (estimated size 1168.0 B, free 30.3 KB)
16/12/06 12:31:39 INFO BlockManagerInfo: Added rdd_4_0 in memory on localhost:62136 (size: 1168.0 B, free: 1124.6 MB)
16/12/06 12:31:39 INFO GeneratePredicate: Code generated in 35.193967 ms
16/12/06 12:31:39 INFO GenerateColumnAccessor: Code generated in 52.555004 ms
16/12/06 12:31:39 INFO GenerateMutableProjection: Code generated in 14.129896 ms
16/12/06 12:31:39 INFO GenerateUnsafeProjection: Code generated in 14.130749 ms
16/12/06 12:31:40 INFO GenerateMutableProjection: Code generated in 19.217034 ms
16/12/06 12:31:40 INFO GenerateUnsafeRowJoiner: Code generated in 72.736302 ms
16/12/06 12:31:40 INFO GenerateUnsafeProjection: Code generated in 133.407346 ms
16/12/06 12:31:41 INFO Executor: Finished task 0.0 in stage 0.0 (TID 0). 3895 bytes result sent to driver
16/12/06 12:31:41 INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 5452 ms on localhost (1/1)
16/12/06 12:31:41 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
16/12/06 12:31:41 INFO DAGScheduler: ShuffleMapStage 0 (count at cassSpark.scala:69) finished in 5,542 s
16/12/06 12:31:41 INFO DAGScheduler: looking for newly runnable stages
16/12/06 12:31:41 INFO DAGScheduler: running: Set()
16/12/06 12:31:41 INFO DAGScheduler: waiting: Set(ResultStage 1)
16/12/06 12:31:41 INFO DAGScheduler: failed: Set()
16/12/06 12:31:41 INFO DAGScheduler: Submitting ResultStage 1 (MapPartitionsRDD[10] at count at cassSpark.scala:69), which has no missing parents
16/12/06 12:31:41 INFO MemoryStore: Block broadcast_1 stored as values in memory (estimated size 9.3 KB, free 39.6 KB)
16/12/06 12:31:41 INFO MemoryStore: Block broadcast_1_piece0 stored as bytes in memory (estimated size 4.6 KB, free 44.1 KB)
16/12/06 12:31:41 INFO BlockManagerInfo: Added broadcast_1_piece0 in memory on localhost:62136 (size: 4.6 KB, free: 1124.6 MB)
16/12/06 12:31:41 INFO SparkContext: Created broadcast 1 from broadcast at DAGScheduler.scala:1006
16/12/06 12:31:41 INFO DAGScheduler: Submitting 1 missing tasks from ResultStage 1 (MapPartitionsRDD[10] at count at cassSpark.scala:69)
16/12/06 12:31:41 INFO TaskSchedulerImpl: Adding task set 1.0 with 1 tasks
16/12/06 12:31:41 INFO TaskSetManager: Starting task 0.0 in stage 1.0 (TID 1, localhost, partition 0,NODE_LOCAL, 1999 bytes)
16/12/06 12:31:41 INFO Executor: Running task 0.0 in stage 1.0 (TID 1)
16/12/06 12:31:41 INFO ShuffleBlockFetcherIterator: Getting 1 non-empty blocks out of 1 blocks
16/12/06 12:31:41 INFO ShuffleBlockFetcherIterator: Started 0 remote fetches in 15 ms
16/12/06 12:31:41 INFO GenerateMutableProjection: Code generated in 92.969655 ms
16/12/06 12:31:41 INFO GenerateMutableProjection: Code generated in 11.48414 ms
16/12/06 12:31:41 INFO Executor: Finished task 0.0 in stage 1.0 (TID 1). 1830 bytes result sent to driver
16/12/06 12:31:41 INFO TaskSetManager: Finished task 0.0 in stage 1.0 (TID 1) in 602 ms on localhost (1/1)
16/12/06 12:31:41 INFO TaskSchedulerImpl: Removed TaskSet 1.0, whose tasks have all completed, from pool
16/12/06 12:31:41 INFO DAGScheduler: ResultStage 1 (count at cassSpark.scala:69) finished in 0,605 s
16/12/06 12:31:41 INFO DAGScheduler: Job 0 finished: count at cassSpark.scala:69, took 10,592173 s
time: 19242.858679ms
16/12/06 12:31:48 INFO CassandraConnector: Disconnected from Cassandra cluster: Test Cluster
16/12/06 12:31:48 INFO SparkContext: Invoking stop() from shutdown hook
16/12/06 12:31:48 INFO SerialShutdownHooks: Successfully executed shutdown hook: Clearing session cache for C* connector
16/12/06 12:31:48 INFO SparkUI: Stopped Spark web UI at http://192.168.56.1:4040
16/12/06 12:31:48 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped!
16/12/06 12:31:48 INFO MemoryStore: MemoryStore cleared
16/12/06 12:31:48 INFO BlockManager: BlockManager stopped
16/12/06 12:31:48 INFO BlockManagerMaster: BlockManagerMaster stopped
16/12/06 12:31:48 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
16/12/06 12:31:48 INFO SparkContext: Successfully stopped SparkContext
16/12/06 12:31:48 INFO ShutdownHookManager: Shutdown hook called
16/12/06 12:31:48 INFO ShutdownHookManager: Deleting directory C:\Users\superbrainbug\AppData\Local\Temp\spark-17606f05-6bb8-4144-acb5-015f15ea1ea9

Process finished with exit code 0

Also, for @Yves DARMAILLAC if I remove .cache() runtime is 12s

A: 20 sec for you environment looks a little bit bigger then expected, it should be around 2 sec
Could you enable INFO level spark logging and post result here
The main time consumers in your example are initializations, the second run will be much faster

*

*Spark is lazy framework, so a lot of initialization at the first query. You use "local" master, so it will be slower when you will run on spark cluster.

*Connector is optimized for bulk queries, so at it do a lot of preparations, to run the bulk query faster: Query C* cluster meta informations with table sizing and token ranges location, create split, establish C* connections.

A: Why are you persisting the load() stream ? This is not necessary as you do not reuse it. Is timing still the same wihtout caching ?
Try this :
time{
   val df = sqlContext
       .read
       .format("org.apache.spark.sql.cassandra")
       .options(Map( "table" -> "nth1", "keyspace"->"nth", "cluster" -> Test Cluster"))
       .load()

    df.count()
}


text:
Q: JS runtime errors in Express I have a basic Express app which has a few routes.
One is as such:
router.post('/upload', (req, res) => {
  let audioFile = req.files.audioFile;

  const file = __dirname + '/../' + req.body.uploadLocation + audioFile.name;

  mp3.mv(file, function(err) {  // <--- HERE
    if (err) {
      return res.status(500).send(err);
    }

    res.send('File uploaded!');
  });
});

Now, if you would try to upload a file to this route you would get a 500 and that's it. The highlighted line is a result of me changing variable name. Is there any way to get it so that it prints out the actual error? I am tripped up by this so often and it would make it an awful lot quicker if the terminal output just told me the normal JS error like it does on the browser or when I'm running node normally.

A: In Express there is middleware to handle errors. In the a base setup of express you'll find:
// error handler
app.use(function(err, req, res, next) {
  ...
  // render the error page
  res.status(err.status || 500);
  res.json({ error: err });
});

Just add a console.error there:
// error handler
app.use(function(err, req, res, next) {
  console.error(err.stack); // <- HERE
  ...
  // render the error page
  res.status(err.status || 500);
  res.json({ error: err });
});


text:
Q: Draw Rect and optimization I have an NSMutableArray that's holding objects (the objects represent arcs);
Everytime I tap the screen, a circle is added to the array, and the draw rect sets needsupdate. I am not calling drawRect:, just telling it that it needs to update.
Everytime that drawRect: looks through the array of circles, is it redrawing every circle, or only what's new / hasn't changed from the previous time through?
If it does redraw every circle, are there any good practices to optimize against this?

A: Your drawing code is doing exactly whatever it says -- if you've written it to draw every circle, then every circle is drawn. You can write your drawRect: method such that it takes into account the passed rectangle, which is the "dirty" portion of the view -- that portion which needs updating, but it's only worth doing so if you've determined, via testing and measurement, that your drawing is a performance issue.
Cocoa Touch will clip your drawing, though, so that it doesn't have to refresh the whole screen, if, instead of using setNeedsDisplay, you use setNeedsDisplayInRect:, passing an appropriate dirty rectangle. You could, for example, pass just the boundary rectangle of each new circle when one is added.

A: Do you mean you're calling setNeedsDisplay?  If so, that method does redraw the whole view.  You can use setNeedsDisplayInRect: if you only want to redraw a portion of your view.


text:
Q: Can python decorators be executed or skipped depending on an earlier decorator result? I learnt from this stack_overflow_entry that in Python decorators are applied in the order they appear in the source.
So how will the following code snippet should behave?
@unittest.skip("Something no longer supported")
@skipIf(not something_feature_enabled, "Requires extra crunchy cookies to run")
def test_this():
  ....

The first decorator (noted below) asks test runner to completely skip test_this()
@unittest.skip("Something no longer supported")

While the second decorator asks test runner to skip running test_this() conditionally.
@skipIf(not something_feature_enabled, "Requires extra crunchy cookies to run")
So does it mean that test_this won't be run at all unless we put conditional skip decorator first?
Also, is there any way in Python to define dependent execution of decorators? e.g.
@skipIf("Something goes wrong")
@skipIf(not something_feature_enabled, "Requires extra crunchy cookies to run")
@log
@send_email
def test_this():
  ....

The idea is to enable execution of @log and @send_email if @skipIf("Something goes wrong") is true.
Apologies if I am missing something very obvious.

A: I think you may be missing a key point: a decorator is just a function that gets passed a function and returns a function.
So, these are identical:
@log
def test_this():
    pass

def test_this():
    pass
test_this = log(test_this)

And likewise:
@skip("blah")
def test_this():
    pass

def test_this():
    pass
test_this = skip("blah")(test_this)

Once you understand that, all of your questions become pretty simple.

First, yes, skip(…) is being used to decorate skipIf(…)(test), so if it skips the thing it decorates, test will never get called.

And the way to define the order in which decorators get called is to write them in the order you want them called.
If you want to do that dynamically, you'd do so by applying the decorators dynamically in the first place. For example:
for deco in sorted_list_of_decorators:
    test = deco(test)

Also, is there any way in Python to define dependent execution of decorators?

No, they all get executed. More relevant to what you're asking, each decorator gets applied to the decorated function, not to the decorator.
But you can always just pass a decorator to a conditional decorator:
def decorate_if(cond, deco):
    return deco if cond else lambda f: f

Then:
@skipIf("Something goes wrong")
@decorate_if(something_feature_enabled, log)
@decorate_if(something_feature_enabled, send_email)
def test_this():
    pass

Simple, right?
Now, the log and send_email decorators will be applied if something_feature_enabled is truthy; otherwise a decorator that doesn't decorate the function in any way and just returns it unchanged will get applied.
But what if you can't pass the decorator, because the function is already decorated? Well, if you define each decorator to expose the function it's wrapped, you can always unwrap it. If you always use functools.wraps (which you generally should if you have no reason to do otherwise—and which you can easily emulate in this way even when you have such a reason), the wrapped function is always available as __wrapped__. So, you can write a decorator that conditionally removes the outermost level of decoration easily:
def undecorate_if(cond):
    def decorate(f):
        return f.__unwrapped__ if cond else f
    return decorate

And again, if you're trying to do this dynamically, you're probably going to be decorating dynamically. So, an easier solution is to just skip the decorator(s) you don't want by removing them from the decos iterable before they get applied.


text:
Q: MongoDB- Return Array of existing fields by compare collection with Array of object I'm new to Mongo and trying compare a array with a documents of collections and return list of matching records.
Let me explain:First Array
I have a collection (user) with following documents:
> db.user.find().pretty()
{
    "_id" : ObjectId("57358220bf3e7d076b6ccdb1"),
    "name" : "Sunny",
    "phone" : "9417702107",
    "email" : "ssdhiman07@gmail.com"
}
{
    "_id" : ObjectId("57358242bf3e7d076b6ccdb2"),
    "name" : "Pal",
    "phone" : "9015719419",
    "email" : "ss998@gmail.com"
}
{
    "_id" : ObjectId("57358262bf3e7d076b6ccdb3"),
    "name" : "viveky",
    "phone" : "8826565107",
    "email" : "sds998@gmail.com"
}

Second Array: i have a array of objects that is come from Http request below is structure of array.
{
 "contacts" : [
            {
                    "name" : "Sunny",
                    "phone" : "9417702107"
            },
            {
                    "name" : "Sukhpal",
                    "phone" : "9015719419"
            },
            {
                    "name" : "anurag",
                    "phone" : "9988776655"
            },
            {
                    "name" : "vivek",
                    "phone" : "8826565107"
            }
         ]
}

Now I want to know which objects of Second Array are exists in First Array and which doesn't . Comparison should on basis of phone only . And in result i want same Array as Second Array but with one extra field that is
"exists":"true" or "exists":"false" . Something like this.
{
   "contacts" : [
            {
                    "name" : "Sunny",
                    "phone" : "9417702107"
                    "exists" :"true"
            },
            {
                    "name" : "pal",
                    "phone" : "90177668899"
                    "exists" :"false"
            }
          ]
  }

So for this i had tried something here is code of node.js with mongoos.
exports.matchcontacts = function(req, res, next)
{
  var response = {};
  var conArray = req.body.contacts;
  var contact_list = [];

for(var i=0; i<conArray.length;i++)
{
  var name = conArray[i].name;
  var phone = conArray[i].phone;

  Users.findOne({"phone":conArray[i].phone},function(err,data)
  {
        if(err)
        {
            response = {"error" : true,"message" : "Error fetching data"};
        }
        else if(!data)
          {
               contact_list.push({name:name,phone:phone,exists:"false"});
          }
        else
         {
             contact_list.push({name:name,phone:phone,exists:"true"});
         }

    });
  }
  response = {"error":false,"contacts":contact_list};
  res.json(response);
};

But always got null {} empty result, and if i tried to get response inside Callback function then it return only single last compared value.
Problem is in first method is that callback function return result very late so result always empty .
and in second method loop override result and it also inefficient to use callback inside loop it will call no of time. So whole story i had explained
Now Please can anybody help me with code or suggest right way to get desired result thanks

A: Haven´t used mongodb, but the idea I would use is to first iterate your contacts and make a mapping of the phones to the corresponding object and mark them as non existent:
var obj = {};

for(var i=0; i<conArray.length;i++){
    obj[conArray[i].phone] = conArray[i];
    conArray[i].exists = false;
}

Then search in some way for the users that have those phones in your db, something like
var results = Users.find(records that have phone in Object.keys(obj) array)

Finally, you iterate your existant records and mark the corresponding contact
for(var i=0;i<results.length;i++){
    obj[results[i].phone].exists = true;
}


text:
Q: Best web app programming platform/ language for someone used to Xcode I have learnt to program apps in Xcode and like the environment, especially the interface builder. I want to learn how to code web apps but don't seem to be able to find any similar platform, everything seems to be pretty much purely code based. Any help on where to start?
Thanks

A: You DO NOT want to work with any web app framework that includes an Interface builder. You will get a WYSIWYG mess of code that will be impossible to work with.
You DO want to adopt a web app framework, which makes deploying a web app fast and intuitive. Ruby on Rails is one of the most popular.
Then integrate that that framework with Bootstrap which makes CSS styling a breeze.
http://getbootstrap.com
This would be my recommendation;
1. Pick any framework like Rails(ruby), flask(Python), play!(Java), etc.
2. Learn how to integrate that framework with Bootstrap. If you choose Rails I recommend this tutorial, which teaches you how to integrate bootstrap: https://www.railstutorial.org/book/beginning


text:
Q: NGINX: Redirect a user based on cookie for a specific URL only I'm building a closed social network and currently when a user is not logged in they will always be redirected to the homepage of my domain.
What I would like to do is do the following:

*

*Use NGINX to check if a user is logged in (through checking for a cookie) and then when they go to the homepage (mydomain.com) redirect to to mydomain.com/newsfeed.

*This check should only be applied when a user brows to the homepage and should not work at ANY other url (or else they would always be redirected).
I'm very new to NGINX and looked at various tutorials for using cookies for redirect but failed to get an answer (most notably to limiting the redirect to only the homepage).
Thanks in advance!

A: Let's pretend I've a cookie like so: name=value
server {
    listen 80;
    server_name mydomain.com;

    location ~* ^/$ {
        if ($cookie_name = "value") {
            return 301 http://example.com/newsfeed/;
        }
    }
}

The location block will only match the homepage, check that the cookie exists (you could also just use if ($cookie_name)), and if present, redirect the user to http://example.com/newsfeed/

A: Final correct solution:
location ~* ^/$ {
 if ($http_cookie ~* "wordpress_logged_in") {
    return 301 http://example.com/newsfeed/;
 }
}


text:
Q: Iterate through dictionary with foreach loop and fetch all key/value pairs with value subset items I have a concurrent dictionary that I am storing key/value pairs in. The complexity here is that the values are not single objects like string or integer, they are a collection of items that are added using a class model. It seems looking at the debug, I am able to add the items to the dictionary successfully, but the issue I have is not knowing how to read these items when iterating through the dictionary from another thread. I simply want to read all the key/value pairs, including all the items and add them to an array that I can pass back to the user through JsonResult/Ajax.
My AlarmEngine Class:
public static ConcurrentDictionary<string, object> concurrentDictionary = new ConcurrentDictionary<string, object>();

public class Alarm
{
    public int AlarmId { get; set; }
    public string AlarmName { get; set; }
    public string AlarmDescription { get; set; }
    public string ApplicationRoleId { get; set; }
    public DateTime DateTimeActivated { get; set; }
}

An extract from the method where I add items to the dictionary:
concurrentDictionary.TryAdd(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"), new Alarm
                {
                    DateTimeActivated = DateTime.Now,
                    ApplicationRoleId = applicationRoleId,
                    AlarmId = alarmId,
                    AlarmName = alarmName,
                    AlarmDescription = description,
                }); // I'm using datetime as the key as this is unique form each key/value pair added.

My AlarmList MVC Controller:
[HttpGet]
public Task<IActionResult> FetchAlarmsListAsync()
{

    // Enumeration is thread-safe in ConcurrentDictionary.
    foreach (var item in AlarmEngine.concurrentDictionary)
    {
        // How do I access the key and value pairs here?
        // Note each value contains a subset of items
        // i want to access all items stored
    }

    return new JsonResult(Array containing all keys and value items);
}

If it's better to read through the whole dictionary and store all keys/value(with sub items) to a list before returning to the user as an JSON array, this would be an acceptable solution for me as well, just keep in mind I want to do this as efficiently as possible to minimize converting from one form to another too many times. Items will be added and removed to the dictionary from other threads, but this particular bit of my application i.e. iteration through the dictionary is just for readonly purposes and it doesn't really matter to me if the contents have changed whilst reading through it, it's just to put together a list of alarms relevant/active at the time of the query.

A: You need to store the data as the right class, do not use object
public static ConcurrentDictionary<string, Alarm> concurrentDictionary = new ConcurrentDictionary<string, Alarm>();
//                                          ^^^

public class Alarm
{
    public int AlarmId { get; set; }
    public string AlarmName { get; set; }
    public string AlarmDescription { get; set; }
    public string ApplicationRoleId { get; set; }
    public DateTime DateTimeActivated { get; set; }
}

Now you can access the properties of the alarm.
// Enumeration is thread-safe in Dictionary.
foreach (var item in AlarmEngine.concurrentDictionary)
{
    Trace.WriteLine(item.Key);  // which is the datetime
    Trace.WriteLine(item.Value.AlarmName);
    // How do I access the key and value pairs here?
    // Note each value contains a subset of items
    // i want to access all items stored
}

One thing you should change is not storing the DateTime as string.
public static ConcurrentDictionary<DateTime, Alarm> concurrentDictionary = new ConcurrentDictionary<DateTime, Alarm>();

A: If these resources are shared amoung multiple clients/threads and mostly the clients are reading. I would suggest a ReaderWriterLockSlim. It allows multiple readers and one writer.
This way the jsons can be generated parallel. A ConcurrentX is usefull passing resources to others thread (like passing ownership) or just share simple typed data.
private static ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();

[HttpGet]
public Task<IActionResult> FetchAlarmsListAsync()
{
    cacheLock.EnterReadLock();
    try
    {
        // Enumeration is thread-safe in Dictionary.
        foreach (var item in AlarmEngine.normalDictionary)
        {
            // How do I access the key and value pairs here?
            // Note each value contains a subset of items
            // i want to access all items stored
        }

        return new JsonResult(Array containing all keys and value items);
    }
    finally
    {
        cacheLock.ExitReadLock();
    }
}

cacheLock.EnterWriteLock();
try
{
    normalDictionary.TryAdd(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"), new Alarm
    {
        DateTimeActivated = DateTime.Now,
        ApplicationRoleId = applicationRoleId,
        AlarmId = alarmId,
        AlarmName = alarmName,
        AlarmDescription = description,
    }); // I'm using datetime as the key as this is unique form each key/value pair added.
}
finally
{
    cacheLock.ExitWriteLock();
}

It's even possible to cache the json result when the dictionary isn't changed, but you should only do such thing when it is a problem.


text:
Q: How to create a flashing record button for iPhone I've looked at several posts, including [this one].1 This is exactly what I want to do, but I cannot get it to work.
I want to show the user that they have pressed a record button, and that they will need to press it again to stop recording.
So far, the code for the start recording method looks like this:
NSLog(@"DetailVC - recordAudio -  soundFilePath is %@", soundFile);
        [audioRecorder prepareToRecord];
        recording = YES;
        NSLog(@"start recording");
        NSLog(@"1");
        //[autoCog startAnimating];

        [audioRecorder recordForDuration:120];
        recording = NO;

        //Start a timer to animate the record images
        if (recording == YES) {
        toggle = FALSE;
        timer = [NSTimer scheduledTimerWithTimeInterval: 2.0
                                                          target: self
                                                        selector: @selector(toggleButtonImage:)
                                                        userInfo: nil
                                                         repeats: YES];

        //UIImage *changeImage = [UIImage imageNamed:stopButtonFile];
        //[recordButton setImage:changeImage forState:UIControlStateNormal];

        //[timer invalidate];
        //timer = nil;

        NSLog(@"2");

        }

and the toggleButton method looks like this:
- (void)toggleButtonImage:(NSTimer*)timer
{
   NSLog(@"%s", __FUNCTION__);
    if(toggle)
    {
        NSLog(@"1");
        /*
        [UIView beginAnimations];
        recordButton.opacity = 0.0;
        [recordButton setAnimationDuration: 1.5];
        [recordButton commitAnimations];
        [recordButton setImage:[UIImage imageNamed:@"record.png"] forState: UIControlStateNormal];
         */
        CGContextRef context = UIGraphicsGetCurrentContext();
        [UIView beginAnimations:nil context:context];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseIn]; //delete "EaseOut", then push ESC to check out other animation styles
        [UIView setAnimationDuration: 0.5];//how long the animation will take
        [UIView setAnimationDelegate: self];
        recordButton.alpha = 1.0; //1.0 to make it visible or 0.0 to make it invisible
        [UIView commitAnimations];
    }
    else
    {
         NSLog(@"2");
        CGContextRef context = UIGraphicsGetCurrentContext();
        [UIView beginAnimations:nil context:context];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut]; //delete "EaseOut", then push ESC to check out other animation styles
        [UIView setAnimationDuration: 0.5];//how long the animation will take
        [UIView setAnimationDelegate: self];
        recordButton.alpha = 0.0; //1.0 to make it visible or 0.0 to make it invisible
        [UIView commitAnimations];
        //[recordButton setImage:[UIImage imageNamed:@"stopGrey.png"] forState: UIControlStateNormal];
    }
    toggle = !toggle;
}

I get to see the logs showing that the loop is iterating, but:

*

*the images do not switch, and

*the operation is not running in parallel with the record method.

I would appreciate any ideas as to how to proceed.

A: Expanding on Ashley's answer, I'd go with something more like this:
- (IBAction)record:(id)sender {
    self.recording = !self.recording;

    if (!self.recording) {
        [UIView animateWithDuration:0.1
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         self.recordButton.alpha = 1.0f;
                     }
                     completion:^(BOOL finished){
                     }];
    } else {
        self.recordButton.alpha = 1.0f;
        [UIView animateWithDuration:0.5
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionAllowUserInteraction
                         animations:^{
                             self.recordButton.alpha = 0.0f;
                         }
                         completion:^(BOOL finished){
                         }];
    }
}

A: Try this:
- (IBAction)record:(id)sender
{
    self.recording = !self.recording;

    [self toggleButton];
}

- (void) toggleButton
{
    if (!self.recording) {
        self.recordButton.alpha = 1.0;
        return;
    }

    [UIView animateWithDuration: 0.5
                          delay: 0.0
                        options: UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         self.recordButton.alpha = !self.recordButton.alpha;
                     }
                     completion:^(BOOL finished) {
                         [self toggleButton];
                     }];

}