How do loop through nested json object with javascript?

Question: Struggling with iterating through the following return json string from an API:
{
"data": [
{
  "ActionNeeded": null,
  "OldestStatus": null,
  "ServiceHost": "W501",
  "ServiceName": "Renewals",
  "ServiceStatusDateTime": "2023-03-15T22:47:05.313000",
  "ServiceVersion": "1.0.0",
  "SortOrder": "0",
  "TimeAgo": null
},
{
  "ActionNeeded": null,
  "OldestStatus": null,
  "ServiceHost": "W202",
  "ServiceName": "Monitor",
  "ServiceStatusDateTime": "2023-03-15T22:46:42.560000",
  "ServiceVersion": null,
  "SortOrder": "1",
  "TimeAgo": null
},
{
  "ActionNeeded": null,
  "OldestStatus": null,
  "ServiceHost": "W0070204",
  "ServiceName": "Monitor",
  "ServiceStatusDateTime": "2023-03-15T22:46:39.840000",
  "ServiceVersion": "2.0.2",
  "SortOrder": "1",
  "TimeAgo": null
}
]
]

I've tried a for..in loop, but am only managing to get the first "set" of key/value pairs.
Here is my current code:
var json_obj = JSON.parse(event.data);

// Returned records
const items = json_obj['data'];

for (var item_index in items) {
    if (items.hasOwnProperty(item_index)) {
        console.log(item_index);
    }
}

How can I loop through each "set" of data and out both key and value?
Comment: So you want to loop over all the objects in that array? Or do you want to go through all objects recursively?
Comment: Would like to loop through each index in that "data" object (each set of { }) and be able to reference each key/value set (at a time if possible). Like.. data[0] = {"ActionNeeded": null, "OldestStatus": null}, data[1] = etc
Answer: You can use Array#forEach or for...of to loop over an array and Object.entries to get all the key-value pairs in an object.

let o={data:[{ActionNeeded:null,OldestStatus:null,ServiceHost:"W501",ServiceName:"Renewals",ServiceStatusDateTime:"2023-03-15T22:47:05.313000",ServiceVersion:"1.0.0",SortOrder:"0",TimeAgo:null},{ActionNeeded:null,OldestStatus:null,ServiceHost:"W202",ServiceName:"Monitor",ServiceStatusDateTime:"2023-03-15T22:46:42.560000",ServiceVersion:null,SortOrder:"1",TimeAgo:null},{ActionNeeded:null,OldestStatus:null,ServiceHost:"W0070204",ServiceName:"Monitor",ServiceStatusDateTime:"2023-03-15T22:46:39.840000",ServiceVersion:"2.0.2",SortOrder:"1",TimeAgo:null}]};
o.data.forEach((x, i) => {
  for (const [k, v] of Object.entries(x))
    console.log('index', i, k, '=', v);
});
Comment: Let me try this out! I've been so used to jquery's .each stuff, that I'm struggling with vanilla methods for this.. embarrassing lol
Comment: So this works in a way. So it seems like it goes through every item, and for each item, outputs each key/value pair. Is there a way I can reference a key directly for each "item" instead of looping over every key? That way I can do something like: "for each item, if 'ActionNeeded' != '' then print the ServiceName"
Comment: @SourceMatters It depends. If you have a string, you need JSON.parse to parse it. If you already have an object, then you don't need to.
Answer: Here is good approach, hope this work for you!
const eventJsonString = JSON.stringify({
    "data": [
        {
            "ActionNeeded": null,
            "OldestStatus": null,
            "ServiceHost": "W501",
            "ServiceName": "Renewals",
            "ServiceStatusDateTime": "2023-03-15T22:47:05.313000",
            "ServiceVersion": "1.0.0",
            "SortOrder": "0",
            "TimeAgo": null
        },
        {
            "ActionNeeded": null,
            "OldestStatus": null,
            "ServiceHost": "W202",
            "ServiceName": "Monitor",
            "ServiceStatusDateTime": "2023-03-15T22:46:42.560000",
            "ServiceVersion": null,
            "SortOrder": "1",
            "TimeAgo": null
        },
        {
            "ActionNeeded": null,
            "OldestStatus": null,
            "ServiceHost": "W0070204",
            "ServiceName": "Monitor",
            "ServiceStatusDateTime": "2023-03-15T22:46:39.840000",
            "ServiceVersion": "2.0.2",
            "SortOrder": "1",
            "TimeAgo": null
        }
    ]
});

const event = JSON.parse(eventJsonString);
const items = event.data;

items.forEach(item => {
    const { ActionNeeded, OldestStatus, ServiceHost, ServiceName,
        ServiceStatusDateTime, ServiceVersion, SortOrder, TimeAgo } = item;

    console.log(ActionNeeded);
    console.log(OldestStatus);
    console.log(ServiceHost);
    console.log(ServiceName);
    console.log(ServiceStatusDateTime);
    console.log(ServiceVersion);
    console.log(SortOrder);
    console.log(TimeAgo);
    console.log("---------------");
});

Answer: In your code snipper items is an array, but you are using for...in which is meant for objects. You can change it to for...of and you won't need hasOwnProperty anymore since it's meant for keys in an object:
var json_obj = JSON.parse(event.data);

// Returned records
const items = json_obj['data'];

for (var item of items) {
    console.log(item);
}


Natural deduction $\{A \vee L, A \leftrightarrow N, L \rightarrow N\} \vdash N$

Question: Natural deduction $\{A \vee L, A \leftrightarrow N, L \rightarrow N\} \vdash N$
my work
1- $A \vee L$
2- $A \vee$ Elim FROM 1
3- $A \leftrightarrow N$
4- $A \leftrightarrow$ Elim FROM 3
5- $L \rightarrow N$
6- $L \rightarrow$ Elim FROM 5
is that correct or wrong, need guide please
Comment: $A\vee L\not\vdash A$ That is not how $\vee$ elimination works.
Answer: The disjunction elimination rule allows to eliminate a disjunctive statement by reasoning that if $A$ implies $C$ and $B$ implies $C$, then if $A$ or $B$ is asserted, we can conclude $C$ directly. Symbolically:
$$\frac{\begin{align}
A \rightarrow C, B \rightarrow C, A \lor B
\end{align}}{\begin{align} C \end{align}}$$
That is, whenever both disjunctors, separately, imply a certain sentence, we can just conclude it.
That being said, we can apply it in the following:

$A ↔ N$, Premise
$A \rightarrow N$, 1, $↔$E
$L \rightarrow N$, Premise
$A \lor L$, Premise
$N$, 2,3,4, $\lor$E

