text:
Q: Confusion about the boundary of connected components Let $C$ be a connected component of $X\subset\mathbb{R}^n$. I want to prove of disprove that $\partial{C}\subset\partial{X}$ (where $\partial{A}$ means the boundary set of $A$).
In metric space, I know a connected component is closed.
In locally connected space(clearly, $\mathbb{R}^n$ is locally connected), I know a connected component is open.
So, in $\mathbb{R}^n$, any components are clopen. Therefore, the boundary set of a given connected component $C$ is exactly the empty set, which trivially is contained in $\partial{X}$
However, it looks very strange to me. There must be something wrong.
I know this question is definitely a newbie topology question. Any explanation will be appreciated.

A: Let $x \in \mathrm{cl}(C)$.
Then, suppose that $x \in \mathrm{int}(X)$. Since $\mathbb{R}^n$ is locally connected, there is a connected set $V \subset X$ which is a neighborhood of $x$.
Since $C$ is connected and $V$ intersects $C$,
$C \cup V \subset X$ is connected (why?). Therefore, $V \subset C$. That is, $x \in \mathrm{int}(C)$.
That is, for any $x \in \mathrm{cl}(C)$,
$$
  x \in \mathrm{int}(X)
  \Rightarrow
  x \in \mathrm{int}(C).
$$
Therefore,
$$
  \partial C
  =
  \mathrm{cl}(C) \setminus \mathrm{int}(C)
  \subset
  \mathrm{cl}(C) \setminus \mathrm{int}(X)
  \subset
  \mathrm{cl}(X) \setminus \mathrm{int}(X)
  =
  \partial X.
$$
Notice that this proof works for any locally connected space in place of $\mathbb{R}^n$.

Edit: Proof made much much simpler (and correct :-P).

A: Suppose $X$ is locally connected, in this case $\mathbb{R}^n$ is locally connected for any $n \in \mathbb{N}$. If $A \subseteq X$ and $C$ is a connected component of $A$ then:

*

*$C^\circ = C \cap A^\circ$.

*$\delta(C) \subseteq \delta(A)$
The inclusion $C^\circ \subseteq C \cap A^\circ$ is trivial since $C$ is a subset of $A$.
We want to prove that $C \cap A^\circ \subset C^\circ$. Let $x \in C \cap A^{\circ}$, since $X$ is locally connected then there must exist $U$ connected neighborhood of $x$ such that $U \subseteq A$. Since $U$ is connected and contains $x$ and $C$ is the maximal connected set that contains $x$ then $U \subset C$, therefore $x \in C^{\circ}$.
$\therefore C^{\circ} = C \cap A^{\circ}$
By definition $\delta(C) = \overline{C} \backslash C^{\circ}$, using what we just proved we have
\begin{align}
\delta(C) &= \overline{C} \backslash (C \cap A^{\circ})\\
&= \overline{C} \cap (C \cap A^{\circ})^c\\
&= \overline{C} \cap (C^c \cup (A^{\circ})^{c})\\
&= (\overline{C} \cap C^c) \cup (\overline{C} \cap A^{\circ})
\end{align}
Notice that $C$ is always a closed set, therefore $C = \overline{C}$, therefore
\begin{align}
\delta(C) &= (C \cap C^c) \cup (C \cap (A^{\circ})^c)\\
&= \varnothing \cup (C \backslash A^{\circ})\\
&= C \backslash A^{\circ}
\end{align}
Lastly, since $C \subseteq A$ it's not hard to see that $C \backslash A^{\circ} \subseteq \overline{A}  \backslash A^{\circ}$.
$\therefore \delta(C) \subseteq \delta(A)$


text:
Q: VS Code extension - programmatically find keybindings When programming a vscode extension...
Is there a programmatic way to find the keybinding for a provided command?
I would like to be able to see if a user has updated the key mapping from default for a command so that the UI can display the up-to-date binding. (and if not, look up the default binding)
Here are the APIs I've looked into so far:

*

*vscode.workspace.getConfiguration() - I cannot determine how to access the keybindings.json file / perform a lookup.

*vscode.extensions.getExtension(name/id) allows access to the package.json, but not the command or keybinding override.

*vscode.getCommands does not provide access to the keybinding values either...

A: You can get keybinding values from the keybindings.json file using NodeJS.
keybindings.json path on diferrent systems:
Windows: %APPDATA%\Code\User\keybindings.json
Mac: $HOME/Library/Application Support/Code/User/keybindings.json
Linux: $HOME/.config/Code/User/keybindings.json

To build the path you'll need to get Environment variables using process.env.{variableName}.
For example for MacOS it'll be:
var process = require('process');
//...
var keybindingsPath = process.env.HOME + "/Library/Application Support/Code/User/keybindings.json";

vscode.workspace.openTextDocument(keybindingsPath).then((document) => {
    let text = document.getText();
    //then use this JSON file for your needs
    //...
});