This shows that $A \lor L, A ↔ N, L → N ⊢ N$ (In fact, note that we don't even need $A ↔ N$, we only need one side of it, $A \rightarrow N$)
Answer: That's not how the elimination rules work.

Conjunction elimination ($\wedge$ elim.) is the rule: $$\;P\wedge Q\vdash P$$ However...
Disjunction elimination ($\vee$ elim.) is the rule: $$P\vee Q, P\to R, Q\to R\vdash R$$
Biconditional elimination ($\leftrightarrow$ elim.) is the rule: $$P\leftrightarrow Q \vdash P\to Q$$
Implication elimination ($\to$ elim.) , also known as Modus Ponens (MP), is the rule: $$P, P\to Q \vdash Q$$

Contrapositive elimination, also known as Modus Tollens (MT), the rule: $$\neg Q, P\to Q\vdash \neg P$$

tl;dr Just use Biconditional Elimination and follow with Disjunction Elimination
$$\frac{\begin{align}
A\leftrightarrow N      & \vdash A\to N
\\
A\vee L, A\to N, L\to N & \vdash N
\end{align}}{\begin{align}A\vee L, A\leftrightarrow N, L\to N & \vdash N\end{align}}$$


Login destination to file download - prompt user

Question: we have some private file links that are pasted into emails. When a user clicks the link, if they are not logged in they get something like this:
http://mysite.com/user/login?destination=/system/files/private/myfile.docx
Once they login and authenticate, the file starts to download in the user's browser.
I'd like to override the automatic download behavior and provide a "download this file?" type prompt first, since users don't often realize the file download starts automatically.
Any ideas? Thanks in advance.
Answer: Well, there are a few ways you could handle this. All of them are going to involve some code to handle these type of requests. One way I can think of would be to catch these requests on your custom 404 page and redirect the user to the login page with a new destination and keep the file name as a parameter. Then, on the new destination page grab the file download parameter and provide them a big fat button that links to that file.
If they are already logged in and you want to do the same thing you would need some sort of pre-processing filter to capture these and do the same as above.


Kotlin: What is the difference between = vs ==?

Question: I'm trying to set a certain value, monsterHealth, to display 0 instead of a negative number. If I'm trying to reassign the value to show 0 instead of, say, -2, would I want to use = or ==?
Comment: `=` is an assignment, `==` is a comparison for equality
Answer: Those are different operators:

= - assignment operator,
== and != - equality operators,
=== and !== - referential equality operators.

also

val - read only variable/property (it cannot be reassigned/changed),
var - mutable variable/property.

Kotlin Documentation - Keywords and operators
Comment: Thanks! I tried looking it up in the documentation, but I could never find out which was used for what.
Comment: The IDE will literally tell you if you use the wrong one!


Training with a class imbalanced dataset

Question: I have a dataset with 50 positive and 950 negative classes. I used Logistic regression with SMOTE and I got an AUC of 69% using 10 fold cross validation. How can I improve the performance?
Comment: Even after rectification of class imbalance and N-fold CV if the performance is unsatisfactory probably, the model has reached its limits of explanatory power. Maybe you could try different/additional predictors. Do remember the quote 'If you torture the data long enough, it will confess.', Ronald H. Coase
Comment: This is a pretty open-ended question. There is a helpful chapter in the book Applied Predictive Modeling by Kuhn and Johnson that also shows R code. If you have access to a research library that might help. The authors also have a discussion here: http://appliedpredictivemodeling.com/blog/2014/2/1/lw6har9oewknvus176q4o41alqw2ow.
Answer: If you aren't using a bias term, regularizing, and setting the regularization parameter using a validation set, you should do those things.  Beyond that you're entering the thicket of model selection and feature engineering.


Conditional posterior distribution of coefficient in logistic regression

Question: I would like to derive the conditional distribution of β in a logistic regression where

Y follows a Binomial distribution B(n,p)

the probability model is given as: logit(p)=X'β +u+v  ;

u is spatial random effects and v is non spatial random effects

β follows a priori a normal distribution

The posterior distribution is given as:

My question is,  what do I have to replace by

if I want to derive the conditional distribution of β  ?
Is it possible to get the mean and variance of  logit(p)=X' β +u+v so that I can transform it by normal distribution.
Comment: You should write the posterior $f(\beta,u,v,\kappa,\lambda|\mathbf y)$ in terms of the $\beta_j$'s as well, rather than writing $p_i$'s for the likelihood part.
Answer: The purpose of the question is unclear, as well as the background of the OP in terms of exposure to Bayesian statistics.
If considering the full posterior $f(\beta|\mathbf y,\mathbf u,\mathbf v)$, which is given by (up to a multiplicative constant)
$$\prod_{i=1}^n p_i(\beta,\mathbf u,\mathbf v)^{y_i}[1-p_i(\beta,\mathbf u,\mathbf v)]^{n_i-y_i}\varphi(\beta)$$
where $\varphi(\beta)$ denotes the multivariate Normal density. This means that the full posterior is the same as in the regular logistic regression when treating $\mathbf u,\mathbf v$ as constant. This is a standard model treated in Bayesian textbooks (as for instance in our Bayesian Essentials, Section 4.4, pp.124-6). This posterior is not a standard distribution and requires simulation tools to approximate it, incl. its posterior mean and posterior variance. (Once again, this is processed in textbooks like ours.) It is only asymptotically in $n$ that the posterior turns into a Normal distribution.
Comment: Thanks.  treating u,v as constant.


Selecionar linha da Kendo Grid quando clicar no hiperlink das colunas

Question: Estou com um problema na Grid da Kendo. O que ocorre é que eu tenho uma grid com várias colunas, dentre elas, tenho uma com a última posição enviada pelo rastreador. Essa coluna tem os dados em formato de hiperlink e quando clicado nele, abrirá uma nova tela mostrando a posição no mapa.
Até este ponto está pronto, mas quando eu clico no hiperlink e NÃO seleciono a linha da grid, simplesmente ele não pega a coordenada, pois ao clicar eu mando a latitude e a longitude da posição.
Em testes eu vi que seria necessário selecionar a grid no momento do click no link. Mas como faço isso?
Segue o código da montagem da grid:
$("#grdUltimasPosicoes").kendoGrid({
        columns: [
            {
                field: "Ignicao",
                title: "Ign.",
                template: "<input class='check_row' type='checkbox' #= Ignicao === true ? checked='checked' : ''  # disabled='disabled'/>",
                width: "70px"
            },
            {
                field: "Posicao",
                title: "Posiç&atildeo",
                width: "300px",
                template: "#=Posicao#",
                attributes: {style: "background-color: #= Cor #"}
            },
            {field: "DataEvento", title: "Data/Hora", format: "{0: dd/MM/yyyy HH:mm}", width: "135px"},
            {field: "DataGPS", title: "Data GPS", format: "{0: dd/MM/yyyy HH:mm}", width: "135px"},
            {field: "Rpm", title: "RPM", width: "80px"},
            {field: "Velocidade", title: "Vel.", width: "70px"},
            {field: "PotenGPS", title: "Nº GPS", width: "95px"},
            {field: "PotenGPRS", title: "Nº GPRS", width: "100px"}
        ],
        change: function (e) {
            if (this.select != null) {
                latlng = this.dataItem(this.select());
                Latitude = latlng.Latitude;
                Longitude = latlng.Longitude;
            }
        },
        groupable: false,
        sortable: true,
        editable: false,
        filterable: true,
        scrollable: true,
        pageable: false,
        selectable: "row",
        height: 250,
        dataSource: posicoes
    });

E esta é a função chamada para abrir a nova tela com o mapa:
function Maps() {
    acessaTela('HelpDesk', 'MapaPosicao', 'Novo', '1', 'Posiç&atildeo no Mapa', '495', '650', VeiculoSelecionado + '|' + Latitude + '|' + Longitude);
}

Answer: Na verdade não é correto usar o change nesse caso. O change é mais pra quando o usuário clica e seleciona a linha. Nesse caso, como o evento diz respeito à coluna em específico, não é certo usar a seleção da linha toda nele. Até vira uma questão de experiência de uso do usuário.
Eu prefiro registrar um evento depois de criada a grid, por fora mesmo:
$(grid.element).on("click", ".link", function() {
    var tr = $(this).closest("tr");
    var dataItem = grid.dataItem(tr);
});

Onde .link seria a classe do seu a no template:
template: "#=Posicao#",

Agora, o que acontece no evento é que o dataItem() também aceita um elemento tr da grid, onde ele pode acessar o uid da linha e achar o objeto no dataSource. Como o evento do clique está no a em si, usando o closest() ele encontra o tr respectivo.
Aqui uma demo.


Responsive Buttons

Question: I'm currently making a simple responsive template, but unfortunately when I "shrink" the page from inspect the buttons don't go with the flow.
Here's my code:

.w3container {
  max-width: 100%;
  position: relative;
  left: 750px;
  font-size: 22px;
  color: white;
  font-family: 'Comfortaa', cursive;
  margin: 0;
}

  <button class="btn1">btn1</button>
  <button class="btn2">btn2</button>
  <button class="btn3">btn3</button>

Comment: what is it you're trying to do?
Comment: tryna make my webpage responsive, so when you click "inspect" on your web browser, there's a "phone screen" button, so you'd see how does your web page looks on a smartphone. when i do that my buttons just don't move (shrink),they stay "behind" the screen.
Answer: button {
    display: inline-block;
    box-sizing: border-box;
    max-width: 100%;
}

Or if you want the buttons full width
button {
    display: block;
    box-sizing: border-box;
    max-width: 100%;
}

Comment: didn't seem work, i actually added {float:right;}   , it surprisingly shrinks, but as i shrink the page, buttons disappear one-by-one. seems like they're hiding behind some elements
Comment: Remove the position relative and left from the container, that's probably forcing them off the page when your screen is less than 750 pixels in width

Responsive Buttons


Prove fact about polynomial with coefficients from $\mathbb{Z}$

Question: Let $f \in \mathbb{Z}[x]$.
And for more than 3 (i.e $\geqslant 4$) distinct $a \in \mathbb{Z}\ f(a) = 1$.
Prove that $\forall a \in \mathbb{Z} \ f(a)\neq -1$.
I have clearly no idea how to tackle this.
The only thing I've noticed (I'm pretty sure it is an obvious fact for the most of you) is that since polynomial is continuous function we have to prove that $f(a) > -1\  \forall a \in \mathbb{Z}$.
Comment: Your statement $f(a) > -1\  \forall a \in \mathbb{Z}$ would't be true.  Pick something like $f(x) = (x-1)(x-6)(x-11)(x-16)+1$, then $f(2)=-503$
Comment: Supose $f$ is a polynomial with coefficients in $\mathbb{Z}$ such that $f(a_1) = f(a_2) = f(a_3) = f(a_4) = 1$ where $a_1 < \dots < a_4 \in \mathbb{Z}$. Assume that $f(c) = -1$. Set $g(x) = f(x + a_4) + 1$, then $g(b_i) = 0$ for
Comment: @HansEngler What was that...?
Comment: @DonAntonio - I edited my answer. Please check again.
Answer: Supose $f$ is a polynomial with coefficients in $\mathbb{Z}$ such that $f(a_1) = f(a_2) = f(a_3) = f(a_4) = 1$  where $a_1 < \dots < a_4 \in \mathbb{Z}$. Assume that $f(c) = -1$ for some integer $c$.
Set $g(x) = f(x) - 1$, then $g(a_i) = 0$, and also $g(c) = -2$.
Consequently we may factor $g(x) = (x-a_1)(x-a_2)(x-a_3)(x-a_4)h(x)$ where $h$ is another polynomial. Now $h$  has integer coefficients as well, since it is obtained by repeated applications of the Euclidean Algorithm. Substitute $x = c$ to obtain
$$
-2 = (c-a_1)(c-a_2)(c-a_3)(c-a_4)h(c)
$$
and all factors are integers. The first four factors are all different. That is impossible since their product would be at least 4 in absolute value.
Note that $f(x) = x^3 - 7x^2 + 14x - 7$ indeed satisfies $f(1) = f(2) = f(4) = 1$ and $f(3) = -1$. So there have to be at least four $a_i$ with $f(a_i) = 1$.
Answer: Let
$$
f(x)=(x-1)(x-3)(x-5)(x-7)+1.
$$
Then $f(a)=1$ for $a=1,3,5,7$. Nevertheless we have $f(6)=-14<-1$.
As for the first claim, compare with this question, for an idea how to tackle this.


Can F# present in the key of Db?

Question: I'm coding an algorithm for transpose chords, but I only have little knowledge of the Music theory.
Is it wrong F# include in key of Db instead of Gb? If the key with a flat all the enharmonic chords must replace with their flat notes?
Key C
G   A    B    C   D    E   F
when transpose to Key Db
Ab   Bb    C    Db   Eb    F   Gb
or Is this also correct according to music theory?
Ab   Bb    C    C#   Eb    F   F#
Comment: Seriously, if what you're doing needs answers to questions like this, you're going to be well out of your depth very soon.
Answer:
Is it wrong F# include in key of Db instead of Gb?

Usually, yes.  The fourth degree of the D♭ scale is G♭, and it is incorrect to spell it as F♯.
However, F♯ is the raised third degree of the D♭ scale, and if your source is very chromatic, it might legitimately use the raised third degree, in which case the correct result in D♭ would be F♯.  This is unlikely, but possible.  To be clear, the source pitch would have to be one of the following:

Key
Pitch

C
E♯

D
F♯♯

E♭
G♯

E
G♯♯

F
A♯

F♯
A♯♯

G♭
B

G
B♯

A♭
C♯

A
C♯♯

B♭
D♯

B
D♯♯

As you might guess by the number of keys in which this pitch is something-double-sharp, it is not common.
There is a simple rule for this.  When you transpose, two things must change identically for every note: the distance in letters and the distance in half steps.  If you go from C to D, all the letters must increase by one (for G, this means changing to A) and all the pitches must move by two half steps.  If you go from C to D♭, the letters are still increasing by one, but the pitches are increasing by only one half step.
Unfortunately, a lot of music notation software gets this wrong, or perhaps the people using it get it wrong.  Regardless, you can find a lot of horribly misspelled scores out there on the internet.  I was looking for a particularly chromatic passage from Mozart's Requiem a few weeks ago, and the first score of it that I found on YouTube was self-engraved by someone who didn't know what they were doing, and it was a disaster.
So make sure you're using reputable sources for your transpositions, and stick to the "letter first, then half steps" rule, and you should be fine.
Comment: @Nishantha if you change from C sharp to D flat you are changing the letter and moving zero half steps.  So all the letters have to change and the accidentals then must be adjusted accordingly.  The third, E sharp, becomes F.  The fifth, G sharp, becomes A flat.  And so on.
Comment: This means when changing C# to Db no change to letters and only change enharmonics? Am I correct?
Answer: Short answer: for a lot more than convenience's sake, each key will consist of each one of 7 letter-named notes, those being A-G. One main reason is to avoid having a ♯ and/or ♭ next to another same letter name, and thus having to write them on the same line/space. That would mean one or more letter names would not feature as well.
Generally, keys will have only sharps or only flats affecting notes - in major keys. This is reflected in their key signatures, which are there to tell which notes will not be naturals. That falls apart somewhat when minor keys are met: the leading note will mean in some keys with a flat in the key sig. will often have a sharpened note for that note. It doesn't mean the key sig. gets a sharp and a flat, but the notes involved in their scales will have flats and sharps, e.g. D (harmonic) minor - D E F G A B♭ C♯ D.
Whilst in 12tet, you idea of the G♭ sounding exactly like F♯, doing that will produce two notes with the 'G' name - not good, and where's F? Also two C names but lacking a D in your last version will also be confusing.
Best stick to sharps only when needed, and flats only when needed. So, we could (and do!) have a key of C♯ written differently from the key of D♭.But both sounding the same in 12tet.
Comment: "Generally, keys will have only sharps or only flats affecting notes - in major keys": it's true, but it's a fairly weak generalization.  If the music is more than a little bit chromatic, you can easily find sharps in a flat-side major key.  Trivially, they would be expected if the relative minor is tonicized at all, but there are other possibilities as well.

Can F# present in the key of Db?


How to override Drupal behaviors?

Question: I want to override the drupal core behavior Drupal.behaviors.filePreviewLinks which is located at core\modules\file\file.js from my custom module
I tried placing the following code in js file of my custom module
Drupal.behaviors.filePreviewLinks = {
    attach: function (context, settings) {
        console.log($(context).find('div.js-form-managed-file .file a'));
        //some custom code
    },
    detach: function (context, settings){
       //some custom code
    }
};

But it is not working. What I need to do? How to override Drupal core behavior in custom module?
EDIT
Let me explain my actual question. I am loading a form in page that is created using ECK entity type module. One of a field in form has 'file' as field type. So once I upload a file, it is showing filename with link in a table(I hope it is default drupal feature). I want to remove the file link and show only file name.
Comment: Not enough info here. Are you attaching this file to the page?
Comment: `delete Drupal.behaviors.filePreviewLinks.attach; Drupal.behaviors.filePreviewLinks.detach;` in your own library loaded afterwards.
Answer: Use libraries-override in your theme's info.yml file
Step 1: Find the library name in core that the JS or CSS file to override belongs to.
For example, it is clear that core\modules\file\file.js  belongs to the file module. Review at core/modules/file/file.libraries.yml to find the library name .  In the yaml file, the library name is the top-level item in the yaml structure where file.js is defined.  In this case drupal.file.
#core/modules/file/file.libraries.yml
drupal.file:
  version: VERSION
  js:
    file.js: {}  #### Drupal 8+ defines the js/css to override in libraries.yml
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

Step 2: Find the fully-qualified library name.
The fully-qualified library name is generally prefixed by the module name, in the format <modulename>/<libraryname>. However, some core system libraries don't follow this format, so if unsure of the fully qualified library name, search for instances of the <libraryname> in the core codebase, which may turn up a string with the fully-qualified library name like drupal/<libraryname>.
In this case the fully qualified name is file/drupal.file.
Step 3: Override the file in your theme
In your custom theme's info.yml file add the following lines:
libraries-override:
  file/drupal.file:
    js:
      file.js: js/file.js

If you want to override a core or contrib CSS file, the syntax is similar:
libraries-override:
  filter/caption:
    css:
      theme: # <-- this line must match the definition in libraries.yml
        css/filter.caption.css: css/components/captions.css
#        ^                       ^
#        |                       |
#      File path as defined     File path relative to your
#      in *.libraries.yml       theme's folder.

Step 4: Copy the file into your theme, and modify it to your needs
For the 2 examples given above, you'd place the files.js inside a folder js in your theme, and you'd rename filter.caption.css to captions.css and place it inside the css/components folder of your theme.
Step 5: Clear caches and reload the page.
Use your Web browser's resource inspector to verify the path to the overridden file is coming from your theme folder.
Answer: Since Drupal behaviors are really just javascript objects, all you need to do is to ensure that the behavior you're overwriting is loaded before your replacement. So:
my_module.libraries.yml
some_new_lib:
  js:
    my-js-file.js: {}
  dependencies:
    - libary_with/behavior_you_want_to_override
    - core/jquery   # anything else you need

my-js.file
(function ($) {

  Drupal.behaviors.nameOfBehaviorYouWantToOverride = {
    // Your little dash of magic
  }

})(jQuery);

Answer: I do something similar in the Node Revision Delete module to override the drupal.content_types library doing this:
In the *.libraries.yml file define your library:
content_types:
  version: 1.0.0
  js:
    js/content_types.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupal.form

Attack your library where you need it:
  // Element to track the content type.
  $form['workflow']['section']['node_revision_delete_track'] = [
    '#type' => 'checkbox',
    '#title' => t('Limit the amount of revisions for this content type'),
    '#default_value' => $track,
    '#attached' => [
      'library' => [
        'node_revision_delete/content_types',
        'node_revision_delete/admin_settings',
      ],
    ],
  ];

And remove the core library:
/**
 * Implements hook_library_info_alter().
 */
function node_revision_delete_library_info_alter(&$libraries, $extension) {
    unset($libraries['drupal.content_types']);
}

Comment: This helps to override entire library file. It is working fine and I up-voted for this. Thanks. But, is it possible to override only particular behavior instead of entire library?
Comment: @siddiq I don't know (is the first time that I see a problem like this), but you can duplicate the file and rewrite the function that you need to change.

How to override Drupal behaviors?


Python returning two identical matrices

Question: I am trying to write a small program for Markov Decision Process (inventory problem) using Python. I cannot figure out why the program outputs two identical matrices (for profit and decision matrices). The programming itself has some problems too because the last two columns are all zeros, which should not happen. Any help on the program itself would also be super helpful!
import math
import numpy as np

def salvageCost(b):
    return 5 * b

def orderingCost(b):
    if b == 0:
        return 0
    else:
        return 4 + 2 * b

def holdingCost(b):
    return 1.5 * b

def revenue(b):
    return 8 * b

M = 10
N = 4
u = np.zeros((M+1,N))
T = np.array([4,3,2,1])
S = np.array(range(M+1))
A = np.array(range(M+1))
u[:,0] = S*5
d = np.zeros((11,4))

probs = np.array([0.05, 0.1, 0.15, 0.2, 0.2, 0.15, 0.1, 0.05, 0, 0, 0])
demands = np.array(range(11))
candidate = [0]*11
d = u

for i in T[1:N]:
    for j in S:
        for a in range(M-j+1):
            candidate[a] = -holdingCost(j) - orderingCost(a) \
            + np.array([probs[k]for k in range(j+a)]).dot(8*np.array([demands[k]for k in range(j+a)])) \
            + np.array([probs[p] for p in range(min(j+a+1,M+1),M+1)]).dot(np.array(range(min(j+a+1,M+1),M+1)))*80\
            + probs.dot(u[:,i-1])
        u[j,i] = max(candidate)
        d[j,i] = candidate.index(max(candidate))

print(d)
print(u)

This is the output
[[ 0.  0.  0.  0.]
 [ 5.  0.  0.  0.]
 [10.  0.  0.  0.]
 [15.  0.  0.  0.]
 [20.  0.  0.  0.]
 [25.  0.  0.  0.]
 [30.  0.  0.  0.]
 [35.  0.  0.  0.]
 [40.  0.  0.  0.]
 [45.  0.  0.  0.]
 [50.  0.  0.  0.]]
[[ 0.  0.  0.  0.]
 [ 5.  0.  0.  0.]
 [10.  0.  0.  0.]
 [15.  0.  0.  0.]
 [20.  0.  0.  0.]
 [25.  0.  0.  0.]
 [30.  0.  0.  0.]
 [35.  0.  0.  0.]
 [40.  0.  0.  0.]
 [45.  0.  0.  0.]
 [50.  0.  0.  0.]]

Comment: Basic Python, with `d = u`, `d` references the **same** object as `u`.  No copying is involved.
Answer: Because numpy.ndarrays are mutable, when you write
d = u

d and u point to the same matrix, so any change to d or to u affects both:
>>> import numpy as np
>>> x = np.array([1, 2])
>>> y = x
>>> y[0] = 10
>>> x
array([10,  2])

Answer: This line:
d = u

points d and u to the same location in memory. As a result, any changes to d are reflected in u, and vice versa.
You are probably looking to create a copy of the contents of u, in which case you can use d = u.copy().

Python returning two identical matrices


Let a,b,c be digits such that the six digit number abcabc has 4 prime factors and only one prime factor out of the four has a power of 3, find numbers

Question:
Let a,b,c be digits such that the six digit number $abcabc$ has 4 prime factors and only one prime factor out of the four has a power of 3 (say $\mathrm{k}^3$ ). If there are $\mathrm{n}$ such numbers find $n$.

$abcabc$ can be re-written as $7 \times 11 \times 13 \times(100a+10b+c)$. Hence $3$ of those primes are $7,11,13$ and so the prime with power of $3$ has to be $100a+10b+c$. Let it be equal to $k^{3}$, then $100 \leq k^{3} \leq 999$. Hence $k=5,6,7,8,9$ and from there we get $5$ cases for $a,b,c$. But the answer key says there are $23$ such numbers. What did I get wrong /missed?
Comment: @JohnOmielan Hello! But how can they 2 more factors of $7,11,13$ if it's said that only one of the four primes factors have a power of 3?
Answer: Well, but what about $3$-digit [or fewer] numbers $x$ of the form $x=7^e11^f13^g3^h$; $e,f,g,h$ nonnegative integers; furthermore $h \ge 1$? [Keep in mind no one said $a>0$ or $b>0$ here.]
Comment: Which 3 digit number are you considering (what is the role of $x$)? Also why is there a $3^{h}$? Where are you getting $3$ as a prime factor?
Comment: As you wrote the problem: Let $y$ be the integer. Then $y$ can be written $y=1001x$. The $4$ factors of the integer $y=1001x$; $1 \le x \le 999$, are $7,11,13$, and $3$. So $x$ is precisely any integer in $[1,999]$ that is divisible by $3$ and whose other prime factors, if any, are in the set $\{7,11,13\}$
Comment: I guess you're letting $abc=x$ but then $100 \leq x \leq 999$ and not $1$ if I'm not wrong. And I still don't get why $3$ has to be a prime factor of $y$? It is said on the problem that only one prime factor has a power of 3 and that prime factor is not necessarily 3 by itself right?


Question about standardizing in ridge regression