A: Inspired by @nikita-kunevich answer Here is a code I use in autoit extension.
First it gets default keybindings from package.json, then it parses keybindings.json via JSON5 library (can't use JSON.parse() because file may contain comments) and replaces default keys with new keys.
//get keybindings
const keybindings = new Promise(resolve => {
  //default keybindings
  const data = require("../package.json").contributes.keybindings.reduce((a,b)=>(a[b.command]=b.key,a),{});
  const parse = list => {
    for(let i = 0; i < list.length; i++) {
      if (list[i].command in data)
        data[list[i].command] = list[i].key;
    }
    for(let i in data) {
      //capitalize first letter
      data[i] = data[i].replace(/\w+/g, w => (w.substring(0,1).toUpperCase()) + w.substring(1));
      //add spaces around "+"
      // data[i] = data[i].replace(/\+/g, " $& ");
    }

    Object.assign(keybindings, data);
    resolve(data);
  };
  const path = {
    windows: process.env.APPDATA + "/Code",
    macos: process.env.HOME + "/Library/Application Support/Code",
    linux: process.env.HOME + "/config/Code"
  }[{
    aix: "linux",
    darwin: "macos",
    freebsd: "linux",
    linux: "linux",
    openbsd: "linux",
    sunos: "linux",
    win32: "windows"
  }[process.platform]||"windows"];
  const file = ((process.env.VSCODE_PORTABLE ? process.env.VSCODE_PORTABLE + "/user-data/User/" : path) + "/User/keybindings.json")
    .replace(/\//g, process.platform == "win32" ? "\\" : "/");

  //read file
  workspace.openTextDocument(file).then(doc => {
    //we can't use JSON.parse() because file may contain comments
    const JSON5 = require("json5").default;
    parse(JSON5.parse(doc.getText()));
  }).catch(er => {
    parse([]);
  });
});

To install JSON5 package use:
npm install json5

Usage:
keybindings.then(list => {
  console.log(list);
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Drop factor levels containing single observation I'd like to know if there exists a simple function (similar to drop.levels) to drop levels from a factor containing just one observation. I'll provide a reproducible example below. Until now I'm only able to store the names of the factors containing levels with just one observation, but it will be a pain to write all the code to drop the specific levels, is there some quick way to do it?
db0 <- data.frame(let = c(sample(letters[1:5], 99, replace = T),"z"),
                  let2 = sample(letters[6:11], 100, replace = T))

#Checking which factor has levels with only one obs
facLevels <- lapply(db0, table)
facNames <- list()
for(i in 1:length(facLevels)){
  facNames[i]<-ifelse(min(facLevels[[i]])==1, names(facLevels[i]), NA)
}
facNames <- as.character(facNames[!is.na(facNames)])

basically what I want to do is to drop just the z level in let.
Thanks.

A: The for loop here will set any factor level with one observation to NA then fully removes that factor level from the column by refactoring it.
db0 <- data.frame(let = c(sample(letters[1:5], 99, replace = T),"z"),
  let2 = sample(letters[6:11], 100, replace = T))

#Checking which factor has levels with only one obs
facLevels <- lapply(db0, table)
# make a list for each factor level that has one value
to_change <- lapply(facLevels, function(x) names(x)[x==1])

for(i in 1:ncol(db0)){
  if(length(to_change[[i]])>0){
  # set as NA
  db0[which(db0[,i] %in% to_change[[i]]),i] <- NA
  # removes the factor level, remove the code below if this is not what
  # what you wanted to do
  db0[,i] <- as.factor(db0[,i])
  }
}

> tail(db0)
     let let2
95     b    i
96     a    g
97     c    k
98     d    j
99     d    f
100 <NA>    j

> levels(db0[,i])
[1] "f" "g" "h" "i" "j" "k"

A: And in case you don't like writing for loops
# create a sample dataset
db0 <- data.frame(let1 = c(sample(letters[1:5], 99, replace = T),"z"),
                  let2 = sample(letters[6:11], 100, replace = T))

# calculate how many times each level is present
facLevel <- lapply(db0, table)

# drop levels which are present once
test <- sapply(facLevel, function(x) x[x != 1])

# drop rows in the original dataset where a unique level is present (do this for both columns)
db1 <- db0[rowSums(mapply(function(x, y) x %in% names(y), db0, test)) == ncol(db0), ]


text:
Q: Django - UpdateView - Empty select field? I have an Updateview :
class Cotisations_des_adherentsUpdate(UpdateView):
    model                = Cotisations_des_adherents
    form_class           = UpdateCotisations_des_adherentsForm
    template_name_suffix = '_update'

And a model( extract here) :
class Cotisations_des_adherents (models.Model):
    n_reglement                  = models.AutoField(primary_key=True)
    cotisation_acquittee         = models.FloatField(    blank=True  ,     null=True, choices=settings.CHOICE_OUI_NON)
    frais_de_dossier_acquittes   = models.FloatField(    blank=True  ,     null=True, choices=settings.CHOICE_OUI_NON)
    a_jour                       = models.FloatField(    blank=True  ,     null=True, choices=settings.CHOICE_UN_ZERO)

the settings value are :
CHOICE_OUI_NON          = [ (1  , "1-oui"     ),
                            (0  , "0-non"     )]
CHOICE_SEXE             = [ (1, "1-Homme"   ),
                            (2, "2-Femme"   ),]

And the form_class inherite from a personnal class:
class UpdateCotisations_des_adherentsForm(Cotisations_des_adherentsForm):
    def __init__(self, *args, **kwargs):
        super(UpdateCotisations_des_adherentsForm, self).__init__(*args, **kwargs)  # Call to ModelForm constructor

the super class is (extract here):
class Cotisations_des_adherentsForm(ModelForm):
    error_css_class     = 'error'
    required_css_class  = 'required'

    class Meta:
        model   = Cotisations_des_adherents
        fields = [   "n_reglement",
                     "cotisation_acquittee",
                     "a_jour",
                    ]
    def __init__(self, *args, **kwargs):
        super(Cotisations_des_adherentsForm, self).__init__(*args, **kwargs)

My issue is that on the upadte view I don't see the last saved value of the user :
cotisation_acquittee
frais_de_dossier_acquittes
a_jour

gives me an empty select html :

I understand from the doc that there is something sepecific about the CHOICES option :

If the model field has choices set, then the form field's widget will
  be set to Select, with choices coming from the model field's choices.
  The choices will normally include the blank choice which is selected
  by default. If the field is required, this forces the user to make a
  selection. The blank choice will not be included if the model field
  has blank=False and an explicit default value (the default value will
  be initially selected instead).

(I verified, there are information saved in the db :
|2.0|0.0|1.0

)
How can I make the last value saved in the database appearing in the select box in the updating html form ?

A: The use of floats here is central to your problem. Although 1 and 1.0 are numerically equivalent, they are not the same value and therefore the form does not recognise the 1.0 stored in the database as being one of the possible choices in the form.
You could probably fix this by using 1.0 and 0.0 as the values in your CHOICES tuples, but the proper way is to use the correct data type in the first place, which is Boolean.


text:
Q: Why is it recommended to use TestNGCitrusTestRunner instead of TestNGCitrusTestDesigner? Due to the way I set up my Maven projects the default sample Test class suggests extending Test classes with TestNGCitrusTestDesigner while using Citrus version 2.7.6. Hence I worked with the Designer since to do integration tests.
While troubleshooting my projects set up with the Designer I've run into this statement several times:
"It is recommended that you use TestNGCitrusTestRunner."
This statement was not backed up with further statements such as that the Designer might be outdated or faulty besides that the Runner is what should be used with Citrus version 2.7.5 or higher.
Why is it recommended? Does the Runner have advantages in it's usage in comparison to the Designer? Is the Designer in fact outdated?

A: The designer implementation will read all test actions first into a complete test case at design time. As soon as the test case is completely built via Java DSL in the design time the whole test case is executed in a runtime step.
The runner implementation is not having a separation between design time and runtime. The test case and its actions are executed immediately when built with Java DSL. This approach feels more natural to developers as you can access the results of test actions immediately and you can debug the runner execution.
The designer is not able to perform a debug session as you would expect. In addition to that the designer is not capable for mixing custom Java code between test actions.
Designer and runner implementations do support the exact amount of actions and Java DSL fluent API. The designer approach is likely to be deprecated in future as developers keep complaining about the design time to runtime separation.
There is still a todo for the Citrus team to strengthen the runner usage in samples and documentation though.
Please see also the Citrus documentation that tries to explain the different designer and runner approaches with a concrete example: https://citrusframework.org/citrus/reference/html/index.html#writing-test-cases-in-java


text:
Q: Not read all entered words in customEditField in Blackberry I am using custom EditField which given in Rim samples.
With this editfield, i can input maximum characters in one line.. But the problem is that left most hidden characters are not getting when i am getting from edittext.
Following is my CustomEditField class
  import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.component.EditField;

public class CustomEditfield extends Manager
{

    private final static int DEFAULT_LEFT_MARGIN = 0;
    private final static int DEFAULT_RIGHT_MARGIN = 5;
    private final static int DEFAULT_TOP_MARGIN = 0;
    private final static int DEFAULT_BOTTOM_MARGIN = 0;

    private final static int DEFAULT_LEFT_PADDING = 5;
    private final static int DEFAULT_RIGHT_PADDING = 5;
    private final static int DEFAULT_TOP_PADDING = 0;
    private final static int DEFAULT_BOTTOM_PADDING = 0;

    private int topMargin = DEFAULT_TOP_MARGIN;
    private int bottomMargin = DEFAULT_BOTTOM_MARGIN;
    private int leftMargin = DEFAULT_LEFT_MARGIN;
    private int rightMargin = DEFAULT_RIGHT_MARGIN;

    private int topPadding = DEFAULT_TOP_PADDING;
    private int bottomPadding = DEFAULT_BOTTOM_PADDING;
    private int leftPadding = DEFAULT_LEFT_PADDING;
    private int rightPadding = DEFAULT_RIGHT_PADDING;

    private int totalHorizontalEmptySpace = leftMargin + leftPadding + rightPadding + rightMargin;
    private int totalVerticalEmptySpace = topMargin + topPadding + bottomPadding + bottomMargin;

    private int minHeight = getFont().getHeight() + totalVerticalEmptySpace;

    private int width ;
    private int height ;

    private EditField editField;
    private Bitmap _currentPicture;

    public CustomEditfield(String label,String initialValue,int maxChars,long style,Bitmap image)
    {
        super(0);
        this._currentPicture=image;

        this.width=_currentPicture.getWidth();
        this.height=_currentPicture.getHeight()+20;
        editField = new EditField(label, initialValue, maxChars,style);
//        editField.setPadding(_currentPicture.getHeight()/7, 0, 0, _currentPicture.getWidth()/40);
        add(editField);
    }

    protected void sublayout(int width, int height)
    {
        Field field = getField(0);
        layoutChild(field, this.width - totalHorizontalEmptySpace, this.height - totalVerticalEmptySpace);
        setPositionChild(field, leftMargin+leftPadding, topMargin+topPadding);
        setExtent(this.width, this.height);
    }

    public void setTopMargin(int topMargin)
    {
        this.topMargin = topMargin;
    }

    public void setBottomMargin(int bottomMargin)
    {
        this.bottomMargin = bottomMargin;
    }

    protected void paint(Graphics graphics)
    {
//        graphics.drawRoundRect(leftMargin, topMargin, width - (leftMargin+rightMargin), height - (topMargin+bottomMargin), 5, 5);
        graphics.drawBitmap(leftMargin, topMargin, width - (leftMargin+rightMargin), height - (topMargin+bottomMargin), _currentPicture, 5, 0);
        EditField ef = (EditField)getField(0);
        String entireText = ef.getText();

        String textToDraw = "";
        Font font = getFont();
        int availableWidth = width - totalHorizontalEmptySpace;
        if (font.getAdvance(entireText) <= availableWidth)
        {
            textToDraw = entireText;
        }
        else
        {
            int endIndex = entireText.length();
            for (int beginIndex = 1; beginIndex < endIndex; beginIndex++)
            {
                textToDraw = entireText.substring(beginIndex);
                if (font.getAdvance(textToDraw) <= availableWidth)
                {
                    break;
                }
            }
        }

        ef.setText(textToDraw);

        super.paint(graphics);

    }

    public int getPreferredWidth()
    {
        return width;
    }

    public int getPreferredHeight()
    {
        return height;
    }

    protected boolean keyChar(char ch, int status, int time)
    {
        if (ch == Characters.ENTER)
        {
            return true;
        }
        else
        {
            return super.keyChar(ch, status, time);
        }
    }

    public String getText()
    {
        return ((EditField)getField(0)).getText();
    }

    public void setText(final String text)
    {
        ((EditField)getField(0)).setText(text);
    }
}

------ In my screen class---
et_fname = new CustomEditfield("", "", 50, EditField.NO_NEWLINE
            | EditField.FOCUSABLE, txt_bg);

So when i called
et_fname.getText().toString().trim()

It will return only visible characters.
So how can i get all entered characters.
If any one has idea,please help..
Help will be appreciated.

A: Look at your paint method.  In there you truncate the EditField so that it only contains the text that will fit.  So what did you expect to happen?
You might think you can save the full text, then call super.paint() and the restore the full text, but that is actually gong to cause you other problems.  A setText() on an EditField will tell the field that it has been updated and so it will try to repaint itself.  So you will truncate, which will flag up to the EditField it needs to be painted, call super.paint, replace, which will flag up a paint required again, and then the paints for the EditField will kick in and that will try to paint themselves, I suspect on the way invoking the paint() for the Manager which will get recursive and messy.
This approach to painting only the visible are in the Manager is flawed and will never work.
What you seem to be trying to do is a single line EditField that scrolls left and right,  The more normal approach to doing this is to have a full width HorizontalFieldManager add the EdtiField to that and have the HFM scroll the EditField left and right.  I have not looked for sample code that does this, but I suspect you will find some if you look round.  So have a go at that option and let us know how you get on.

A: According to Peter Strange suggestion,
I found new solution for Single line editfield which have solved my actual problem.
Following is my CustomEditField class for Single line editfield with horizontal scrolling.
 import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.container.HorizontalFieldManager;

public class CustomEditfield extends HorizontalFieldManager
{
    private int managerWidth;
    private int managerHeight;
    BasicEditField searchEdit;
    private Bitmap _currentPicture;
    private int width ;
    private int height ;
    private final static int DEFAULT_LEFT_MARGIN = 0;
    private final static int DEFAULT_RIGHT_MARGIN = 5;
    private final static int DEFAULT_TOP_MARGIN = 0;
    private final static int DEFAULT_BOTTOM_MARGIN = 0;

    private final static int DEFAULT_LEFT_PADDING = 5;
    private final static int DEFAULT_RIGHT_PADDING = 5;
    private final static int DEFAULT_TOP_PADDING = 0;
    private final static int DEFAULT_BOTTOM_PADDING = 0;

    private int topMargin = DEFAULT_TOP_MARGIN;
    private int bottomMargin = DEFAULT_BOTTOM_MARGIN;
    private int leftMargin = DEFAULT_LEFT_MARGIN;
    private int rightMargin = DEFAULT_RIGHT_MARGIN;

    private int topPadding = DEFAULT_TOP_PADDING;
    private int bottomPadding = DEFAULT_BOTTOM_PADDING;
    private int leftPadding = DEFAULT_LEFT_PADDING;
    private int rightPadding = DEFAULT_RIGHT_PADDING;

    private int totalHorizontalEmptySpace = leftMargin + leftPadding + rightPadding + rightMargin;
    private int totalVerticalEmptySpace = topMargin + topPadding + bottomPadding + bottomMargin;

    public CustomEditfield(String label,String initialValue,int maxChars,long style,Bitmap image)
    {
        super(Manager.NO_HORIZONTAL_SCROLL);
        this._currentPicture=image;
        this.width=_currentPicture.getWidth();
        this.height=_currentPicture.getHeight()+20;

        searchEdit = new BasicEditField(label, initialValue, maxChars,style){
            public int getPreferredHeight()
            {
                return _currentPicture.getHeight();
            }
            public int getPreferredWidth()
            {
                return _currentPicture.getWidth();
            }
//            public void paint(Graphics g)
//            {
//                getManager().invalidate();
//                super.paint(g);
//            }
        };
        searchEdit.setPadding(_currentPicture.getHeight()/7, 0, 0, 0);

        HorizontalFieldManager hfm = new HorizontalFieldManager(Manager.HORIZONTAL_SCROLL)
        {
            public void sublayout(int width, int height)
            {
                if (managerWidth == 0) {
                    managerWidth = searchEdit.getPreferredWidth();
                }
                if (managerHeight == 0) {
                    managerHeight = searchEdit.getPreferredHeight();
                }
                super.sublayout(managerWidth, managerHeight);
                setExtent(managerWidth,managerHeight);
            }
            public void paint(Graphics g) {
                super.paint(g);
            }
        };
//        searchEdit.setMaxSize(70);
        hfm.add(searchEdit);
        add(hfm);
    }

    public int getPreferredHeight()
    {
        return _currentPicture.getHeight();
    }

    public String getText()
    {
        return searchEdit.getText();
    }

    public void setText(final String text)
    {
        searchEdit.setText(text);
    }

    protected void sublayout(int maxWidth, int maxHeight)
    {
        Field currField;

        currField = this.getField(0);
        this.setPositionChild(currField,leftMargin+leftPadding, topMargin+topPadding);
        this.layoutChild(currField, this.width - totalHorizontalEmptySpace, this.height - totalVerticalEmptySpace);
        setExtent(this.width, this.height);
    }

    protected void paint(Graphics graphics)
    {
        graphics.drawBitmap(0, 0, getWidth(), getHeight(), _currentPicture, 0, 0);
//      graphics.drawBitmap(leftMargin, topMargin, width - (leftMargin+rightMargin), height - (topMargin+bottomMargin), _currentPicture, 5, 0);
        super.paint(graphics);
//        graphics.drawRect(0, 0, this.getPreferredWidth(), this.getPreferredHeight());
    }
}

I have found this solution from Blackberry - Custom EditField Cursor
I am giving this so it can help others.

A: the problem is when you typed character once width of field occupied with characters. it will take new character and drop old characters in field. so when you get data inside field you only get characters available on the fields.
you can reproduce this by following steps:
1. type atleast 8 characters.
2. prees back key.
3. then come to 1st character it is not that character that you entered.


text:
Q: JavaScript doesn't work until I resize the window then resize it back I've implemented JavaScript on wordpress and it only works after i re-size the window from the original size to a different size then back to the original size. I don't understand why it just doesn't work from the start?
Here is the script in the head

The place the script is used in content.php inside the body

        <a href="<?php the_permalink(); ?>"><?php the_content(); ?>

        <?php echo get_simple_local_avatar( $id_or_email, $size, $default, $alt ); ?>

A: Scripts should be enqueued for execution using wp_enqueue_script in functions.php file of your theme. This is the preferred method to enqueue scripts and style.
http://codex.wordpress.org/Function_Reference/wp_enqueue_script
Perhaps this might be preventing your script from being executed right from start.

A: Would prefer to comment but don't have the reputation, please check here.
Running javascript after page is fully rendered
I had this issue prevsiouly as a script was being triggered before the page was rendered. Resizing the window, zooming in and out and also bringing up the chrome element inspector reszied the issue div.


text:
Q: In WiX can Windows Service re-start delays be set individually? The SERVICE_FAILURE_ACTIONS struct contains multiple SC_ACTIONs (normally 3). Each contains a re-start delay.
However in WiX the util:ServiceConfig contains a single RestartServiceDelayInSeconds which sets the value for all 3.
e.g.
  <util:ServiceConfig FirstFailureActionType="restart"
                      SecondFailureActionType="restart"
                      ThirdFailureActionType="restart"
                      ResetPeriodInDays="1"
                      RestartServiceDelayInSeconds="1" />

Is there a way to give 3 different values for the delay for the 3 failure actions?

A: Looks like it is not possible. The description of the RestartServiceDelayInSeconds states:

If any of the three *ActionType attributes is "restart", this specifies the number of seconds to wait before doing so.


text:
Q: How to make machine learning model with One multiple value feature I would like to train a machine learning model with several features as input as X[] and with one output as Y. For example Every sample has a Data frame like this:
X[0], X[1], X[2], X[3], X[4], Y
Let's say One sample the followings Data is only one value:
X[0], X[1], X[2], X[4], Y
This is normal machine training problem.
But now, if I would like to set X[3] multiple values for example sample 1 Data is:
X[0] | X[1] | X[2] |         X[3]         | X[4] | Y
 10  |  5   |   6  | [10, 20, 30, 40, 50] |  7   | 90

Data in sample 2 is:
X[0] | X[1] | X[2] |         X[3]         | X[4] | Y
 11  |  7   |   5  | [20, 30, 40, 50, 60] |  3   | 80

Is this possible to follow the normal machine training process and got a model which could calculate a sample with other example with Data like:
X[0]   | X[1] |  X[2]  |         X[3]         | X[4] | Y
 10.5  |  6   |   5.5  | [15, 25, 35, 45, 55] |  5   | ???

If the length for each X[3] is not long, it is possible to divide the X[3] into multiple new features, but if the length of X[3] is very long (len > 1000) with different distribution, making binary is also lead to too many new features. Is there any way to treat the X[3] directly without adding new features?

A: A simple thing is to try taking the mean or median of X[3] and replace X[3] with its mean or median. Then train a normal machine learning model using updated data.

A: Solution depends very much on the task you are pursuing.
Main approaches:

*

*convert X3 to one values (use mean, median, sum) or multiple features (min, max, stdev, quantiles),

*PCA or another dimension reduction algorithm for to reduce the dimension inside,

*for free text features use embedding methods.

Note: I would recommend first checking whether you are throwing out important data by replacing the X3 vector with a single value.

A: Do you have the data dictionary? What is X[3]? It will always be good to understand what that feature stands for and accordingly do a transformation that makes contextual sense.
In general, you can split that feature into 2 - length and some aggregation like sum, mean, median. Or even multiple features, but it is important to understand the meaning of the feature to decide which transformation or aggregation makes more sense.


text:
Q: Is there a way I can extract a specific word in a string if I only have part of the word? I would like to extract a link from a string without questions such as "Go to", "Open", "take me to"... Is there a way I can extract a single word without spaces or punctuation as long as it has the domain in such word? (E.g. I want to find the link "google.com" in a string that contains "Go to google.com". I am looking for .com, .org, .net, etc to be in the link.) I want the extracted link to be in a variable form.
I use Python 3.7.3.
I tried .split and ".com" in i:
The code is
i = input("What should I do? ")
    if ".com" in i or ".org" in i:
        print(i)

I want the output to just include the link but it includes "Go to (link)". Sadly I don't know how I can just output a link into a variable.

A: What you're looking for is regular expression. You can define regex pattern to extract from a string. [Python re][1] library is very rich and has lot of useful utilities to use from. Sample below:
>>> import re
>>> y = "Go to google123.net"
>>> pattern = r'([\w\d]+\.(com|org|net))'
>>> re.findall(pattern, y)
[('google123.net', 'net')]
>>> re.search(pattern, y).group(0)
'google123.net'

  [1]: https://docs.python.org/3/library/re.html

A: You should use a regular expression for this task. For example:
import re

pattern = "(https?:\/\/)?(www\.)?([a-zA-Z0-9]+(-?[a-zA-Z0-9])*\.)+[\w]{2,}(\/\S*)?"

text_1 = "Go to google.com"
text_2 = "Read more on www.microsoft.com"
text_3 = "available at http://wikipedia.org"

texts = [text_1, text_2, text_3]

for text in texts:
    matched_urls = re.finditer(pattern, text)  # collect all matches
    extracted_urls = [m.group(0) for m in matched_urls]  # extract matched strings
    print(extracted_urls)

And the output will be:
['google.com']
['www.microsoft.com']
['http://wikipedia.org']


text:
Q: Blob creating function in javascript saving multiple files Can someone explain to me how this piece of code works. Also, the output is not what I want. It saves 2 files instead of 1.
Javascript
function saveTextAsFile() {
     var textToWrite = document.getElementById('textArea').innerHTML;
     var textFileAsBlob = new Blob([ textToWrite ], { type: 'text/plain' });
     var fileNameToSaveAs = "file.txt";

     var downloadLink = document.createElement("a");
     downloadLink.download = fileNameToSaveAs;
     downloadLink.innerHTML = "Download File";
     if (window.webkitURL != null) {
       downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
     } else {
       downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
       downloadLink.onclick = destroyClickedElement;
       downloadLink.style.display = "none";
       document.body.appendChild(downloadLink);
     }

     downloadLink.click();
   }

   var button = document.getElementById('save');
   button.addEventListener('click', saveTextAsFile);

   function destroyClickedElement(event) {
     document.body.removeChild(event.target);
   }

HTML
    <button id="save" onclick="saveTextAsFile()">Save</button>
    <textarea id="textArea" class="Textarea" placeholder="Click to Type" cols="20"></textarea>

A: You code does NOT work:

*

*textarea input values are read with .value not .innerHTML, you where getting no output so
change:
var textToWrite = document.getElementById('textArea').innerHTML;
into
var textToWrite = document.getElementById('textArea').value;

*You get 2 files because you made 2 same events on same button that call same function, remove one of those:
<button id="save" onclick="saveTextAsFile()">Save</button>
here remove onclick="saveTextAsFile()" or remove this two lines:
var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);
This will fix your errors, and as far how whole code works, this is not code review site, for that visit https://codereview.stackexchange.com/ or google each command and read its definitions.


text:
Q: how to create a MDX query to count customer retention How can I get the retained customer from the previous year?
1. Customer Retention...the most recent trailing 12 months vs the previous 12 months...exclude new business...what % of customers are we still selling to? Ideally 100%...

explaining the above statement:-

I need the percentage of customers who were retained this year from the previous year depending on sales. for example- 1,2,3,4,5 (This year) are the customers doing business with us this year and 1,2,3,4,6 (previous Year) are the customers doing business in the previous year. so what I am looking for is the number of customers who have been retained from the previous year is 1,2,3,4 is (Four) divided by the total number of customers whom we are doing business within the previous year 1,2,3,4,6 is (Five). If I can get this somehow the percentage calculation is simple. So the percentage of customers who have been retained is (4/5)*100 = 80%. I want to calculate this as a measure for all the years.


text:
Q: Finding 2-Tuple Combinations of IEnumerable collection, C# I would like to implement a method, that takes a collection of an unknown Type as a parameter and returns a Collection of 2-tuples which contains all possible distinct combinations  from these elements (with no repetition). My Code:
public static IEnumerable<Tuple<T, T>> Get2Combinations<T>(this
IEnumerable<T> col)
    {
        /*foreach (var item1 in col)
        {
            col.GetEnumerator().MoveNext();
            foreach (var item2 in col)
            {
                yield return new Tuple<T, T>(item1, item2);
            }
        }*/
        for (int i = 0; i < col.Count(); i++)
        {
            for (int j = i + 1; j < col.Count(); j++)
            {
                yield return new Tuple<T, T>(col.ElementAt(i),
col.ElementAt(j));
            }
        }
    }

What I'm doing is i take the first element and take a pair with every other. Then using this inner for loop i loop through all the remaining ones. The problem i see is the method col.ElementAt(i). If we look into source code, we see that if 'col' is of type IList, then this gets directly the value at given index, but taking any other collection, this would be veery very slow and would take a lot of time.
I attempted to deal with this using foreach loops (the commented section), which are efficient when using IEnumerable, but that part just doesn't work, because the enumerator is common for both inner and outer loop and therefore this produces set of all 2-tuples, where some of them are repeated.
Would anyone give me some suggestions, how to improve this code?

A: The problem is that Enumerable is designed to describe a class where you can iterate through it (like a stream). Its not intended to support efficiently random access (like an array).
Where you use Count() you are forcing the Enumerable to iterate itself to its end, so in the case of a Stream this will wait until the entire stream is read. Of course a Stream might not support efficient direct access, or even buffer its content in memory (remember - it just promises to support enumeration) - so subsequently calling ElementAt() could force it to re-read from the beginning to the position indicated.
Best way to solve this is to swap from IEnumerable to IList. This means it does support random access; clearly it could still be poorly performing, but thats not the responsibility of your function.


text:
Q: What is the difference between "notice" and "realize"? I believe these are used in the same way, but is there any difference?
I think they both mean "to remember something".
Which is the more polite way to say it and which is more casual?

*

*I noticed that the score was wrong.

*I just realized I have to go home

A: They are very similar in meaning but there are subtle differences in how they are used. Notice involves direct perception, such as seeing or hearing a thing, without necessarily thinking about it. Realize involves thinking about something and coming to a conclusion, and does not require seeing or hearing it.
The relevant definitions from Merriam-Webster are:

Notice: to become aware of (something or someone)

Realize: to conceive vividly as real : be fully aware of

Notice typically involves a passive seeing or hearing something, for instance you notice a door is open or an alarm is going off. There is not much thought involved. You can also "notice something in passing", i.e. see or hear it but not pay much attention to it.
Realise tends to involve more of a mental process. If you realise something you are commonly thinking about it, rather than directly seeing or hearing it.
One difference would be if you notice the oven was on vs. you realise the oven was on. In the former case, you are probably in the kitchen and actually looking in the oven, while in the latter case you might be far away but are thinking about the oven and come to the conclusion that you did not turn it off.
Having said that, there are cases where either would do, for instance if you look at something and have a thought about it. If you look in a kennel and see the dog is gone, then you might say "I noticed the dog was gone" or "I realised the dog was gone", depending on whether you're focused on seeing the dog wasn't there, or working out that it wasn't there.


text:
Q: Gödel diagonalization and formulas not holding for themselves Is there a formula $\varphi (n)$ in one free variable $n$ in ZFC (PA etc.) such that for every formula $\psi(n)$ in one variable the equivalence
$$ \varphi ( \ulcorner\psi\urcorner) \leftrightarrow \neg \psi (\ulcorner\psi\urcorner) $$
is provable? Because this would imply the meta-equivalence
$$\vdash \varphi (\ulcorner\varphi\urcorner) \quad \Leftrightarrow \quad \vdash \neg \varphi (\ulcorner\varphi\urcorner) $$
so that the consistency of our formal system leads to neither $\varphi (\ulcorner\varphi\urcorner)$ nor its negation being provable.
My philosophy is: Formulas like $\psi (n)$ represent subsets of the natural numbers and gödelization seems to be an injection from the set of those formulas into $\mathbb{N}$. The $\varphi$ above corresponds exactly to the subset, that produces the  contradiction in the proof of Cantor's theorem.
I once read a prove of the first incompleteness theorem but I remember the Gödel formula to be more complicate. What do you know about the suggested $\varphi$?
I also observe the resemblence between Cantor's theorem, the liar paradox, the Russel set and the Grelling–Nelson paradox. These paradoxes always arise if one considers properties of properties. Because a property can be associated to the class of all objects it holds for, the consideration of properties as objects, that can be inserted into properties, creates an injection from the totality of classes into the class of all objects and these injection, by Cantor's theorem, cannot exist. The paradoxes (Does a sentence holding for those sentences not holding for themselves hold for itself?, does a set containing those sets not containing themselves contain itself?, does a word describing those words not describing themselves describe itself?) now simply imitate the proof technique of Cantor's theorem. So I am interested if Cantor's theorem can be used to prove Gödel's inconsistency theorems.

A: Unless I'm missing something, this isn't possible unless the theory in question, which I'll call "$T$," is inconsistent: taking $\psi=\varphi$ we would have $$T\vdash (\varphi(\ulcorner\varphi\urcorner)\leftrightarrow\neg\varphi(\ulcorner\varphi\urcorner)).$$
That is, there is a sentence $\alpha$ (namely, $\alpha\equiv\varphi(\ulcorner\varphi\urcorner)$) such that $T\vdash (\alpha\leftrightarrow\neg\alpha)$. This clearly means that $T$ is inconsistent.

In a bit more detail, to make it clear that all rules are being followed, your assumption is that for each $\psi$ we have $$T\vdash (\varphi(\ulcorner\psi\urcorner)\leftrightarrow\neg\psi(\ulcorner\psi\urcorner)).$$ So taking $\psi$ to be $\varphi$ yields as a specific instance the contradiction-inducing sequent above; there's no need to pass to a "meta-equivalence."

Re: the role of diagonalization as a general framework for such arguments, see e.g. A universal approach to self-referential paradoxes, incompleteness and fixed points. My brief spiel on the matter would be that Lawvere's fixed point theorem has many such results as instances, but in no way "trivializes" them - you still need to set up the category in question and check its relevant properties. But there is definitely something real there.


text:
Q: Newtonsoft Json.Net correct parsing of string arrays inside a JSON object I have the following problem, I want to parse a Json object I get passed by a url query string
e.g.
...&json={tags=[tag1,tag2]}

I have used
JsonConvert.DeserializeObject<Dictionary<string, object>>(json)

But when calling the Deserialize method I get an error
Newtonsoft.Json.JsonReaderException : Unexpected character encountered while parsing value: d. Line 1, position 8.

If I pass in the string
"{tags:[\"tag1\",\"tag2\"]}

It works fine, I don't want my users to have to add the "" quotes
Is there a way to work around this problem?

A: pseudocode For a solution could be...
Grab the json query string element.
Split on first equals "=".
Grab all text between "{tags=[" and "]}"
Take that text split on ","
trim any whitespace off of the items.
Join them back together but put quotes around them and coma delimited them.
put that value back inbetween "{tags=[" and "]}"   ie "{tags=[" + newValue+ "]}"
Here is some sample C# code...
        [Test]
        public void TestHack()
        {
            string almost = "{tags=[tag1,tag2]}";
            string json = this.HackToJson(almost);
            Trace.WriteLine(json);
        }
        public string HackToJson(string almostJson)
        {
            if( almostJson.StartsWith("{tags=[") && almostJson.EndsWith("]}"))
            {
                int tagsLen = "{tags=[".Length;
                string tags = almostJson.Substring(tagsLen, almostJson.Length - (tagsLen + 2));

                var items = tags.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                var itemsCleaned = (from c in items select "\"" + c.Trim() + "\"");

                var jsonpart = string.Join(",", itemsCleaned);

                var json = string.Format("{{tags=[{0}]}}", jsonpart);

                return json;

            }
            throw new NotImplementedException("not sure what to do here... ");
        }


text:
Q: Mocking REST call to another rest-service I've written a REST proxy that calls a REST service
@RequestMapping(value = { "session" }, method = {RequestMethod.GET)
    @ResponseBody
    public String sesionGet(HttpServletRequest request, HttpServletResponse httpServletResponse) {

            //call rest webservice
            PostResponse postRequest = IncomeAccessUtils.postRequest(/*call web esrvice*/);

I need to do an integration test on that proxy but sometimes the server at which the external web service deployed on is down. Can I mock a response from webservice call ? I am using spring-test-mvc and/or rest-assure frameworks for testing.

A: Yes there are several way of doing this in Java.
Without much details I would recommend looking at betamax - it records any network integration and saves it for replay later. You can pass in whethere you want to run live or use the recording. (In one project we ran against real servers in the CI env but used version controlled recordings when running tests locally.)
SoapUI is another tool capable of mocking a web server. This may be a good choice if you work with WSDL and/or SOAP. (Poor you! :-) ) There are numerous such alternatives for rest out there but I don't have it fresh in my head.
A simplistic alternativ is to run pythons simple HTTP server: python -m SimpleHTTPServer 8888. It just serves whatever is in the directory where it was started. Put your reponses there as files and you are good to go. (Work with simple stuff but if headers etc is important not so good. Also not good at simulating failed calls.)
Finally if you are fine with not making the web call at all you can have mocks on the inside. If you use a dependency injection framework like Spring it is easy to run a version with mocked implementations of a backend call instead of the real one.


text:
Q: How to lookup data with a partial match on search key I have two spreadsheets.  The first has a column with employee job IDs with commas seperating them (e.x: 123DB, 345CX, 031DB).  The second spreadsheet has the job IDs and the description.  For instance, 123D is Financial Advisor, 345C is Manager, etc... It is not an exact match because some of the other numbers and letters represent skill and other things.
So basically, I want to search the second spreadsheet for the job ID and print the description in a new column on that first spreadsheet (but it's not an exact match; like 123BD=123XB=123AP).  I'm not sure if VLOOKUP is what I want. Please and thank you!
Also, there are tens of thousands of rows to brute force isn't possible.  I plan to get more descriptive as I go on so if 23D is finance, 23D04 is a financial regulator or something.

A: Yeah you can't comfortably deal with that many IDs in a single formula. Below is the formula for finding the Description for a single ID # in cell A2.
This formula assumes the description lookup range has been converted to a table that has been named "Jobs".
Also, this is an array formula that needs to be entered using CTRL+SHIFT+ENTER
=INDEX(Jobs[Description],MATCH(TRUE,ISNUMBER(SEARCH(Jobs[Job Code],A2)),0))
Considering it is searching for this in the middle of a string that seems to contain various other random numbers and letters, you may get some false matches. These are hard to avoid without there being a more fixed structure to the IDs.


text:
Q: php loop executing only once echo statement for img tag I was trying to print multiple images using img tag in HTML using PHP loops, but it was only printing it once.
here is what I tried :
  $rating = 5;
    for ($i = 1; $i <= 5; $i++) {
      echo($i);
      echo("

Output: image
If I remove the img tag it works as expected.

A: You don't have a closing angle bracket for the img tag.
This should work
  $rating = 5;
    for ($i = 1; $i <= 5; $i++) {
      echo($i);
      echo("");
    }
  ?>

A good way to troubleshoot something like this in the future is to view the source code of the browser page after it has loaded (Ctrl + U for Chrome on Windows)
That way you will see how the actual HTML code looks
It's also a good idea to add an alt tag, which is what would display if the image couldn't be loaded, or by a screen reader for someone with visual impairment.


text:
Q: Error Writing a Copy constructor in C++ I am trying to write a copy constructor for a class but I get these two error messages, which I cannot decipher. Can somebody please tell me what I am doing incorrect?
class Critter
    {

    public:
        Critter(){}
        explicit Critter(int hungerLevelParam):hungerLevel(hungerLevelParam){}
        int GetHungerLevel(){return hungerLevel;}

        // Copy Constructors
        explicit Critter(const Critter& rhs);
        const Critter& operator=(const Critter& rhs);

    private:
        int hungerLevel;
    };

Critter::Critter(const Critter& rhs)
    {
    *this = rhs;
    }

const Critter& Critter::operator=(const Critter& rhs)
    {
    if(this != &rhs)
        {
        this->hungerLevel = rhs.GetHungerLevel(); // ERROR: object has type qualifier not compatible with member function
        }
    return *this;
    }

int _tmain(int argc, _TCHAR* argv[])
    {
    Critter aCritter2(10);
    Critter aCritter3 = aCritter2; // ERROR : No suitable copy constructor
    Critter aCritter4(aCritter3);
    return 0;
    }

A: You need int GetHungerLevel() const {return hungerLevel;}
Otherwise, you aren't allowed to call GetHungerLevel() using the reference-to-const rhs.
Also, you can't do copy-initialization with an explicit copy constructor, only direct initialization: Critter aCritter3(aCritter2);
Probably you want to make the copy ctor non-explicit rather than necessarily change the definition of aCritter3, but your call.

A: 1) You declared your copy constructor explicit (do you need it to be explicit?), so the correct syntax is
Critter aCritter3 (aCritter2);

not
Critter aCritter3 = aCritter2;

2) Also, the proper signature for an assignment operator is:
Critter& operator=(const Critter& rhs);

3) The method GetHungerLevel should be const, but you don't need to use it - you can just write:
this->hungerLevel = rhs.hungerLevel;

A: add const qualifier to  GetHungerLevel()
  int GetHungerLevel() const {return hungerLevel;}


text:
Q: how to send http request to a server from the chaincode I am very new to the hyperledger fabric and even blockchains. I am wondering if i can send a http request from the chaincode. Basically before transaction i want to verify some data. Data server is located outside of the fabric network.
So basically scenario is that once a party started the transaction process,  chaincode first verify that the assets are delivered or not. Then engage in the transaction. Any kind of help is appreciated.

A: The chaincode itself should not send any network requests because it can lead to Non-deterministic response from chaincode. For example what if new block is generated with information that asset is "not delivered", but later, we will try to re-play this transaction to verify entire ledger's consistency and the answer will be "delivered" ?
The hash for this block will be different and entire chain will get into inconsistent state.
Fabric V1 proposes another approach:

Then, the peer forwards internally tran-proposal (and possibly tx) to the part of its (peer's) logic that endorses a transaction, referred to as endorsing logic. By default, endorsing logic at a peer accepts the tran-proposal and simply signs the tran-proposal. However, endorsing logic may interpret arbitrary functionality, to, e.g., interact with legacy systems with tran-proposal and tx as inputs to reach the decision whether to endorse a transaction or not.


text:
Q: Для чего options.php в form action? Когда нужно указывать в форме options.php ?
В каких случаях это нужно делать?
Допустим я создаю плагин с отдельной страницей настроек в меню "Инструменты".
Нужно ли в форме настроек указывать options.php ?
т.е. в атрибуте action.

A: Указывать нужно всегда, потому что именно файл options.php в составе ядра WordPress отвечает за обработку пользовательской формы настроек.
Хорошее руководство по созданию страниц настроек здесь.


text:
Q: Existence of certain coprime numbers Given $m\in\Bbb N$ large enough is there a coprime pair $a,b$ in $[2^{m-1},2^m]$ and $m_1,n_1, m_2,n_2\in[0,m^{c'}]\cap\Bbb Z$ with each of
$$m_1a-n_1b,m_2a-n_2b\in[0,m^c]\cap\Bbb Z$$
$$m_1n_2\neq n_1m_2$$
true at some $c,c'>0$ independent of $m$?

A: What you seem to request is that the matrix $M=\begin{pmatrix}m_1 & -n_1 \\
m_2 & -n_2\end{pmatrix}$ were non-degenerate, and the vector $d:=M\binom ab$
had its coordinates of size polynomial in $m$. If this could be arranged, as
a result we would get $\binom ab=\Delta^{-1}Ad$, where $\Delta:=\det M$ is a
non-zero integer, and $A$ is a matrix with integer entries; moreover, $\Delta$
and the entries of $A$ are of size polynomial in $m$. But this would imply
$\Delta\binom ab=Ad$, which is impossible as the entries of the vector in the
left-hand side are of size exponential in $m$, while the vector in the
right-hand side has entries of size polynomial in $m$.


text:
Q: Missing role permissions on the request even though it is added I am testing sending activity feed notifications to users.
I have configured my app in Azure AD app registrations to have delegated permission: TeamsActivity.Send
I first obtain auth token by calling:
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
with client_id, client_secret, scope = https://graph.microsoft.com/.default, and grant_type = client_credentials
I then call activity feed notification endpoint: https://graph.microsoft.com/v1.0/users/{userId}/teamwork/sendActivityNotification with the auth token as part of Authorization: Bearer {authToken} header.
However, I am getting the following error:
"Missing role permissions on the request. API requires one of 'TeamsActivity.Send'. Roles on the request ''."
May someone help with this? I am not sure why I am getting this error.

A: There are 2 different types of permissions

*

*Delegated (scope)

*Application (role)

Take a look at the TeamsActivity.Send permission from the MS Graph reference.

Permission
Type
Display String
Description

TeamsActivity.Send
Delegated
Send a teamwork activity as the user
Allows the app to create new notifications in users' teamwork activity feeds on behalf of the signed in user. These notifications may not be discoverable or be held or governed by compliance policies.

TeamsActivity.Send
Application
Send a teamwork activity to any user
Allows the app to create new notifications in users' teamwork activity feeds without a signed in user. These notifications may not be discoverable or be held or governed by compliance policies.

See the difference? Delegated permission requires a user to be logged into the application, and the application will send a message on behalf of the user (as the user). Application permission will send the message on behalf of the application (as itself).
You're using the client_credentials flow, which is a non-interactive flow. You can't use delegated permissions because there is no user signed-in.
You need to assign the same TeamsActivity.Send permission, but of the Application type instead, and grant admin consent for this permission as well.
Reference
Microsoft identity platform and the OAuth 2.0 client credentials flow - Application permissions
Introduction to permissions and consent - Types of permissions


text:
Q: How does this Op Amp affect voltage? I have a circuit as follows:

Note that \$V^+\$ is a voltage source that has both an AC and DC component. I want to see how the OpAmp affects both components. My guess is that we can write:
$$V_{out}(AC)=(1 + \frac{R2}{R1} - \frac{X_c}{\sqrt{X_c^2+ R_1^2}})V^+(AC) $$
Where I assumed the role of the RC part as a low pass filter as seen by \$V^+\$. Then, since low pass filters let all DC pass through unaffected, I would say that as long as C1 is not very large, $$V_{out}(DC)=(1 + \frac{R2}{R1})V^+(DC) $$
If I was told C1 is large enough to be considered as a short for AC and an open for DC, I would say $$V_{out}(AC)=(1 + \frac{R2}{R1})V^+(AC)$$ and $$V_{out}(DC)=V^+(DC)$$
Can someone tell me if this is correct or provide alternative explanations?

A: This diagram explains everything

At DC the capacitor reactance is very high (open circuit)\$X_C = \infty \$.
So, op-amp work as a voltage follower (gain one).
As the input signal frequency increases the capacitor reactance decreases.
And when \$X_C = (R_1 + R_2) \$ at \$F_1 = \frac{1}{2 \pi C_1 (R_1 + R2)}\$
The op-amp voltage gain start to increases and will reach \$ \large (1 +\frac{R_2}{R_1})\$ for signal frequency larger than :
\$\large F_2 = \frac{1}{2 \pi C_1 R_1}\$ When \$X_C < R_1\$

A: Yes, you have the basic concept right. The other interesting question is, what is the frequency at which the transition between the two regimes occurs?

Actually, your first equation isn't quite right. It should be
$$V_{out} = V_{in} (1 + \frac{Z2}{Z1})$$
where Z2 = R2, and Z1 = the series combination of R1and C1.
It becomes
$$V_{out} = V_{in} (1 + \frac{R2}{R1 - \frac{1}{j\omega C1}})$$
This reduces to your other equations in the limit cases.


text:
Q: best way to remove specific index from all arrays in a multidimentional array PHP hi i have multidimensional array in php i want to remove an index from every array , my array is like this
Array
(
    [0] => Array
        (
            [ProfilePrivacySettingDefaultID] => 1
            [UserType] => 2
            [Type] => 1
            [EntityID] => 0
            [PrivacySettingPublic] => 1
            [PrivacySettingElephantiUser] => 1
            [PrivacySettingFriend] => 1
            [IsValid] => 1
            [CreatedOn] => 1330580809
            [CreatedBy] => 0
            [UpdatedOn] => 0
            [UpdatedBy] => 0
        )

    [1] => Array
        (
            [ProfilePrivacySettingDefaultID] => 2
            [UserType] => 2
            [Type] => 1
            [EntityID] => 0
            [PrivacySettingPublic] => 1
            [PrivacySettingElephantiUser] => 1
            [PrivacySettingFriend] => 1
            [IsValid] => 1
            [CreatedOn] => 1330580809
            [CreatedBy] => 0
            [UpdatedOn] => 0
            [UpdatedBy] => 0
        )

    [2] => Array
        (
            [ProfilePrivacySettingDefaultID] => 3
            [UserType] => 2
            [Type] => 1
            [EntityID] => 0
            [PrivacySettingPublic] => 1
            [PrivacySettingElephantiUser] => 1
            [PrivacySettingFriend] => 1
            [IsValid] => 1
            [CreatedOn] => 1330580809
            [CreatedBy] => 0
            [UpdatedOn] => 0
            [UpdatedBy] => 0
        )

    [3] => Array
        (
            [ProfilePrivacySettingDefaultID] => 4
            [UserType] => 2
            [Type] => 1
            [EntityID] => 0
            [PrivacySettingPublic] => 1
            [PrivacySettingElephantiUser] => 1
            [PrivacySettingFriend] => 1
            [IsValid] => 1
            [CreatedOn] => 1330580809
            [CreatedBy] => 0
            [UpdatedOn] => 0
            [UpdatedBy] => 0
        )
    );

i want index ProfilePrivacySettingDefaultID from all arrays , so the final result will be like this
  Array
    (
        [0] => Array
            (
                [UserType] => 2
                [Type] => 1
                [EntityID] => 0
                [PrivacySettingPublic] => 1
                [PrivacySettingElephantiUser] => 1
                [PrivacySettingFriend] => 1
                [IsValid] => 1
                [CreatedOn] => 1330580809
                [CreatedBy] => 0
                [UpdatedOn] => 0
                [UpdatedBy] => 0
            )

        [1] => Array
            (
            [UserType] => 2
            [Type] => 1
            [EntityID] => 0
            [PrivacySettingPublic] => 1
            [PrivacySettingElephantiUser] => 1
            [PrivacySettingFriend] => 1
            [IsValid] => 1
            [CreatedOn] => 1330580809
            [CreatedBy] => 0
            [UpdatedOn] => 0
            [UpdatedBy] => 0
        )

    [2] => Array
        (
            [UserType] => 2
            [Type] => 1
            [EntityID] => 0
            [PrivacySettingPublic] => 1
            [PrivacySettingElephantiUser] => 1
            [PrivacySettingFriend] => 1
            [IsValid] => 1
            [CreatedOn] => 1330580809
            [CreatedBy] => 0
            [UpdatedOn] => 0
            [UpdatedBy] => 0
        )

    [3] => Array
        (
            [UserType] => 2
            [Type] => 1
            [EntityID] => 0
            [PrivacySettingPublic] => 1
            [PrivacySettingElephantiUser] => 1
            [PrivacySettingFriend] => 1
            [IsValid] => 1
            [CreatedOn] => 1330580809
            [CreatedBy] => 0
            [UpdatedOn] => 0
            [UpdatedBy] => 0
        )
    );

what is the best way to do this , thank you very much..............

A: You can easily use array_map to do this, with unset to remove the index. Example:
$your_array = array_map(
  function($array) {
     unset($array['ProfilePrivacySettingDefaultID']);
  },
  $your_array
);

A: I would say a foreach would be the most efficient way of doing this.
so either
foreach($user_array as $key => $value){
    unset($user_array[$key]['ProfilePrivacySettingDefaultID']);
}

or
foreach($user_array as &$value){
    unset($value['ProfilePrivacySettingDefaultID']);
}

array_map would just be doing a lot more work than is needed and using an anonymous function as your array_map callback is just counter productive.
$user_array = array_map(
    function($value){
        unset($value['ProfilePrivacySettingDefaultID']);
        return $value;
    }, $user_array
);

function array_map ( $callback , $array){

    foreach($array as $key => &$value){

        $value = call_user_func( $callback, $value );
        // which is equal to
        /*function my_callback($value){
            unset($value['ProfilePrivacySettingDefaultID']);
            return $value;
        }
        $value = my_callback();*/
    }
    return $array;
}

A: I would just iterate over the arrays and unset the specific value:
foreach($array AS $value){
    unset($value['ProfilePrivacySettingDefaultID']);
}


text:
Q: Firebase not taking same package name for Release build variant I have a Problem Regarding different Build Variant.
I have made 3 Build variant with Beta,Debug and Release. I have also integrated OTP using Firebase.
When i try to run the app with debug or beta, the otp comes. but when i switch to release mode, the otp doesn't come.
and i got to know this is happening because of SHA-1 not updated in firebase release package name but when i try to connect it with release build variant, it still taking debug package name.
I tried every other solution but nothing works for me.
check the package name even if i have set the build to release mode:

A: I got my own answer, as, debug app doesn't need any release key, but when i set my app to release, it generate a release mode, so, it need the original keyforandroid.jks, but i didn;t set the path for it. That's why the problem occurs.


text:
Q: Does direct GPIO communication between 2 microcontrollers requires pull up/down If I want to use GPIO pins of two microcontrolles as a mean of simple communication (e.g. reporting an event by sending 1 or 0), Do I need to enable internal pull up or pull down resistors on any of the MCUs?
I Want to put 2xSTM32 on the same board and need a way to signal the other chip that something has happened. I want to do this using a single GPIO pin on each device (hence no I2C/SPI/etc.)

Can you please tell me how what configuration should I do to the GPIO on each side? e.g.
SENDER:
GPIO Mode = output push-pull OR output open drain?
Pull Up/Down = Pull up or pull down or NONE?

RECEIVED:
GPIO Mode = input mode
Pull Up/Down = Pull up or pull down or NONE?

I mean what is the difference between push-pull and open drain and what will enabling pull up or pull down resistors do anyways?

A: The configuration I would use:
SENDER:
GPIO Mode = output push-pull
Pull Up/Down = no PU/PD

RECEIVER:
GPIO Mode = input mode
Pull Up/Down = opposite of logic high signal

And here is why:
The output as push-pull has generally the benefit, that it will drive the line in either way and ensure a good signal integrity. So even if your line gets a bit longer and the capacity might be a bit higher you usually don't suffer too much from it.
On the input side, you have to take into account (in my opinion) that you don't know if the sender will actually be there or if the line might be broken or not. So you should provide a way to ensure a stable logic level on that input even if the sender is absent or the line is broken. For that you use the pull up or pull down resistors. Depending on your physical layer specification (read: is your signal active low or active high) I would activate the pull resistor to the inactive signal level.
If your signal is active low, use a pull up, if it is active high, use a pull down.
To be more precise, the pull resistor should pull the signal to the safe state. Consider a write protect pin for example. Pull it in the direction that the write protection is enabled.
For this purpose the internal pull resistors are usually fine, just make sure to set them before you do any handling of the pin level.

An open drain output has only the ability to pull a line low, but it cannot drive the line high. This is commonly used on lines where multiple chips might want to signal something on the same line. Each chip can pull the line low, but no chip is driving it high, so no short circuit will happen.
Something has to drive the line high however and that is a pull up resistor. Pull up and Pull down are named like this because they will "pull" the voltage level of a line in the respective direction (high -> supply voltage, low -> ground, usually). The value of the resistor is chosen in such a way that no damaging current will flow in any device, no excessive current is flowing while the line is driven in the other direction and so that the line will return to the pulled level in the correct amount of time (depends on the capacity of the line).


text:
Q: Parse and Organize GovTrack API JSON data I have the JSON data from an API call to GovTrack (https://www.govtrack.us/api/v2/role?state=ne&current=true) in a JSONObject.
I'm having trouble navigating the JSON data and organizing it in a meaningful way.  My count is 2 (and I think it should be 5, as there are 5 actual "people" returned from the API call.  Plus the meta tag 'total_count' is 5 as well).  Also, I'm blowing up when trying to access "firstName" and "lastName".
Any help getting the correct data grouped and possibly organizing it into objects by person would be great.
My code:
    public void getRepJSONdata(){
    try{
        JSONArray allRepsResults = allRepData.getJSONArray("objects");
        for (int i = 0; i < allRepsResults.length(); i++) {
            JSONObject currentItem = allRepsResults.getJSONObject(i);
            String firstName = currentItem.getString("firstName");
            String lastName = currentItem.getString("lastName");

        }
    }catch (Exception ex){
        //trace out bad stuff
    }
}

A: Try the below code:
public void getRepJSONdata(){
        try{
            JSONArray allRepsResults = allRepData.getJSONArray("objects");
            for (int i = 0; i < allRepsResults.length(); i++) {
                JSONObject currentItem = allRepsResults.getJSONObject(i);
                JSONObject person = currentItem.getJSONObject("person");
                String firstName = person.getString("firstName");
                String lastName = person.getString("lastName");

            }
        }catch (Exception ex){
            //trace out bad stuff
        }
    }

A: What helps to sort out new JSON strings you don't really know is to use a JSON parser:

*

*http://json.parser.online.fr/

*http://jsonformatter.curiousconcept.com/
The correct answer was already posted by bhavesh N, but I thought this could be useful.


text:
Q: Keras - understand example I am currently trying to learn Deep Learning by focussing on Keras and the book "Deep Learning with Python-Keras"
I do have an example - I do understand the code but not the result - where I need your help. The example is about analyzing movie review from the imdB dataset which is included in Keras. The code goes as follows
def vectorize_sequences(sequences,dimension=10000):
    results=np.zeros((len(sequences),dimension))
    for i, sequence in enumerate(sequences):
        results[i,sequence]=1.
    return results

X_train=vectorize_sequences(train_data)
X_test=vectorize_sequences(test_data)
y_train=np.asarray(train_labels)
y_test=np.asarray(test_labels)

model=models.Sequential()
model.add(layers.Dense(16,activation="relu",input_shape=(10000,)))
model.add(layers.Dense(16,activation="relu"))
model.add(layers.Dense(1,activation="sigmoid"))
model.compile(optimizer="rmsprop",loss="binary_crossentropy",metrics=["accuracy"])

history=model.fit(X_train,y_train,epochs=4,batch_size=512)

In the explanation it is written, that "the final layer will use a sigmoid activation so as to output a probability indicating how likely the sample is to have the target "1""
I know that the sigmoid function ranges between [0,1]. Suppose the output of my network is 0.6
Why am I allowed to say that this value gives the probability to have the target "1" and not the target "0"?
I am kind of stucked and need some help :)

A: The interpretation of your output depends on the labels you used during your training. So train_labels and test_labels are concluded of 0s and 1s.
During training, the network is optimized to yield the correct label corresponding to an input sequence. So if your output is 0 or 1, the network is giving a confident classification. But, if your output is e.g. 0.5, the network is totally unsure to which class your input belongs.
Now we make the assumption that your input corresponds to class 1. In case of an output like 0.6, the class might be 1, but only with a confidence of 60 percent. It describes the probability to be class 1, since an output of 1 is a correct interpretation of the input to its label. If the output would be a 0, it would be the worst classification of the input since the label is 1. So this in the end corresponds to values ranging from 0 to 1, while the closer to 1 you are the better the classification - so it is a probability in the end.
But keep in mind that this definition only holds if you know that your input belongs to class 1. If it instead is part of class 0, the previous definition has to be turned around.
So in the end, you got two options. First, you can take these values as they are and treat them as a probability an input corresponds to one of the classes. Second, you can introduce a threshold - in this case it makes sense to set it to 0.5 - and say that if you are larger than the threshold, categorize your input to class 1, else to class 0. The closer your output is to 0.5 the more the network is just guessing the class in the end.
The choice of the threshold has a direct influence on the performance of your network in the end. This can be evaluated for example with a ROC curve (https://en.wikipedia.org/wiki/Receiver_operating_characteristic).


text:
Q: python super :TypeError: __init__() takes 2 positional arguments but 3 were given every one I am practicing Python, and I found something strange, here is my code

LogicG.py

class LogicGate:

    def __init__(self,n):
        self.label = n
        self.output = None

    def getLabel(self):
        return self.label

    def getOutput(self):
        self.output = self.performGateLogic()
        return self.output

class BinaryGate(LogicGate):

    def __init__(self,n):
        LogicGate.__init__(self,n)

        self.pinA = None
        self.pinB = None

    def getPinA(self):
        return int(input("Enter Pin A input for gate "+ self.getLabel()+"-->"))

    def getPinB(self):
        return int(input("Enter Pin B input for gate "+ self.getLabel()+"-->"))

class UnaryGate(LogicGate):

    def __init__(self,n):
        LogicGate.__init__(self,n)

        self.pin = None

    def getPin(self):
        return int(input("Enter Pin input for gate "+ self.getLabel()+"-->"))

class AndGate(BinaryGate):

    def __init__(self,n):
        super(AndGate,self).__init__(self,n)

    def performGateLogic(self):

        a = self.getPinA()
        b = self.getPinB()
        if a==1 and b==1:
            return 1
        else:
            return 0

however, it shows the error below, I use python 3.6.4

after I mark out the code "the super" it can work ok

super(AndGate,self).init(self,n)

class AndGate(BinaryGate):

    # def __init__(self,n):
    #     super(AndGate,self).__init__(self,n)

    def performGateLogic(self):

        a = self.getPinA()
        b = self.getPinB()
        if a==1 and b==1:
            return 1
        else:
            return 0

above those code just I copy from this site for python study, see that site in Listing 11, it shows these code work, but when I copy to my computer the code did not work?? I have to mark out "super" part?? why? thank you

A: When using super, self is passed automatically.
Also, in Python3.3 and above, super does not even need to receive arguments to know from which class it is being called. You can simply do this.
super().__init__(n)

This greatly improves maintainability, so it would be the prefered approach.

A: If you are using Python 3.3 and above, you should replace
LogicGate.__init__(self,n)

with
super().__init__(n)

It is better to use this format when ever you want to call super class constructor.

A: You don't need to pass self here:
super(AndGate,self).__init__(self,n)

It should be
super(AndGate,self).__init__(n)


text:
Q: How to make a Loadvars sendAndLoad request from embedded swf in flex I've developed a simple flex app with embedded swf. Basically swf use Loadvars to get data from particular database table. Ok, when I tested the flex app on localhost it is works fine and embedded swf make its sendAndLoad calls correctly.
But! When it is located on the web server swf not work correctly. I meant there is not returned values by sendAndLoad method.
Well, to make some points: questionContentLoadVars.img1 holds(return) the string from php call. This "img1" is an empty returned string only in Flex app placed in the web server otherwise it returns correct value from php call?
When gameplay22.swf is standallone works!
When gameplay22.swf is in HTML page works!
When gameplay22.swf is embedded in FLex and executed in LOCALHOST works!
But in the web server this embedded gameplay22.swf doesn`t works!
What is the problem with it?
//* here is flash(swf) part of gameplay22.swf file which is embedded in the Flex by SWFLOader(gameplay22.swf)

questionContentLoadVars = new LoadVars();
questionContentLoadVars.onLoad = function(success){
    if (success){
        slidingSvityk_mc.descripTA_mc.description_ta.text = questionContentLoadVars.theContent;
    }
    else
    {
        slidingSvityk_mc.description_ta.text = "err!";
    }
};

function loadQuestionData(sectionID){
    var tablename ='questionsgeo';  // database tablename
    //sending variables to the PHP script
    questionContentLoadVars.row = sectionID;
    questionContentLoadVars.tablename = tablename;
    questionContentLoadVars.id_ = "";
    questionContentLoadVars.img1 = "";
    questionContentLoadVars.sendAndLoad("getQuestionRec.php",questionContentLoadVars,"_POST");
};

function showLoadedGalleryImages():Void{
    infphp.text = questionContentLoadVars.img1;

    var img1Bulk:MovieClip = new MovieClip();

    img1Bulk = imgGalleryContainer_mc.img1Bulck_mc.createEmptyMovieClip(img1Bulk, _root.getNextHighestDepth());
    img1Bulk._x = 0;
    img1Bulk._y = 0;
    image_mcl.loadClip(questionContentLoadVars.img1, img1Bulk);
};

//* And here is Flex part of embedded SWFLOader(gameplay22.swf) component

<s:SWFLoader includeIn="user" width="1024" height="768" horizontalCenter="0" source="gameplay22.swf" verticalCenter="0"/>


text:
Q: TypeError: undefined is not an object (evaluating 'parentOutlet.peekState') I have a multi-page angular-nativescript application (with a sidedrawer and a page-router-outlet). When I first launch the application I can navigate between pages on the sidedrawer just fine, but after a few minutes (like 10), trying to navigate from one page to another crashes the app with this message:

JavaScript error:
  file:///app/tns_modules/nativescript-angular/zone-js/dist/zone-nativescript.js:826:78: JS ERROR Error: Uncaught (in promise): TypeError: undefined is not an object (evaluating 'parentOutlet.peekState')
  upsertModalOutlet@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:506:41
  file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:128:44
  forEach@[native code]
  pushStateInternal@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:111:54
  pushState@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:85:31
  pushState@file:///app/tns_modules/nativescript-angular/router/ns-platform-location.js:49:40
  pushState@file:///app/tns_modules/@angular/common/bundles/common.umd.js:511:45
  go@file:///app/tns_modules/@angular/common/bundles/common.umd.js:286:45
  setBrowserUrl@file:///app/tns_modules/@angular/router/bundles/router.umd.js:4007:33
  file:///app/tns_modules/@angular/router/bundles/router.umd.js:3960:40
  file:///app/tns_m<\M-b\M^@\M-&>
* JavaScript call stack:
  (
  0   UIApplicationMain@[native code]
  1   start@file:///app/tns_modules/tns-core-modules/application/application.js:272:26
  2   run@file:///app/tns_modules/tns-core-modules/application/application.js:300:10
  3   bootstrapNativeScriptApp@file:///app/tns_modules/nativescript-angular/platform-common.js:185:26
  4   bootstrapApp@file:///app/tns_modules/nativescript-angular/platform-common.js:103:38
  5   bootstrapModule@file:///app/tns_modules/nativescript-angular/platform-common.js:87:26
  6   anonymous@file:///app/main.js:7:57
  7   evaluate@[native code]
  8   moduleEvaluation@:1:11
  9   promiseReactionJob@:1:11
  )
  * Terminating app due to uncaught exception 'NativeScript encountered a fatal error: Error: Uncaught (in promise): TypeError: undefined is not an object (evaluating 'parentOutlet.peekState')
  upsertModalOutlet@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:506:41
  file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:128:44
  forEach@[native code]
  pushStateInternal@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:111:54
  pushState@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:85:31
  pushState@file:///app/tns_modules/nativescript-angular/router/ns-platform-location.js:49:40
  pushState@file:///app/tns_modules/@angular/common/bundles/common.umd.js:511:45
  go@file:///app/tns_modules/@angular/common/bundles/common.umd.js:286:45
  setBrowserUrl@file:///app/tns_modules/@angular/router/bundles/router.umd.js:4007:33
  file:///app/tns_modules/@angular/router/bundles/router.umd.js:3960:40

It's pretty reliably reproducible but I have to wait like 10 minutes each time

A: Seems like the problem was related to how I was handling the routing between angular versions. In angular 4 I was using the <router-outlet> and had tkMainContent in a <StackLayout> that was surrounding it. When I switched to using <page-router-outlet> in angular 6 I needed to move the tkMainContent to inside the <page-router-outlet>

A: I had the same error, and I found that it was caused because I used this in main.ts file:
platformNativeScriptDynamic({createFrameOnBootstrap: true}).bootstrapModule(AppModule);

Changing this to:
platformNativeScriptDynamic({createFrameOnBootstrap: false}).bootstrapModule(AppModule);

or
platformNativeScriptDynamic().bootstrapModule(AppModule);

solved the problem.
This error particularly appeared while trying to load a Modal that uses the root view to show the modal.
According to the NativeScript documentation, you should use createFrameOnBootstrap in cases where your application does not use page-router-outlet, as without it you will not get the default Page and Frame, which means you will not be able to inject them in your components or show the ActionBar.
My application had page-router-outlet, so setting createFrameOnBootstrap: false solved this issue.


text:
Q: How do I monitor progress in a TPL Dataflow mesh? I'm working on a C# app with a time-consuming sequential workflow that must be performed asynchronously.  It starts when the user presses a button and the app receives a few images captured from a camera within just a few milliseconds.  The work flow then.

*

*Saves the images to disk

*Aligns them.

*Generates 3d data from them.

*Groups them into a larger, collective object (called a "Scan").

*Add optional analysis data to this scan and executes it.

*Finally saves the scan itself is saved to an xml file alongside the images.

Some of these steps are optional and configurable.
Since the processing can take so long, there will often be a queue of "scans" awaiting processing  So I need to present to a user a visual representation of the queue of captured scans, their current processing state (e.g. "Saving", "Analyzing", "Finished" etc.)
I've looked into using TPL DataFlow for this.  But while the mesh is simple to create, I'm not getting just how I might monitor the status of what is going on so that I can update a user interface.   Do I try to link custom action blocks that post back messages to the UI for that?  Something else?
Is TPL Dataflow even the right tool for this job?

A: Reporting Overall Progress
When you consider that a TPL DataFlow graph has a beginning and end block and that you know how many items you posted into the graph, all you need do is track how many messages have reached the final block and compare it to the source count of messages that were posted into the head.  This will allow you to report progress.
Now this works trivially if the blocks are 1:1 - that is, for any message in there is a single message out.  If there is a one:many block, you will need to change your progress reporting accordingly.
Reporting Job Stage Progress
If you wish to present progress of a job as it travels throughout the graph, you will need to pass job details to each block, not just the data needed for the actual block.  A job is a single task that must span all the steps 1-6 listed in your question.
So for example step 2 may require image data in order to perform alignment but it does not care about filenames; how many steps there are in the job or anything else job related. There is insufficient detail to know state about the current job or makes it difficult to lookup the original job based on the block input alone.  You could refer to some external dictionary but graphs are best designed when they are isolated and deal only with data passed into each block.
So a simple example would be to change this minimal code from:
var alignmentBlock = new TransformBlock<Image, Image>(n => { ... });

...to:
var alignmentBlock = new TransformBlock<Job, Job>(x =>
{
     job.Stage = Stages.Aligning;

     // perform alignment here
     job.Aligned = ImageAligner.Align (x.Image, ...);

     // report progress

     job.Stage = Stages.AlignmentComplete;
});

...and repeat the process for the other blocks.
The stage property could fire a PropertyChanged notification or use any other form of notification pattern suitable for your UI.
Notes
Now you will notice that I introduce a Job class that is passed as the only argument to each block.  Job contains input data for the block as well as being a container for block output.
Now this will work, but the purist in me feels that it would be better to perhaps keep job metadata separate what is TPL block input and output otherwise there is potential state damage from multiple threads.
To get around this you may want to consider using Tuple<> and passing that into the block.
e.g.
var alignmentBlock = new TransformBlock<Tuple<Job, UnalignedImages>,
                                        Tuple<Job, AlignedImages>>(n => { ... });


text:
Q: Loading into Array causes Stack Smashing while having enough space? When executing the following code I get a Stack Smashing error.
const uint size = 62;

...
for (int i=0; i < 10; ++i){
    // mask = elements != zero
    // input = epi32 m512 data containing 1 byte values
    _mm512_mask_compress_epi32(input, mask, input);
    // get just elements != 0 as previous mask.
    __mmask16 mask1 = _mm512_cmpneq_epi32_mask(compressed, _mm512_setzero_epi32());
    // append the non-zero elements to the uchar*
    _mm512_mask_cvtusepi32_storeu_epi8((uchar*)str+pos, mask1, compressed); // uncommenting = no error, truncating mask = no error

     // add size of the inserted elements by counting 1's in mask
     pos += sizeOfInsertion;

     // print the position of the pointer AFTER storing
     void* pp = (void*) ((uchar*) str + pos);
     std::cout << pp << std::endl;
}

To investigate this issue, I was checking the position of the pointer while inserting the elements.
At beginning (pointing to str[0]) I have 0x7ffce3468d30, at the end 0x7ffce3468d69. Subtracting these addresses I get 3E = 62. So it should fit inside the declared array.
Shifting the mask by 1 (truncating one element), it doesn't throw an error.

A: The failure was in the compression. I didn't mind zeroing the values not matching the mask, so data wasn't stored contiguously and the stack was therefore overflowing.
In short:
_mm512_maskz_compress_epi32(mask, input);

made it work.


text:
Q: Squeryl JDK 1.8 We recently hit the same issue as discussed here - Squeryl fails to reflect in debug mode only
And it was also solved by changing to use JDK 1.7
As Java 7 support life-cycle has ended; we would like to move to Java 8.
Does squeryl support Java 8?
Is there a solution to the 'error while reflecting on metadata' issue?
Are there any other migration considerations?
Thanks,
Brent

A: Maybe there is same issue in salat, lift-json. see https://github.com/novus/salat/issues/133

A: I posted the same question on the squeryl group and got
Does squeryl support Java 8?
Yes; it should work on Java 8 <- mostly I was looking to confirm that in theory it should
Is there a solution to the 'error while reflecting on metadata' issue?
Kenji's link might be a lead to investigate this further; but till now I don't have an update
Are there any other migration considerations?
None were mentioned on the group


text:
Q: Is that true that $\|g\circ f\|\leq \|g\|\cdot\|f\|$? I have to construct an argument to my proof and I want to use a result that I don't know if it's true. The question is:
Let $f\in\mathcal{L}(E,F)$ and $g\in\mathcal{L}(F,G)$. Is that true that $\|g\circ f\|\leq \|g\|\cdot\|f\|$?
My attempt was:
As $g$ is continuous, then there is a $C>0$ such that $\|g(y)\|\leq C\|y\|$, for all $y\in F$.
So:
$$\|g(f(x))\|\leq C\|f(x)\|.$$
And we can see here that $\|g\circ f\|\leq C\|f\|$.
But how is going to appear $\|g\|$?
I think this is true, but i can't get there.
If it's true (as I imagine), so how can I visualize an example (non-trivial, ie, not the equality) that shows it happening? Like... $\|g\circ f\|<\|g\|\cdot \|f\|$?

A: Use the definition of norm operaror and how that translates to continuity (in the finite-dimensial case that happens always). Can you see why
$$ \|g(z)||\leq ||g||||z|| ?$$
Now choose $z$ wisely and use the same argument.

A: \begin{align} \|(gf)(x))\|=\|g(f(x)\|&\leq \|g\|\|f(x)\|\\&\le\|g\|\|f\|\|x\|\\&=(\|g\|\|f\|)\|x\|\end{align}
Now apply definition of norm of $\|gf\|$.


text:
Q: Which system calls can return EINTR or EAGAIN error codes? Which of the following system calls can return EINTR or EAGAIN/EWOULDBLOCK?
getsockname()
chdir()
bind()
fcntl()
listen()
setsid()
setsockopt()
socket()
stat()
unlink()
access()
accept()
open()
usleep()
dup2()
fork()
waitpid()
wait()
read()
write()

Some of these system calls return EINTR or EAGAIN on error (by the API of man pages).
Also some system calls exist that the API do not refer the EINTR/EAGAIN and however return these.
Please help.

A: I have found the answer. This question should not have been deleted. As a rule only syscalls which are "slow" return EINTR. Slow things are terminal I/O and things which wait (select, wait, sleep, pause, etc).


text:
Q: Django deployment on GoogleCloudPlatform I followed this tutorial and made sure I'm typing and doing everything perfectly. However I'm on GoogleCloudPlatform and I could see the application while I was running server with 0.0.0.0:8000 but I had to enable/create firewall to let me see it.
My http permissions on Google Cloud Platform is default.
The site just doesn't load and give Gateway Timeout after a while. But even though I run server with 0.0.0.0:8000 I can see the page. Is there any settings I need to enable on GoogleCloudPlatform?
I haven't followed the ufw firewall part in the video though so nothing related to firewall on the server itself.
while running manage.py check --deploy I'm getting these warnings
?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems.

?: (security.W006) Your SECURE_CONTENT_TYPE_NOSNIFF setting is not set to True, so your pages will not be served with an 'X-Content-Type-Options: nosniff' header. You should consider enabling this header to prevent the browser from identifying content types incorrectly.

?: (security.W007) Your SECURE_BROWSER_XSS_FILTER setting is not set to True, so your pages will not be served with an 'X-XSS-Protection: 1; mode=block' header. You should consider enabling this header to activate the browser's XSS filtering and help prevent XSS attacks.

?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your site should be available over both SSL and non-SSL connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS.

?: (security.W012) SESSION_COOKIE_SECURE is not set to True. Using a secure-only session cookie makes it more difficult for network traffic sniffers to hijack user sessions.

?: (security.W016) You have 'django.middleware.csrf.CsrfViewMiddleware' in your MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. Using a secure-only CSRF cookie makes it more difficult for network traffic sniffers to steal the CSRF token.

?: (security.W019) You have 'django.middleware.clickjacking.XFrameOptionsMiddleware' in your MIDDLEWARE, but X_FRAME_OPTIONS is not set to 'DENY'. The default is 'SAMEORIGIN', but unless there is a good reason for your site to serve other parts of itself in a frame, you should change it to 'DENY'.

This is the second time happening this even after starting all over again.

A: You are getting all these warnings with deployment as you are deploying for production mode.
Here is the deployment check follow it and all your warning will be gone.
You have to add the code below into settings.py
https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/


text:
Q: How to get label text from child of class inside of each loop? (jQuery) so I'm currently stuck on trying to get the label text of a couple of input fields

http://codepen.io/leongaban/pen/fJGie
^ in the codepen above I have created 2 phone input fields. However haven't been able to get the label text of each one. Originally I had the added_phone class on the input, but since moved that to the parent li.
I tried $(this.children) no error, but no output, tried var tag = $(this).children.label.text() but got an error

var elems = $('.added_phone');

elems.each( function(i) {
  console.log(i);

  var tag = $(this.children.label).text();
  var value = $(this).val();

  console.log('tag = '+tag);
  console.log('value = '+value);
});

Do you see what I'm doing wrong here?

A: $(this).children.label.text()

is invalid syntax for jQuery, you probably meant this:
$(this).children("label").text()


text:
Q: Raw IL in .NET Standard Project With the help of the IL Support VS extension, it was possible to write raw IL in a .csproj file targeting the .NET Framework.  This extension requires using the old .csproj format to properly allow the IL to "compile". Is it possible to write raw IL in a .NET Standard project using the new .csproj format? Or perhaps use the old .csproj format but still target .NET Standard?
EDIT: IL Support v2.4 (VS Extension) has been released with support for the new project format, including .NET Standard and .NET Core.


text:
Q: Correct binary-search algorithm Is it okay to write an implementation of the binary search in the following way?
    def binarySearching(sortedArr,v):
    if len(sortedArr)>=1:
        mid = len(sortedArr)//2
        if v<sortedArr[mid]:
            return binarySearching(sortedArr[:mid],v)
        elif v>sortedArr[mid]:
            return binarySearching(sortedArr[mid+1:],v)
        else:
            return mid
        return None

I don't understand why we need to specify low and high for the algorithm.
edit: Thanks to @Stef, this implementation isn't correct because mid is not of an original array, but of a subarray

A: You have to specify low and high  when you work with the only array/list. At every iteration you treat a part of list in low..high range.
Your implementation makes sublists, so it does not need explicit range definition (but is this sublist formation free of cost?)

A: When using the binary search algorithm you each step narrows down the search area by half.
You specify low and high as you pass the same array to search and change only the search area.
The alternative to passing low and high is to pass part of the array, yet in python that means that each time you slice the array (list) you create another object (which is the sliced list) - and that is memory inefficient.

A: Compare these two implementations of binarySearch. The first is yours, the second is mine.
In your version, you are passing "slices", ie, entire copies of subarrays, to the recursive call. In my version, all recursive calls access the same array without copying it, and instead only low and high are passed as parameters.
# using slices, ie, copies of subarrays
def binarySearching(sortedArr,v):
    # print(sortedArr)
    if len(sortedArr)>=1:
        mid = len(sortedArr)//2
        if v<sortedArr[mid]:
            return binarySearching(sortedArr[:mid],v)
        elif v>sortedArr[mid]:
            return binarySearching(sortedArr[mid+1:],v)
        else:
            return mid
    else:
        return None

# using low and high indices
def otherBinarySearching(sortedArr, v):
    def auxiliary(low, high, v):
        #print(low, high, sortedArr[low:high])
        if high > low:
            mid = (high + low) // 2
            if v < sortedArr[mid]:
                return auxiliary(low, mid, v)
            elif v > sortedArr[mid]:
                return auxiliary(mid+1, high, v)
            else:
                return mid
        elif high == low:
            return (low if v == sortedArr[low] else None)
    return auxiliary(0, len(sortedArr), v)

# add some tests to make sure implementations are correct
if __name__=='__main__':
    a = [x for x in range(0, 101, 2)]
    b = [x for x in range(1, 100, 2)]
    print('a: ', a)
    print('b: ', b)
    print('binarySearching:      ', all(isinstance(binarySearching(a, x), int) for x in a) and all(binarySearching(a, x) is None for x in b))
    print('otherBinarySearching: ', all(otherBinarySearching(a, x) == x / 2 for x in a) and all(otherBinarySearching(a, x) is None for x in b))

In addition, your version returns the wrong indices: the line return mid returns the index of v in the subarray binarySearching is currently looking at, instead of the index in the original array.


text:
Q: file cmdline does not show script name anymore We have 2 linux servers, one is SLES 11 SP3, and the other is SLES 12 SP2.
In Sles 11 sp3, when you start a batch script (name "test.sh"), which has $PID 2200, you can go to
/proc/2200/cmdline

and you will see something like
/bin/shtest.sh

So you can get the script name here.
In Sles 12 sp2 when you do exactly the same thing, you will see only
-bash

It was good for me to have the name in it, so I could get the name of the parent script (with $PPID).
But now the scipt file name is not there anymore.
Is there any alternative now to get the name of the parent script?
Thanks alot in advance.
Edit:
On the new server (12 sp 2), the only place in /proc/"id", where I found
the name was in "/proc/"id"/fd"
fstest:/proc/11248/fd # ls -l
total 0
lrwx------ 1 root root 64 Feb  9 15:52 0 -> /dev/pts/3
lrwx------ 1 root root 64 Feb  9 15:52 1 -> /dev/pts/3
lrwx------ 1 root root 64 Feb  9 15:52 2 -> /dev/pts/3
lr-x------ 1 root root 64 Feb  9 15:52 254 -> /batch/test1.sh
lrwx------ 1 root root 64 Feb  9 15:52 255 -> /dev/pts/3

But I don't know what I should make with it, what is "254"?
Thanks

A: I found the answer:
In "/proc/"id"/fd you have the file descriptors (see above).
0, 1, and 2 are always "in", "out" and "err" (don't not the order).
And it seems that 254 always links to the script.


text:
Q: Can I borrow parts of an apache-licensed project for something not open-source? If I want to make a card game app or android, could I legally borrow parts of the Apache-2.0-licensed Solitaire-for-Android? Would I be able to charge such a project? (I was unable to understand the legal jargon in the license here.)

A: It's actually a very simple license, worth reading with due respect. If you can ask the question in English, I'm very sure you can comprehend the license - just try once again, without distractions.
In short, you can (section 3) IF you follow the rules (section 4 through 9). If you don't follow, then you are in violation.
Disclaimer: I'm not a lawyer and in your shoes, I'd get a legal opinion instead of a random dude online.