Question: Hey guys I found one or two papers which use ridge regression (for basketball data). I was always told to standardize my variables if I ran a ridge regression, but I was simply told to do this because ridge was scale variant (ridge regression wasn't really part of our course, so our lecturer skimmed through it).
These papers I read didn't standardize their variables, which I found a bit surprising. They also ended up with large values of lambda (around the 2000-4000 level) via cross-validation, and I was told that this is due to not standardizing the variables.
How exactly does leaving the variable(s) unstandardised lead to high lambda values and also, what are the consequences of not standardizing the variables in general? Is it really such a big deal?
Any help is much appreciated.
Answer: Ridge regression regularize the linear regression by imposing a penalty on the size of coefficients. Thus the coefficients are shrunk toward zero and toward each other. But when this happens and if the independent variables does not have the same scale, the shrinking is not fair. Two independent variables with different scales will have different contributions to the penalized terms, because the penalized term is a sum of squares of all the coefficients. To avoid such kind of problems, very often, the independent variables are centered and scaled in order to have variance 1.
[Later edit to answer to comment]
Suppose now that you have an independent variable $height$. Now, human height might be measured in inches or meters or kilometers. If measured in kilometers, than in standard linear regression I think it will give a much bigger coefficient term, than if measured in millimeters.
The penalization term with lambda is the same as expressing the square loss function with respect to the sum of squared coefficients less than or equal a given constant. That means, bigger lambda gives much space to the squared sum of coefficients, and lower lambda a smaller space. Bigger or smaller space means bigger or smaller absolute values of the coefficients.
By not using standardization, then to fit the model might require big absolute values of the coefficients. Of course, we might have a big coefficient value naturally, due to the role of the variable in the model. What I state is that this value might have an artificially inflated value due to not scaling. So, scaling also decreases the need for a big values of coefficients. Thus, the optimal value of lambda would be usually smaller, which corresponds to a smaller sum of squared values of coefficients.
Comment: Thanks. How would not standardizing lead to a higher estimated test-error (via cross validation), and thus a higher lambda needed, though?
Comment: I appended my thought in the answer
Comment: I know that this is an old Question, but could you explain maybe why the Tuning Parameter should getting bigger, if we transform our data from kilometers to meters for example
Comment: I guess as you go from Km to meters the values will become big as its x1000, hence coefficient will become smaller in the model and which in turn will make the penalty term very small, so to have an optimal significance of penalty term, the tunning parameter will have to be increased.
Answer: Though four years late, hope someone will benefit from this.... The way I understood it, coeff is how much target variable changes for a unit change in independent variable (dy / dx). Let us assume we are studying relation between weight and height and weight is measured in Kg. When we use Kilometers for height, you can imagine most of the data points (for human height) packed closely. Thus, for a small fractional change in height there will be huge change in weight (assuming weight increase with height). The ratio dy /dx will be huge.
On the other hand, if height is measured in millimeters, data will be spread far and wide on the height attributes. A unit change in height will have no significant change in weight dy /dx will be very small almost close to 0. Lambda will have to be higher when height is in Km compared to lambda when height is in millimeters


A $2$-variable non-differentiable function whose partial derivatives exist

Question: If a $2$-variable function is not differentiable at some single point, but has finite partial derivatives for both variables at that point, can it also have a derivative in any direction, I mean is it valid to say that $dF/dl = \text{grad}F\cdot(l_1\cdot i + l_2\cdot j)$?
For example $f(x,y) = (x^3 - xy^2)/(x^2 + y^2)$ and $f(0,0) = 0$,
We need to determine the set of points $(x,y)$ from $R^2$ such that the function  has a derivative in every direction at any point.
Answer: Your $f$ has directional derivatives everywhere on $\mathbb {R}^2.$ The only problem point is $(0,0).$ Check that $\partial f/\partial x (0,0) = 1, \partial f/\partial y (0,0)=0.$ Look along the lines $y = mx$ and see what happens in other directions. One interesting thing is that $f(x,x)\equiv 0.$ Thus the directional derivative in the direction $(1/\sqrt 2,1/\sqrt 2)$ is $0.$ However, $\nabla f (0,0) \cdot (1/\sqrt 2,1/\sqrt 2)  =1/\sqrt 2.$
Comment: Yes but the problem is in our book it says if the function is differentiable then it is valid to say that $gradf \mathbin{\cdot} e$ is a directional derivative.
Since it's not differentiable i try to do it by definition putting $X(0+ra,0+rb)$ and letting $r \to 0$ i get $$\frac{df(x)}{de} = \lim_{X\to A} \frac{f(X) - f(A)}{\rho(X,A)} = 0$$ so the directional derivative is $0$ in every direction, and therefore it exists even though the $gradf \cdot e$ is different (but I did say it could not be valid, since the function is not differentiable)
Comment: So what I'm really asking is If a function is not differentiable is there any other way to determine if it has directional derivatives in every point or do I have to do it by definition?
Comment: The directional derivative at $(0,0)$ is not equal to $0$ in every direction. Far from it; it is only equal to $0$ along $3$ different lines through the origin.


Composer keeps reinstalling the same core version

Question: I manually updated a Drupal 9 installation to 9.1.2. I need to install the  Real AES module, which depends on the Defuse PHP-Encryption library.
I attempted to install it using Composer, but it tries to update Drupal to 9.1.2 again, which breaks it, and I have to restore from a backup.
Any help would be greatly appreciated!
Running composer --no-plugins --no-scripts require defuse/php-encryption causes the following error.

PHP Warning:  Module 'pdo_mysql' already loaded in Unknown on line 0
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Continue as root/super user [yes]?
Using version ^2.2 for defuse/php-encryption
./composer.json has been updated
Running composer update defuse/php-encryption
Loading composer repositories with package information
Updating dependencies
Lock file operations: 2 installs, 0 updates, 0 removals

Locking defuse/php-encryption (v2.2.1)
Locking paragonie/random_compat (v9.99.100)

Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 3 installs, 0 updates, 0 removals

Installing paragonie/random_compat (v9.99.100): Extracting archive
Installing defuse/php-encryption (v2.2.1): Extracting archive
Installing drupal/core (9.1.2): Extracting archive

1 package suggestions were added by new dependencies, use composer suggest to see details.
Package doctrine/reflection is abandoned, you should avoid using it. Use roave/better-reflection instead.
Generating autoload files
Comment: This is failing because you're running composer with the `--no-plugins` option. That flag is breaking this. It is put quite clearly in your linked issue on github. Don't run the command with that flag. You say you're using these flags because composer says to use them if you run as root, so don't run as root.
Comment: What do you mean by "I manually updated my Drupal9 install to v9.1.2"?
Comment: And what do you mean by "my Drupal is broken"? What error messages do you see?
Comment: I will run it now and share the webpage the appears. Also, someone wrote back to me on Github and explained why this is happening.  (See link at top of the post)
Comment: An error occurred.

Sorry, the page you are looking for is currently unavailable.
Please try again later.

If you are the system administrator of this resource then you should check the error log for details.

Faithfully yours, nginx.
Comment: @bforest please check drupal logs to get more technical error message
Comment: Why are you using `--no-plugins` and `--no-scripts`? The person replying on github says this is happening because you're using `--no-plugins`
Comment: Composer says use "--no-plugins and --no-scripts" if running as root.  Also, the person gave 2 reasons for the issue.  The first being something about the wrong drupal/core directory.

- - - - - - ->8 - ACCESS.LOG
xx.xx.xx.xx - - [11/Jan/2021:20:33:54 -0500] "GET / HTTP/1.1" 302 326 "-" "Mozilla/5.0 (Macintosh; Intel Mac  OS X 10.12; rv:56.0) Gecko/20100101 Firefox/56.0"
xx.xx.xx.xx - - [11/Jan/2021:20:33:55 -0500] "GET /core/install.php HTTP/1.1" 500 494 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:56.0) Gecko/20100101 Firefox/56.0"
Comment: - - - - - - ->8 - ERROR.LOG
2021/01/11 20:33:55 [error] 36458#100381: *486 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Cannot redeclare format_size() (previously declared in /usr/local/www/drupal9/core/includes/common.inc:136) in /usr/local/www/drupal9/vendor/drupal/core/includes/common.inc on line 136" while reading response header from upstream, client: xx.xx.xx.xx, server: drupalsite.info, request: "GET /core/install.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fpm.sock:", host: "drupalsite.info:443"
Comment: Thank you for your feedback.  I was able to modify my "www" user and su to my "www" user and then run the composer without the -- arguments and... ...it worked.
Comment: @bforest If you found the answer, you can write an answer to your own question; this is helpful for future visitors to the site who may have a similar problem.
Answer: The issue is resolved.  I was running Composer as root and disabling scripts and plugins because of that.
In my over concern for security, I didn't think to just enable my servers "www" user to allow for access via "su www".  Sometimes you just need a good SHAKE!

"Don't run the command with that flag. You say you're using these
flags because composer says to use them if you run as root, so don't
run as root.
– sonfd 12 hours ago"

Thank you for your feedback. I was able to modify my "www" user and su to my "www" user and then run the composer without the -- arguments and... ...it worked.
– bforest 11 hours ago
@bforest If you found the answer, you can write an answer to your own question; this is helpful for future visitors to the site who may have a similar problem.
– Patrick Kenny 5 hours ago.


Testing a class based Django view which returns a JsonReponse

Question: What is the proper way to test a class based Django view which returns a JsonResponse type. For example, the beginning of my class looks like this:
class MyView(LoginRequiredMixin, View):

    def get(self, request):

        return JsonResponse({
            "status": 200,
            "message": "message to return."
        })

I have similar 'post' and 'delete' functions. The url /myview is connected to this view. When I attempt something like this:
c = Client()
response = c.get('/myview')

'response' is a HttpResponsePermanentRedirect type, and I am unsure how the JSON data can be obtained from that.
EDIT --
I login in the setup of the test
Comment: Does the redirect go to `/myview/`?
Comment: also you have LoginRequiredMixin which means you should login your client prior to request
https://docs.djangoproject.com/en/3.0/topics/testing/tools/#django.test.Client.login
Comment: yes, executing response['location'] gives /myview/ .
Comment: Also I do login, it is just not shown here
Comment: https://docs.djangoproject.com/en/3.0/ref/settings/#append-slash, in other words always use routes with trailing slash
Comment: Then `/myview/` is the URL you should use.
Answer: I think you just need to add the trailing slash to your URL
c.get('/myview/')

if APPEND_SLASH is turned on (and I think Django turns it on by default), any request without the trailing slash will generate a redirect to a URL with the trailing slash


Pearl's Causal Inference In Statistics: Study Question 1.5.3

Question: Problem Statement: Consider a graph $X_1\to X_2\to X_3\to X_4$ of binary random variables, and assume
that the conditional probabilities between any two consecutive variables are given by
\begin{align*}
P(X_i=1|X_{i-1}=1)&=p\\
P(X_i=1|X_{i-1}=0)&=q\\
P(X_1=1)&=p_0.
\end{align*}
Compute the following probabilities
\begin{align*}
&P(X_1=1,X_2=0,X_3=1,X_4=0)\\
&P(X_4=1|X_1=1)\\
&P(X_1=1|X_4=1)\\
&P(X_3=1|X_1=0,X_4=1).
\end{align*}
My Answer: First, we have
\begin{align*}
P(X_1=1,X_2=0,X_3=1,X_4=0)
&=P(X_1=1)P(X_2=0|X_1=1)P(X_3=1|X_2=0)P(X_4=0|X_3=1)\\
&=p_0(1-p)^2q.
\end{align*}
This is due to the Rule of Product Decomposition. I understand how this works for conjunctions like the first probability. But I feel like that's a warmup question. Pearl has no examples to show how to compute these probabilities when you leave out terms in the graph. Can you please give me some hints on the last three probabilities? For example, how do you work forward through a graph, such as for $P(X_4=1|X_1=1),$ versus working backwards through the graph, such as for $P(X_1=1|X_4=1)?$
Thanks for your time!
Answer: First write conditional probability formula:
$$P(X_4=1|X_1=1)=\frac{P(X_1=1,X_4=1)}{P(X_1=1)}$$
Then, write the numerator in terms of the full joint:
$$\begin{align}P(X_1=1,X_4=1)&=\sum_{x_2\in (0,1)}\sum_{x_3\in(0,1)}P(X_1=1,X_2=x_2,X_3=x_3,X_4=1)\end{align}$$
which can be calculated expanding the joint wrt graph provided.
You can calculate $P(X_4)$ to be used in $P(X_1=1|X_4=1)$ in a similar way.
Comment: Ah, I see. Many thanks!
Comment: No doubt it's obvious to you, but it's not to me; your first equation there is simply the definition of conditional probability. Where does your second equation come from? It kind of makes sense as an equation, but I'm just wanting to know its source. Thanks for your time!
Comment: @AdrianKeister It's basically marginalization: https://en.wikipedia.org/wiki/Marginal_distribution in its simplest form: $$P(A) = P(A\cap B) + P(A\cap B')$$
Answer: Since this specification satisfies the Markov property, the simplest way to frame the problem is as a Markov chain.  Let $X_t$ denote the value at "time" $t$, and note that it has the transition probability matrix:
$$\mathbf{P} = \begin{bmatrix} 1-q & & q \\ 1-p & & p \\ \end{bmatrix}.$$
For simplicity, take the row labels and column labels for this matrix to be $i,j=0,1$.  All of the listed probabilities can be computed from standard probability results for discrete Morkov chains.  For example, to get the second probability on your list, you take three steps of the chain, using the transition probabilities in the matrix:
$$\mathbf{P}^3 = \begin{bmatrix}
1 - q + q^2 - q^3 - q p + 2 q^2 p - q p^2 & & q - q^2 + q^3 - 2 q^2 p + q p^2 + q p \\[6pt]
1 - q + q^2 - q p - q^2 p + 2 q p^2 - p^3 & & q - q^2 + q p + q^2 p - 2 q p^2 + p^3 \\[6pt]
\end{bmatrix}.$$
So you get:
$$\begin{equation} \begin{aligned}
\mathbb{P}(X_4=1|X_1=1) = [\mathbf{P}^3]_{1,1} = q - q^2 + q p + q^2 p - 2 q p^2 + p^..
\end{aligned} \end{equation}$$
The remaining probabilities in the list can be obtained similarly, though in one case you should reverse the "time"-direction Markov chain.
Comment: Thanks, that's informative! While I understand the basic idea of Markov chains, I haven't studied them in detail; I imagine this would all make more sense once I do (it's on my list to study, since I'm extremely interested in queueuing theory). Thanks again!


Why do we need Wald's confidence interval to estimate p in a Bernoulli distribution?

Question: I'm studying statistics and I'm a bit confused about why Wald confidence interval is needed to estimate the p in Bernoulli distribution.
Let's say, I am modeling some phenomenon with a Bernoulli distribution: $ X \sim B_p $.
From my sample where n > 30, I want to estimate the p.
To my knowledge, Central Limit Theorem guarantees that the sampling distribution of $ \hat{p} $ is going to be Normal, if the sample size > 30. I understand that CLT talks about sums and means, but proportion is calculated the same way. Mean applies for continuous distribution and proportion applies to discrete distribution; but it is calculated the same way.
And based on this, I can construct a confidence interval using t-distribution (because I also have to estimate the variance). So in other words, there is no difference between estimating p and mean of a distribution as far as how we go about constructing the confidence interval.
Apologies, but if this is the case, why do we need Wald's confidence interval? I also came across other methods that are used to compute the confidence interval for p.
Did I misunderstand the CLT and how to estimate a proportion and means for any distribution?
Answer: You don't need the Wald interval. I think this link will help you. The $t$ version also works, and may even work better (see link), but it's at least partly a matter of simplicity.
As general advice, there are often multiple ways to create confidence intervals, and they may be better or worse in various ways (simplicity, exact versus approximate, rate of convergence (if not exact), coverage probability, length, and maybe other criteria too).
If you look at Wikipedia you can see a bunch of different confidence intervals for $p$.
Comment: Thanks; going through the link you referred actually clarified how we measure the standard error for the proportions. So t-distribution doesn't make any sense in this case.


python object has properties on initialze

Question: I created a graph node class in Python.
Each node has single parent, multiple children and properties.
An implementation should be like below:
# graph_test.py
class Node(object):
    def __init__(self, name, prop={}):
        self.name = name
        self.properties = prop
        self.parent = None
        self.children = []
        print "New node:", self.name, self.properties
    def add_prop(self, k, v):
        self.properties.update({k:v})
        print "added prop:", k, v
    def add_child(self, n):
        self.children.append(n)
        n.parent = self

class Foo(object):
    def __init__(self, n):
        self.node_num = n
        self.root_node = None
        self.current_node = None
    def bas(self):
        n = Node("root")
        n.add_prop("this_prop_is", "set_only_root_node")
        self.root_node = n
        return self.root_node
    def bar(self):
        self.current_node = self.bas()
        for i in range(self.node_num):
            n = Node(str(i))
            self.current_node.add_child(n)
            self.current_node = n

if __name__ == '__main__':
    f = Foo(5)
    f.bar()

In this code, it is expected that only the root node has the property whose key is "this_prop_is".
However, result of execution is like below:
$ python ./graph_test.py
New node: root {}
added prop: this_prop_is set_only_root_node
New node: 0 {'this_prop_is': 'set_only_root_node'}
New node: 1 {'this_prop_is': 'set_only_root_node'}
New node: 2 {'this_prop_is': 'set_only_root_node'}
New node: 3 {'this_prop_is': 'set_only_root_node'}
New node: 4 {'this_prop_is': 'set_only_root_node'}

All nodes have the same key even I add it to only node "root".
I use python 2.7.6.
My questions are:

Is this a bug?
If this is not a bug, why does this occur?
How to fix this issue?
Answer: This is not a bug. The problem is your default value for prop. You set it as an empty dictionary. However, this empty dictionary is copied by reference with self.properties = prop and when it is modified, the next time a new Node is created, the modified dictionary is used as the default value.
To fix this, put None as the default value and check for None when assigning properties:
# graph_test.py
class Node(object):
    def __init__(self, name, prop=None):
        self.name = name
        self.properties = prop or {}
        self.parent = None
        self.children = []
        print "New node:", self.name, self.properties
    def add_prop(self, k, v):
        self.properties.update({k:v})
        print "added prop:", k, v
    def add_child(self, n):
        self.children.append(n)
        n.parent = self

class Foo(object):
    def __init__(self, n):
        self.node_num = n
        self.root_node = None
        self.current_node = None
    def bas(self):
        n = Node("root")
        n.add_prop("this_prop_is", "set_only_root_node")
        self.root_node = n
        return self.root_node
    def bar(self):
        self.current_node = self.bas()
        for i in range(self.node_num):
            n = Node(str(i))
            self.current_node.add_child(n)
            self.current_node = n

if __name__ == '__main__':
    f = Foo(5)
    f.bar()

Comment: Thanks. In C++, default arguments are evaluated every function call, so it's very confusing...
Answer: This is because you have a mutable default value in Node.__init__. In Python, default values are determined when the function is created, and the same instance will always be used. So every time you create a new Node and don't give it an explicit prop argument, it will use the same dictionary.
This is often solved by using None as the default value and creating a new dictionary each time inside the function if the argument is None, for example by doing self.properties = prop or {}. (This will also use a new dictionary if you give it an empty dictionary, but this isn't usually a problem)
Answer: Change props={} to props=None and self.properties = prop to self.properties = prop or {}
This is due to the behavior of mutable default arguments in Python. Here's a good resource to read up on this: http://effbot.org/zone/default-values.htm


Route Server 08 R2 VPN (PPTP) traffic to two subnets (public & private)

Question: I recently transitioned our VPN server from a Windows Server '03 box to '08 R2, both using built-in Routing and Remote Access for PPTP connections. Our firewall has a rule that forwards traffic from a public IP address (which the clients connect to) to the VPN server which is on a private subnet.
Is there an option in RRAS to force the clients to use the VPN connection for both our private and public (on which the firewall is routing traffic) subnets? VPN connections currently only have access to the private subnet unless "Use default gateway on remote network" or "Send all traffic over VPN connection" is checked on the client.
Ideally clients would route only their traffic for our private and public subnets though their VPN connection, and everything else as normal. I could have sworn we had a option set to allow this when our VPN server was on a Server '03 box.
Answer: There is no way to push routes from a PPTP server, they need to be configured on the client side. For more information, see my answer to this other question:
Windows remote access server (PPTP) advertised routes


Why is k-medians typically used with Manhattan rather than Euclidean distance?

Question: K-medians is typically used with Manhattan distance rather than Euclidean distance. Why is this?
Comment: Do you have a source for this extraordinary claim?
Comment: http://books.google.com/books?id=IfTpAQAAQBAJ&pg=PA67&lpg=PA67&dq=k+medians+manhattan&source=bl&ots=33TM6Vs3mJ&sig=2KDU5EnZlUGGKjilfY8oM9XPCCI&hl=en&sa=X&ei=ceFjVIOfBMW1oQTVxoKgDg&ved=0CEYQ6AEwBw#v=onepage&q=k%20medians%20manhattan&f=false
Comment: At "When folks ..."
Comment: One of the **benefit** of using PAM (K median/K means are not algorithms) is that we can use arbitrary distance metric. That doesn't mean we **need** to use Manhattan distance.
Comment: So, in a way, K median might be used instead of K means when we know Manhattan distance is suitable in our problem. Because, I don't think LLyods algorithm for K means is guaranteed to converge for Manhattan distance. But there might be other reasons for choosing K medoids too.
Comment: Yes, I know we don't need to use the Manhattan distance. I just don't understand the intuition behind why Manhattan distance is more suitable for K medians.
Answer: The mean is a least squares estimator of location. It is appropriate to use with squared deviations (i.e. squared Euclidean distance, k-means algorithm)
The median is the best absolute deviation estimator or location. It is appropriate to use with absolute deviations (i.e. Manhattan distance, k-medians algorithm)
The medoid (c.f. PAM) is a smallest-distance estimator, it works with arbitrary distances. (K-medoids algorithm = PAM).


How do you change the default value on a CCK text field that is part of a field group via hook_form_alter()?

Question: I'm trying to programmatically set the default value (#default_value) on a textfield added via CCK. This field is in a field group. Here is my code:
/**
 * Implements hook_form_id_form_alter().
 */
function EXAMPLE_form_profile_node_form_alter(&$form, $form_state) {
  // We need to jump into a CCK field, so say we all.
  $form['#after_build'][] = 'EXAMPLE_form_profile_node_form_after_build';
}

function EXAMPLE_form_profile_node_form_after_build($form, &$form_state) {
  $form['group_company_profile']['field_pro_name']['#default_value'][0]['value'] = t('test');

  return $form;
}

I've tried various other points in the array and nothing seems to work. Both CCK and my module are weight 0. I must be missing something super obvious...?
UPDATE: One mistake was the field name. It should be field_pro_name. Updated above. It's still not working. Interestingly, I can use the after build to change the field title with:
$form['group_company_profile']['field_pro_name'][0]['value']['#title'] = 'ttt';

However, none of these changes the default value:
// In form alter:
$form['group_company_profile']['field_pro_name'][0]['#default_value']['value'] = 'ttt';
$form['group_company_profile']['field_pro_name'][0]['value']['#default_value'] = 'ttt';

// In after build:
$form['group_company_profile']['field_pro_name'][0]['value']['#default_value'] = 'ttt';
$form['group_company_profile']['field_pro_name'][0]['#default_value']['value'] = 'ttt';

Answer: You should be able to do something like this:
function EXAMPLE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id=='profile_node_form') {
    $form['group_company_profile']['field_pro_type'][0]['#default_value']['value'] = 'hello world';
  }

  // all other form alters here...

}

or
function EXAMPLE_form_profile_node_form_alter(&$form, &$form_state) {

  $form['group_company_profile']['field_pro_type'][0]['#default_value']['value'] = 'hello world';

}

directly from whichever form_alter() style you like.
Comment: Thanks for this, but it did not work. I verified the alter is firing.
Comment: Ok, it worked here so something must be different between systems :(
Comment: I did just notice a cut and paste type in my answer (didn't have a closing ] after 'field_pro_type' that I just fixed :)
Comment: Thanks! Re: typo, I submitted an edit for that. Guess it's not needed. Also, it works for you? Grrr! Thank you very much for trying, will dig deeper. :)
Comment: Yah, none of that array exists in the form_alter, which is (I thought) expected, since it's CCK.
Comment: Well, keep on truckin.  One issue that confuses me is I don't know why you have `users_form....` in any of this as it should just be `profile_node_form` but we all know about `should` with respect to all of this :)
Comment: Oh, man. Paste fail! "users" was part of the module name I forgot to replace with EXAMPLE. Sorry. Also, the "form" is causing I'm using hook_form_FORM_ID_alter().
Comment: OH MAN, fail on my part. I didn't actually test your code in the form_alter, I did it in hook_form_FORM_ID_alter() (which was firing). No idea why it works in the form_alter, but it does. Thanks!
Comment: *should* to the rescue once again :)  glad it works!
Comment: PS -- given there is actually a `user_form` I bet that was confusing drupal in your specific alter (and another reason underscores are frowned upon in module names)
Comment: Thanks! But the module name part was "_users" not "user." Had no idea underscores in module names was frowned upon. Good to know!


WR Line while swimming

Question: Watching the Olympics I have found the swimming very interesting. I've noticed that while the swimmers are swimming the TV Channel (BBC) projects a line across the width of the pool saying WR (World Record) at the end.
I'm a bit unsure about this line, I know it's to show where the swimmers would need to be at to get the World Record but is the line showing where the swimmer who holds that world record was at that point or is it showing the required place through out? e.g. say the 100m WR was 50 seconds, then the line would progress 10m every 5 seconds.
Answer: I'm pretty sure it shows the world record pace, rather than the position of the holder at that point in the race - i.e. it advances at a constant speed. Unless the TV company had exact positional data on every world record swim, it would be impossible to plot the position of the swimmer.
The only reference I can find is at http://forums.usms.org/archive/index.php/t-11588.html which doesn't seem authoritative, while the page at http://ethw.org/Technological_Innovations_and_the_Summer_Olympic_Games, in the final section, talks about the line but doesn't mention the specific question asked.
EDIT: See the second bullet point from http://sports.yahoo.com/blogs/olympics-fourth-place-medal/world-record-line-most-distracting-technology-olympics-021256537--oly.html
Comment: Do you happen to know if it corresponds to the position of the swimmer's hands or head? If someone is swimming with their head at that line, are they ahead of the WR pace?
Comment: I have no source for this, but my intuition tells me that it's the hand position, as that's what stops the timing. So if the swimmer's hands are ahead of the line, they're ahead of the pace.
Comment: Actually it's not out of the question to compile exact positional data on every WR swim at intervals of a fraction of a second, since most of them have been set in the digital age at major world meets where there's at least one camera on every swimmer all the time. But, all you really need are the lap times for that swim, and an interpolation model that can vary the speed of the line to account for naturally faster segments of each lap (launch, final touch in backstroke).
Comment: Since they have splits at every wall, I'm 100% sure that the pace of the line is broken down and adjusted, instead of being a steady WR pace over the course of the entire race.  I think they just do it by 50, instead of instant to instant.
Comment: Can you provide an independent reference saying that?
Comment: @TrueDub - Don't really need one.  If it was a "steady state" pacing of the line using average speed, with the backstroke and, especially, the breaststroke being so much slower than the butterfly and freestyle legs, a steady pace line would have the the swimmers ahead of the line on the butterfly, getting passed in the middle legs, and then closing or passing on the line at the end.  Every time.  That doesn't happen.
Comment: I disagree that you don't need an independent reference - not because I think you're wrong, but because at the moment it's only an opinion, and the site likes opinions to be backed up by references.
Answer: It's definitely based on the particular race that set the world record to some extent.
Ye Shiwen's Women's 400 IM record in 2012 had an incredibly fast last 100m (the freestyle section). If you look at the line showing for the record in this year's races, it was generally a long way behind at the 300m point before surging up in the last 100m so it definitely matches the split times every 50m.
I'd guess that it goes at constant speed along each length but there may be more precise data included.
Comment: Welcome to SE.Sport. To write good answers it is bettere to add one or more sources to confirm what you have written
Answer: The line is based on the world record's holder's lap split. The line goes at the average speed the world record swimmer would have had if swimming at a constant speed. It does not take in account the accelerations or decelerations of the swimmer (you would never see the yellow line go suddenly fast but always at the same pace).
Comment: This is believable, but do you have a source to back this up?
Comment: @PhilipKendall "the WR line will only be the average time of the swimmer's lap split as you cannot define the furthest point of the swimmer: his arms keep moving back and forth." - my swim coach who has been twice an Olympic swimmer
Comment: @PhilipKendall +1. But the way I see this is I don't see any difference between this answer and other two answers.

WR Line while swimming


Caminho de Instalação personalizado através do SETUP

Question: Quando publico  a aplicação do windows form, ele ja gera  o Setup pelo visual Studio 2010 o qual  o qual ao rodar , instala em "arquivos de programas" no windows 7  a Instalação.
Gostaria de criar um diretório de nome c:\CartorioScanner\ e neste diretório ao rodar o Setup, instalar o programa, saberiam como posso fazer isso?
Muito Grato
Comment: Pessoal deu certo, eu mesmo criei o instalador no Visual Studio  e direcionei para criar no diretório especificado.Muito Obrigado!
Comment: Têm como esclarecer um pouco mais sua dúvida? Você quer saber como cria um setup do projeto?
Comment: Isso mesmo Daniel, quando você cria uma versão você  vai no Publish do Visual Studio e gera uma versão para ser instalada em winform.Ai quando vc executa o setup gerado ele por default instala  o programa na pasta de  arquivo de programas do windows.Só que eu não quero que seja assim.Gostaria de gerar uma instalação onde ele me intale num diretório pré-determinado, por exemplo, c:\CartorioScanner\.
Comment: ok, vou postar uma resposta...
Answer: Um dos setups que aprendi que foi bem didático com os desenvolvedores que trabalho é desta maneira, espero que ajude:
passo 1: Crie uma aplicacao de setup.

Junto ao seu projeto web, aplicações e etc. (utilizarei o exemplo do setup project, mas o web setup é semelhante a esses passos)
Passo 2: abra as ações customizadas

Aqui você incluirá seu projeto e entraremos ao passo seguinte
passo 3: Vamos adicionar o projeto

passo 4: abra com duplo clique a opção "application folder"

Abrindo esta opção você irá na opção primary output
passo 5 : Insira sua aplicação ao setup.

Como eu não tenho nenhuma aplicação em meu solution, não apareceu nenhuma opção na aba, mas como exemplo eu dei uma rabiscada rápida para exemplificar.
Passo 6: Dar ok em tudo e verifique se os itens estão adicionados corretamente.
Neste passo, após confirmar todos os passos feitos na imagem do passo 4 ira aparecer o seu projeto em todas as pastas de: Install, Commit, Rollback, Uninstall. Automaticamente aparecerá as Dll's na pasta "detected dependencies" na aplicação de setup. Após feito isso, dar um build e se funcionar corretamente basta buscar o setup que fica na pasta debug desta aplicação.


Multiple strategies for same function parameter in python hypothesis

Question: I am writing a simple test code in Python using the Hypothesis package. It there a way to use multiple strategies for the same function parameter? As an example, use integers() and floats() to test my values parameter without writing two separate test functions?
from hypothesis import given
from hypothesis.strategies import lists, integers, floats, sampled_from
@given(
    integers() ,floats()
)
def test_lt_operator_interval_bin_numerical(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)

The above code doesn't work, but it represents what i would like to achieve.
NB: I have already tried the trivial solution of creating two different tests with two different strategies:
def _test_lt(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)

test_lt_operator_interval_bin_int = given(integers())(_test_lt)

test_lt_operator_interval_bin_float = given(floats())(_test_lt)

However I was wondering if there was a nicer way to do this: when the nummber of strategies becomes larger, it is quite redundant as code.
Comment: so your values can be either integers() or floats()? if so you can simply do `@given(integers() | floats())`
Comment: Yes, that works!  You can also use `st.one_of(integers(), floats())` which may be easier for programattic use.
Comment: Is it possible?? I didn't know it. if it works, it solved my problem
Comment: Well you can add an answer and i will accept it!
Answer: In general if you need your values to be one of several things (like ints or floats in your example) then we can combine strategies for separate things into one with | operator (which operates similar to one for sets -- a union operator and works by invoking __or__ magic method):
from hypothesis import given
from hypothesis.strategies import integers, floats
@given(
    integers() | floats()
)
def test_lt_operator_interval_bin_numerical(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)

or you can use strategies.one_of as @Zac Hatfield-Dodds mentioned which does pretty much the same thing:
from hypothesis import given
from hypothesis.strategies import integers, floats, one_of
@given(
    one_of(integers(), floats())
)
def test_lt_operator_interval_bin_numerical(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)


Copying part of an xml document to another document using Xdocument

Question: I have an xml document which is roughly as follows
<Gov>

        <address></address>
        <address></address>

        <line1></line1>
        <line1></line1>

<Gov>

I need to copy everything in the body(and including) to a new XDocument. What is the best way to
Answer: Here is an example of copying data "xml" from one document to another.With selection of personalized node
First you need convert Xdocument to XmlDocument:
using System;
using System.Xml;
using System.Xml.Linq;

namespace MyTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {

            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");

            var xDocument = xmlDocument.ToXDocument();
            var newXmlDocument = xDocument.ToXmlDocument();
            Console.ReadLine();
        }
    }

    public static class DocumentExtensions
    {
        public static XmlDocument ToXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new XmlDocument();
            using(var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }
            return xmlDocument;
        }

        public static XDocument ToXDocument(this XmlDocument xmlDocument)
        {
            using (var nodeReader = new XmlNodeReader(xmlDocument))
            {
                nodeReader.MoveToContent();
                return XDocument.Load(nodeReader);
            }
        }
    }
}

And now simplified copy with XmlDocument
    XmlDocument doc1 = new XmlDocument();
    doc1.LoadXml(@"<Hello>
                           <World>Test</World>
                   </Hello>");

    XmlDocument doc2 = new XmlDocument();
    doc2.LoadXml(@"<Hello>
                   </Hello>");

    XmlNode copiedNode = doc2.ImportNode(doc1.SelectSingleNode("/Hello/World"), true);
    doc2.DocumentElement.AppendChild(copiedNode);

more information here:

http://blog.project-sierra.de/archives/1050
Copy Xml element to another document in C#
Converting XDocument to XmlDocument and vice versa

I hope this help you.
Answer: Read in the input XML into one XDocument and  construct a second, passing in the node you are interested in:
XDocument newDoc = new XDocument(XDocument.Load("input.xml").Descendants("Body").First());


Como adicionar apenas 1 vez o mesmo item no carrinho ? (JavaScript)

Question: Como faria para adicionar apenas 1 vez o mesmo item no carrinho?
<code>import React, { Component } from "react";
import * as S from './styles'

//Components
import ImgCar from '../src/components/imgs/car.svg';

class Car extends Component {

  state = {
    carAdd: [],
    car: [
      {
        id: 0,
        name: "Jetta",
        assembler: "Volkswagen",
        price: 144000,
        type: "Sedan",
        btnDisabled: false
      },
      {
        id: 1,
        name: "Polo",
        assembler: "Volkswagen",
        price: 70000,
        type: "Hatch",
        btnDisabled: false
      },
      {
        id: 2,
        name: "T-Cross",
        assembler: "Volkswagen",
        price: 123000,
        type: "SUV",
        btnDisabled: false
      }

    ]
  }

  funcBtnAdd = (event) => {
    const check = this.state.car.filter(item => item.id == event.id);
    event.btnDisabled = true;
    console.log(check)
    this.setState({
      carAdd: this.state.carAdd.concat(check)
    })
  }
</code>
Answer: Se check for o carro a ser adicionado, faria o seguinte:
<code>  funcBtnAdd = (event) => {
    const check = this.state.car.filter(item => item.id == event.id);
    event.btnDisabled = true;

    const isCarAlreadyAdded = this.carAdd.some(car => car.id === check.id);

    if (!isCarAlreadyAdded) {
      this.setState(prevState => ({
        carAdd: [...prevState, check]
      }))
    }
  }

</code>
Explicação: A função some retorna true se a condição passada for verdadeira.
Então, ela verfica se no array de carros já adicionados (carAdd) já existe o novo carro a ser inserido. Caso sim, o valor da variável isCarAlreadyAdded será true, e o estado não será atualizado.
Comment: Muito obrigado, entendi a lógica. Vou testar aqui e já já passo se deu bug ou se ta ok. grato


how to analyze memory usage in Windows phone?

Question: I am trying to analyze memory usage in Windows phone. I want to get the memory details about Internal Memory, RAM. In that I want to analyze Total memory, Used memory, Free memory.
I was successful to find the phone memory Free space and Total RAM Size but I failed to find used RAM, Free RAM, Used Phone memory, Total space in phone memory.  Is there any way to find this? Any example?
Answer: If you want to check memory usgae real-time, check out the Coding4Fun toolkit MemoryCounter. You can add the counter to any page via code or xaml
<code><Grid x:Name="LayoutRoot">
   <funtoolkit:MemoryCounter/>
</Grid>
</code>
The MemoryCounter control will display memory stats as you navigate your app. (Note: You'll want to add it to any page that you want to profile)
If you want to get a full report of memory usage then you should use the memory profiler built into Visual Studio. From the Debug menu select Start Windows Phone Application Analysis. This will open a window in which you can pick if you want to profile memory or performance.
You can read more about the profiler on MSDN.
Answer: go to storage sense -> tap on 'Phone' will list apps residing on internal memory.
Tap on SD card -> will list other apps.


Apply comments votes to parent node (with Rate module)

Question: My site have a fivestar field in comments, where users gives their vote and the points are applied to the parent node. This is possible using Fivestar module, following this instructions: http://drupalclinic.blogspot.com.es/2011/09/add-fivestar-ratings-in-comments-and.html
Could the same be done with Rate module (https://www.drupal.org/project/rate) and without custom coding?
Answer: No, it is not possible.
And also unlike Fivestar module, where the rating field can be made visible in node/comment form and node/comment display, the Rate module allows you to add the field only on node/comment display, not on form.
Comment: Maybe using http://stackoverflow.com/questions/11692101/display-rate-module-in-drupal-7-template or some other "hacky" solution??


Como passar parâmetros para um Array em javascript?

Question: Como eu poderia passar dinamicamente as informações para o array abaixo?
Exemplo: tenho uma listagem de 40 coordenadas em um arquivo de texto, por exemplo, ou em um banco Access, como passo essas coordenadas para a variável locations abaixo?
var locations = [
        {lat: -31.563910, lng: 147.154312},
        {lat: -33.718234, lng: 150.363181},
        {lat: -33.727111, lng: 150.371124},
        {lat: -33.848588, lng: 151.209834},
        {lat: -33.851702, lng: 151.216968}
];

Comment: vc teria que mostrar o formato do arquivo de origem. Basicamente vc vai utilizar um get e um loop.
Answer: Caso o objeto já tenha sido criado você pode acessar usando o indíce do array e o a chave que você quer acessar.
Exemplo:
locations[0].lat = -51.00;

para acessar o primeiro elemento de locations.
Para adicionar novos elementos use o push e ele adicionara no final do seu array.
Exemplo:
locations.push({lat: -51.00, lng: 29.00});

Answer: Você pode passar as coordenadas para dentro da variável locations da seguinte forma:
locations.push(
   { lat: -30.851700, lng: 150.363100 }
);

Atualizado
Através do recurso push você irá adicionar o item no final da variável locations (array). Vale ressaltar que você deve se certificar que está passando corretamento o objeto dentro da função push. Exemplo:
{
   lat: 10.00,
   lng: 20.00
}


How are biases updated when 'batch size' > 1?

Question: This is my network represented in matrices: (a dot represents an arbitrary number)

Feed-forwarding: (I omitted nesting it all in an activation function for the sake of brevity)

Backpropagation

The question

$\partial E/\partial b^3$ should equal a matrix of dimensions: $3 \times 1$, in order to make the subtraction possible by the former $b^3$. The batch size of 5, however, made the dimensions of the $b^3$ matrix equal to $3 \times 5$, which is problematic as you now can't subtract $\partial E/\partial b^3$ because of the dimension mismatch.
What went wrong? Am I supposed to take the average of each row of the $\partial E/\partial b^3$ matrix or perhaps just accumulate each row? Or is it something completely different?
My reflection
At the moment I am thinking that what I have done up to now is correct, however I just need to either accumulate or take the average of all the numbers in each row in the matrix $∂E/∂b3$. This way the matrix will be of size $3\times1$ as wanted, and it also makes intuitive sense in the way that I am updating the bias based on an error calculated over an entire batch size, therefor either accumulating or taking the average would make sense. However as I mentioned I am not sure which one it is, or if it is even the right choice.
Any help is highly appreciated!
Comment: What is you loss function ? It is supposed to be a **scalar** function so the derivative should be a $3 \times 1$ vector.
Also, you never use the bias, are you sure that for example $a^1 = W^1 \cdot X $ instead of $a^1 = W^1 \cdot X + b^1 $
Comment: @user7573566 Would it be incorrect to simply average each row, so that the current $3\times 5$ matrix becomes a $3\times 1$ vector? (I refer to $\partial E/\partial b^3$)
Comment: @user7573566 My loss function is MSE (mean squared error) $1/M∗(a^3−y)$ where M is the total number of training examples. I left $1/M$ in the above to simplify the example. What scalar function would you recommend I used instead, so the derivative is becomes $3\times1$ vector?
Answer: You use the batched operations in your derivations which makes it more difficult to understand. When you do this,
$a^3 = W^3 a^2 + b^3$ is an invalid matrix sum since b is a vector and not a matrix.
You cannot apply usual chain rule
$$ \frac{\partial E}{\partial b} = \frac{\partial E}{\partial a^3}\frac{\partial a^3}{\partial b}$$
because $\frac{\partial a^3}{\partial b}$ is a matrix by vector derivatives. Instead, it is easier to apply chain rule as
$$ \frac{\partial E}{\partial b} = \sum_{i = 1}^3 \frac{\partial E}{\partial a^3_i}\frac{\partial a^3_i}{\partial b}$$
$$ \frac{\partial E}{\partial b} = \sum_{i = 1}^3 2(a^3_i - y_i)$$
Where i is the batch index and $y_i$ the target of the i-th input.
Comment: So to clarify, you are saying that I should sum up each row, so the ($3 \times 5$) matrix is reduced to a ($3 \times 1$) vector. Is that correct?
Comment: Yes, when you compute the chain rule, it appears that you sum each row
Comment: Do you happen to have a source that states the same (that you have to sum each row), I don't want to base my knowledge on a single comment (answer) from a stranger online.
Comment: You can look at the answer, it is simply a chain rule.
Comment: Doing the feed-forward phase, the way I added the bias value is not right, as you said yourself: *"$a^3=W^3a^2+b^3$ is an invalid matrix sum since b is a vector and not a matrix."* But what is the correct way to add the bias then? https://i.stack.imgur.com/5YyKp.png
Comment: Can you confirm that this is the correct way the feedforward phase should have been written? https://imgur.com/a/OT20vXO
Comment: Yes it is correct, you can also write it more concisely $b^i (1, 1, 1, 1, 1)$ a duplication 5 times of the columns


exposed filter autocomplete suggestions sort

Question: I have more than 10 terms in vocabulary: car, red car, blue car, yellow car etc.
I know that 10 results is hardcoded value for autocomplete widget. My problem is that after typing "car", I only get various other terms, simple "car" is not in suggestions.
How does the autocomplete widget work?
Is there any way how to sort/alter results? Why it does not show the exact term first "car" and then all other terms containing "car"?
Answer: The filter handler class views_handler_filter_term_node_tid uses the autocomplete path admin/views/ajax/autocomplete/taxonomy and is driven by the callback views_ajax_autocomplete_taxonomy().
This autocomplete callback explicitly excludes the term typed in and doesn't do any explicit sorting (thus defaults to whatever your RDBMS does):
$query = db_select('taxonomy_term_data', 't');
$query->addTag('translatable');
$query->addTag('term_access');

// Do not select already entered terms.
if (!empty($tags_typed)) {
  $query->condition('t.name', $tags_typed, 'NOT IN');
}
// Select rows that match by term name.
$tags_return = $query
->fields('t', array('tid', 'name'))
  ->condition('t.vid', $vid)
  ->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')
  ->range(0, 10)
  ->execute()
  ->fetchAllKeyed();

If you'd like to alter the results or how it's sorted, the query is using tagging, thus available for altering via hook_query_alter().
Comment: HI, thank you for explanation. It is weird that the query explicitly excludes the term typed, though.
Comment: The field accepts comma delimited list of fields. I think the design is meant not to suggest a terms already entered after a user types it out.


Sucess Ajax não funciona com Controller Codeigniter

Question: Boa Tarde, sou iniciante em desenvolvimento.
Tenho um form cujo não quero que a pagina nao seja recarregada quando o usuario submita o form. pra isso estou usando Ajax, consegui realizar a inclusão no banco utilizando o codeigniter+ajax, porem a instrução sucess do ajax não está sendo invocada, gostaria de saber como faço para invoca-la, desde já agradeço`
Controller
public function agendar()
{
        $data['nome'] = $this->input->post('nome');
        $data['email'] = $this->input->post('email');
        $data['celular'] = $this->input->post('celular');
        $data['dia'] = $this->input->post('dia');
        $data['hora'] = $this->input->post('hora');

        echo $this->db->insert('agenda',$data);

    }

Ajax
 $("#formulario").submit(function(event){
     event.preventDefault();
              $.ajax({
                       url: 'http://localhost/Odontologia/odonto/agendar',
                       type: 'POST',
                       data: {
                           nome: $('#nome').val(),
                           email: $('#email').val(),
                           celular: $('#txttelefone').val(),
                           dia: $('#dia').val(),
                           hora: $('#hora').val()
                       },

                       sucess: function() {
                             alert('teste');

                           }

                   });
               });

Answer: Está digitado de forma  errada, o correto é:
success

você também pode usar o error, caso ocorra algum problema, ficaria mais ou menos assim:
    success: function(){
                alert("teste");
            },
    error: function(){
                alert("erro");
            }


How to interprete Discriminator and Generator loss in WGAN

Question: I trained GAN with learning rate 0.00002, discriminator is trained once and generator is trained twice per epoch. Wasserstein loss is used as loss function

This is the loss graph for discriminator and generator with x-axis is epochs and y-axis is loss obtained.
Again I have trained another GAN with learning rate 0.00002, discriminator is trained once and generator is trained once per epoch.

How to interpret the loss graphs? In the first graph generator has negative loss and in second graph discriminator has negative loss. Can we have negative loss for generator?why do we get negative loss?
Comment: What loss functions are you using of the generator and the discriminator?
Comment: I have implemented WGAN
Answer: A few points to make

You mentioned you're using WGAN, I strongly suggest using gradient penalty instead of clipping if you aren't already.
The generator loss is not very meaningful in WGAN. Also in general, there is nothing wrong with negative numbers at all.
Read the WGAN paper. The theory is dense, but there are important details there.
For example, you should train your discriminator more than your generator. Recommended values are 5-10 discriminator iters per generator iter.
The discriminator loss is (an approximation of) the negative Wasserstein distance between the generator distribution and the data distribution. So it's actually very interpretable and useful for diagnostics.


SMTP server on Server 2008 r2. Sorting Mail in Drop

Question: I've managed to configure my smtp server to send mail using asp.net stuff.  This was my main objective and I got it to work.  Now I want to tackle incoming mail, because well, I have an smtp server so I might as well.
I currently have it configured to recieve mail in the drop folder.  ALL mail that gets sent to my @domain.com goes to this drop folder regardless of who the email@example.com is.  So I just have this folder with a ton of emails to any possible user.  In the past, win2k days, I remember being able to add mail users and then subsequent folders within the drop folder.
Basically my question is: what is the standard way to sort the recieved mail by recipient?  I doubt the intended method is parsing .eml files, but maybe thats the new standard.  I really don't know and thats why I'm asking.
I not a sysadmin, I'm just mucking around on my own time.
Answer: Well, the POP end user functionality of SMTP Service was retired a long long time ago - so no more users. Now SMTPS is basically jsut an MTA with a drop / pickup directory, and if you need higher functions - get a full SMTP Server somewhere.
So, yes, it IS parsing EML files.
Comment: Thanks for the answer. Is there built in .net stuff that is designed for parsing .eml files?  I'm only going to have a few users, so the processing algorithm and stuff isn't that big of a deal.  I might even roll the .eml files in a db table.  We'll see.  At least I know what I'm up against now.
Comment: Follow up: Is there a way to setup outlook or any other email client to download emails from this drop directory that are only to a specific user?
Comment: Per definition not. SMTP is only for sending / receiving between servers. FOr outlook you would need another protocol (IMAP, POP etc.). SMTP service in windows is really for programmatic handling ONLY. CHeck out smartertools.com for a "higher up" email server.


Recover user certificates from old domain profile

Question: I have had problems with my Windows 2008 server domain, so I have reinstalled the whole server and recreated the user profiles, but I forgot to extract the user digital sign certificates. Now, the old domain is not available and the computer have been changed to the new domain, so I cannot login to export the certificates. Is there anyway I can recover the user certificates from the old profile?
Thank you very much for your help.
Best regards
Comment: If you didn't delete the old user profile you could try disconnecting the computer from the network and logging into the old profile using the following user name format: **OldDomainName\OldUserName**. If you're able to successfully log in then you might be able to export what you need.
Comment: The computer has been removed from the old domain, and its now in the new one. Is possible to login in the old domain?
Comment: It might be if you specify the username in the format I specified in my first comment. Disconnect the machine from the network and give it a try.
Comment: Hi! I have try it. With network disconnected it says that there no domain server available. With network connected it says that the password is not recognized. Any idea?
Answer: Everything below assumes that the old domain still exists on at least 1 DC, or that you have a backup of one of the DC's that can be restored to provide temporary functionality, even if nothing is connected to it at this time, if that is not the case then I can't think of a way to recover the certs and it's probably best to issue new ones which you'll probably need to do this for most of them anyway to deal with a new domain name.
2 options if the old domain still exists somewhere would be to either move the machines back to the old domain temporarily, export the certs, and then move the machine back into the old domain.  Second option would be to create a trust relationship between your new and old domains and then grant members of the old domain login rights on your workstations, then export the certs.
Hope that helps, let me know if you need me to clarify anything.


Add a svg icon before a link in menu YML

Question: I've created a link menu and I want to add a SVG icon before it.
This is my YML :
<code>double_vue_klesia.listeSwitch2:
  title: 'Double vue Klesia'
  route_name: double_vue_klesia.listeSwitch
  menu_name: navigation-principale
  weight: 4
  options:
    attributes:
      class:
        - listeSwitchMenuItem
</code>
I though adding a class and in CSS, adding the svg content would do the trick, but clearly it doesn't because it's breaking menu CSS.
This is my css :
<code>.listeSwitchMenuItem::before{
  content: url(../images/active.svg);
}
</code>
Is there another way more clean to do this through YML directly ?
Answer: Presumably this is for the top level of the admin toolbar...
If you want to follow core strictly you could convert your image file to an inline data: image string, but the benefits are negligible.
The icon is purely CSS, not configured, so nothing in the YML can help to control it.
You could, probably, theoretically, add a "style" attribute and put it inline, but you're in the realms of bad practice at that point.
Comment: I'd disagree, that seems like the best way to solve that problem. Unless you can do away with setting the attribute altogether in YML, and just target the item in a more natural CSS-selector-y way
Comment: No, this is for my main navigation (not for the toolbar ^^). I want to avoid bad practice, I believe the solution I tried is bad practice
Answer: agree with @Clive on comment, but do you want(not before):

class: not needed

<code>  attributes:
    class:
      - listeSwitchMenuItem
    style:
      - "background:url('url-image.svg') no-repeat 0px 0px;background-size:3px 3px"
</code>
Comment: I would like something like this


Devo usar foreign_key tanto em has_many quanto em belongs_to?

Question: Eu tenho dois models. Office e Employee. Employee tem office_id como chave estrangeira. Então, qual é o correto?
class Office < ActiveRecord::Base
  has_many :employees, foreign_key: 'office_id'
end

class Employee < ActiveRecord::Base
  belongs_to :office, foreign_key: 'office_id'
end

Ou
class Office < ActiveRecord::Base
  has_many :employees
end

class Employee < ActiveRecord::Base
  belongs_to :office, foreign_key: 'office_id'
end

Eu acho que o segundo exemplo é o correto, porque pra mim, não faz sentido declarar o foreign_key no has_many. Um colega de trabalho discorda, e acredita que o primeiro exemplo é o correto, sendo que a chave estrangeira deve ser declarada em ambos os lados da relação. Eu não encontrei muitas referências a esse assunto. Então, alguém sabe me dizer qual dos dois está correto e o porquê?
Answer: A 2º opção é a correta, como você mesmo disse é a sua classe Employee que possue a chave estrangeira na relação. Você também pode omitir a colocação da foreign_key na sua classe Employee, porque por padrão ele usa o nome da associação seguido do sufixo _id.
De acordo com a documentação:

:foreign_key Specify the foreign key used for the association. By
  default this is guessed to be the name of the association with an
  "_id" suffix. So a class that defines a belongs_to :person association
  will use "person_id" as the default :foreign_key.

belongs


Excluding specific files from Visual Studio search

Question: Is it possible to exclude certain files from search in Visual Studio.
For example jquery.js is almost always polluting my search results with half result coming from that file.
I know you can white-list specific types, but when I want to search in .js extension is there solution for that?
Vote here for feature: https://developercommunity.visualstudio.com/idea/405990/code-search-exclude-files-from-search.html?inRegister=true
Comment: Maybe this questions can help you:

http://stackoverflow.com/questions/1749837/exclude-file-types-from-search-in-visual-studio

http://stackoverflow.com/questions/1596337/how-to-exclude-designer-cs-from-visual-studio-file-search
Comment: That vote is now closed. Here's the current item. Please go vote here: https://developercommunity.visualstudio.com/idea/405990/code-search-exclude-files-from-search.html
Answer: Altough it does not solve your problem it may help out a bit
Ctrl + Shift + F should trigger the Find and Replace window.
From there, click Result Options and select "Display file names only".
It won't have all the info you need but might make it easier to recognize the files.
Comment: "Display file names only" is a life-saver! some *.min.js files are massive and cause VS to crash if they come up in results window
Comment: Doesn't really answer the question.
Answer: In Visual Studio 2019 they modernized the "find in files" feature, now you can exclude files, file extensions and directories using an exclamation mark before the items to be excluded in the "File types" textbox, like this:
*.*;!jquery.js
another example:
!*\bin\*;!*\obj\*;!*\.*;!*.xml
More info: https://devblogs.microsoft.com/visualstudio/modernizing-find-in-files/
Comment: It's unbelievable that this UI element doesn't even have a tooltip. Horrible UI design.
Answer: In Visual Studio 2017 there is a workaround: you can right-click a search result and then click Delete. I use it to eliminate the big minified files from the Find Results window.
Answer: I've got the same problem with unwanted .js files polluting the search result. Especially the minified versions (e.g. jquery.min.js) are really annoying since they consist of only one (1) single very very long line. All of that line is displayed line-wrapped in search result. Not ideal!
Possible solutions:

Since .js files are (normally) just static content, you should be able to name them as you like. Rename it to jquery.min.js.nosearch and include the file with   in HTML.
Get these files from an CDN and delete your local files.
Exclude these files from the VS project, provided that you can handle the inclusion of them in an other way when needed, e.g. when deploying (and provided that you scope your search to solution/project, not folder).
Comment: Great idea!. also, you can add a `ren /folder/jquery.min.js.nosearch /folder/jquery.min.js` command in your post-build events :-)
Answer: From this answer there was an UltraFind extension, which unfortunately doesn't exist for newer than 2010 (but see thread for hack to "update" it to 2012)
Answer: It's not particularly elegant - I'd be reluctant to call it a solution to the question - but if you can have Visual Studio Code running side-by-side with VS201x, its Find and Replace feature is pretty sophisticated. If you're using Git for source control, it will exclude any files or folders found in .gitignore from its search results - this is great when used in conjunction with tools like LibMan. Failing that, you can always manually add files / folders to its "files to exclude" option when searching.
Comment: using `.gitignore` for this is a PITA too:

1. if you want to search in files that are not in git, you have to temporarily edit your .gitignore file

2. adding a `.gitigore` is not enough, you have to add the folder to git as well