checking condition fails when using threading

Question: I am using threading in my application
I am creating a folder, when the folder is already not existing
if (!ExistingFolders.Contains(currentFolder)){
    if (lastCreatedFolder != folder) {
             lastCreatedFolder = folder;
             CreateNewFolder(context, siteLink, lName, fName);
                                }
                          }

When there are 5 threads running parallely, this condition is not working!!
For example, all 5 threads are trying to create a folder named "New"
first one is getting created, while the rest are throwing "Folder already exists" error as its already created
How can  i check the condition in this case?
Here all 5 threads are running in parallel, and condition is true for all cases where as it should be true for only the first case
Comment: What is your question?
Comment: Why threads nees to create folder at all. Create it upftont in main thread, and after threads execution terminates, delete it if it was useless. You are pushing perfectly sync io operation to multiple threads and downgrade dramatically their performance by using lock to solve the problem they are not ment to solve. Find a way in your architecture to avoid lock, as much as it possible.
Comment: That's a well-known problem. Just handle the error.
Answer: This is a race condition and you have to put a synchronisation mechanism to fix it. for example by using lock keyword you can make sure a scope of code is only accessible to one thread at a time. here lockobject is an object created before these operations. e.g. a readonly const is common.
lock(lockobject){

if (!ExistingFolders.Contains(currentFolder)){
    if (lastCreatedFolder != folder) {
             lastCreatedFolder = folder;
             CreateNewFolder(context, siteLink, lName, fName);
                                }
                          }
}

Comment: But it can still happen, an other process can do it as well. That makes it a less common error, but it still must be handled.
Comment: Yes, that is true. We can not prevent from that exception. Even my windows explorer has this issue
Answer:
How can i check the condition in this case?

By using a synchronization primitive, such as a lock:
public readonly object syncRoot = new object();

lock (syncRoot)
{
    if (!ExistingFolders.Contains(currentFolder))
    {
        if (lastCreatedFolder != folder)
        {
            lastCreatedFolder = folder;
            CreateNewFolder(context, siteLink, lName, fName);
        }
    }
}

This way, only the first thread to reach the lock statement will hold the lock, while all other threads wait for him to release it. Once it does, all others threads will see the folder has already been created.
Note that if each thread is accessing a different instance of the class containing the lock, you should make it static.


Why is my angular grid so slow?

Question: So, I have made some custom directive which draws kind of a data-grid, based on floated divs (because nested flex implementation in FF sucks - but it's not the point).
How it works :

I pass some data collection to the directive via something like <the-grid data-list="parentController.displayedRows">
Inside this first directive, I have columns via something like  with many attributes I won't precise here.
The data-value value can be a direct expression, bound to the row on which the the-grid directive controller is ng-repeating in order to display each columns, or a function which have to be $eval-uated in order to display the intended value from the parentController.
In my <the-grid> directive controller, I have the rendering template of my grid which make a nested ng-repeat div (first one on the rows of the data-collection, second one on the columns, created in the directive), it looks like :

I have some keyboard nav in order to quickly select a row or navigate within pagination or many tabs, which does nothing more than applying some class on the selected row, in addition to update some "selectedRowIndex".
I'm using angular-vs-repeat in order to have the minimum of row divs in my DOM (because the app is running on slow computers). This works well.

The problem is that every time I'm hitting some "up" or "down" key on my keyboard, Angular is "redrawing" EVERY cells of the list.

So, let's suppose I've 200 rows in my data list, and 7 columns for each rows. First load of the page, it passes ~3000 times in the renderCell() function. Ok , let's accept that (don't really understand why, but ok).
I hit the down key in order to go to the second line of my list. It passes ~1100 times in the renderCell() function.
So yes, the result is very slow (imagine if I let the down arrow key pressed in order to quick navigate within my rows)... I can't accept that. If someone could explain that to me... Any help would be greatly accepted :)
If I make the same thing without a directive (direct DOM manipulation, with columns made by hand and not in a ng-repeat within a ng-repeat), every thing is smooth and clean.
Yes, I've look into every angular grid on the market. No one is satisfying me for my purpose, that's why I've decided to create my own one.
And no, I really can't give you some JSFiddle or anything for the moment. The whole app is really tentacular, isolating this is some kind of complicated).
Answer: Try to use bind once (angular 1.3+)

Comment: This is more like a hack. You still got something wrong (undesired) in your directive.
Comment: Ok it seems to help a significant way. I was aware of the one-way binding but only on some {{ }} expression, didn't know I could apply them to some ng-repeat elements or functions. Next step is to find how to update the parent list if live modifications are made. I will accept that as a solution for the moment. Thx a lot !
Comment: Okay. So what could be wrong ? I can't see why it could be wrong. Isn't my implementation kind of simple ?

Why is my angular grid so slow?


Multi-language site

Question: I'd like to build a multilingual site and I am quite new to drupal, I was wondering if I could proceed in the following way:
I could tag my entries with the world "english" and "italian", then I could display pages only with such tags to filter my site...
Generally speaking, would I be able to filter my site by tag?
Would this option be feasible? What would be the best solution to my problem?
Many thanks for any answer!
Alex
Answer: Use the native Drupal internationalization functionality. You can then configure how nodes of different languages are shown, but by default they are found at [lang_code]/node/123 - eg fr/node/123.
You can alter Views to only show content to users in their specified language. User language can be a configurable option or can be autonegotiated based on browser headers.
Internationalization is a big, difficult topic, which I'm sure you're beginning to realise as you work on your site! i18n module is a good place to start, as it provides many useful add-ons which extend the core Drupal i18n functionality.
Answer: What version of Drupal are you using? As "cam8001" suggests, internationalisation is a huge topic, fortunately Drupal has some substantial functionality to help you out. Take a look at these resources to get a summary of the topic:

Drupal 7: HOW TO CREATE A MULTILINGUAL SITE ON DRUPAL7 PART-1
Drupal 6 & 7: Multilingual Guide, drupal.org

Perhaps most importantly know that multilingual support in Drupal has several different modules to create the functionality of a typical multilingual site. Which ones you choose to use is dependent on your needs.

Multi-language site


Lista de inicialização de membros com atributos de outra classe (herança)

Question: Eu sei que uma lista de inicialização de membros declara e no mesmo instante inicializa um tal atributo(s), é isso oque sei até agora.
No seguinte código:
#include <iostream> // std::cout

class Foo {
public:
    const int intNum;
};

class Bar: public Foo {
public:
    Bar( int x ): IntNum( x ) {}
};

int main()
{
    Bar bar( 1 );

    std :: cout << bar.intNum << "\n";

    return 0;
}

Eu estava tentando inicializar o atributo intNum que passou a pertencer a classe Bar por ter herdado de Foo, então se intVar passou a ser de Bar porquê houve erro ao tentar inicializar?
Oque tem de errado no código?
Answer: Qual o erro? Isso seria importante incluir na pergunta.
Vejo que você declarou intNum com "i" minúsculo na classe-pai, mas está tentando inicializar IntNum (com "I" maiúsculo) na classe-filha.


$(X-P) - (N\cdot(X-P))N = (I - NN^T)(X-P)$ how to prove this?

Question: $(X-P) - (N\cdot(X-P))N = (I - NN^T)(X-P)$
I see a text about Orthogonal projection onto a plane, and this formula I cann't understand, can someone please explain to me, or give me some guide information, I have learn algebra some long time ago, which I forget most of it
Answer: \begin{align}
(X-P) - (N\cdot(X-P))N&=(X-P)-N^T(X-P)N \qquad\text{note that $N^T(X-P)$ is a scalar} \\
&=(X-P)-NN^T(X-P)\\
&=(I-NN^T)(X-P)
\end{align}
Comment: why $(N\cdot V)N = N^TVN$ ?
Comment: @LiuHao for vectors $A,B$ $$ A\cdot B= A^TB$$


Problem about inequation with absolute value

Question: I have this statement:

It can be assured that | p | ≤ 2.4, if it is known that:
(1) -2.7 ≤ p <2.3
(2) -2.2 < p ≤ 2.6

My development was:
First, $ -2.4 \leq p \leq 2.4$
With $1)$ by itself, that can't be insured, same argument for $2)$
Now, i will use $1)$ and $2)$ together, and the intersection between this intervals are: $(-2.2, 2.3)$. So, this also does not allow me to ensure that | p | ≤ 2.4, since, there are some numbers that are outside the intersection of these two intervals, for example 2.35 is outside this interval.
But according to the guide, the correct answer must be $1), 2)$ together. And i don't know why.
Thanks in advance.
Answer: You getting confused by a strong premise implying a weak conclusion.
1 and 2 together say precisely:  $p\in (-2.2,2.3) $
And you are asking to conclude $p\in [-2.4,2.4] $.
That's simply a matter of noting if $(-2.2, 2.3) \subset [-2.4,2.4] $.  And if $p $ is in a smaller subset, then we can conclude $p $ must therefore also be in the bigger superset.
Or in other words:
$-2.2 < p < 2.3\implies $
$-2.4\le -2.2 < p <2.3 \le 2.4\implies $
$-2.4\le p \le 2.4$
....
An analogy:
We can conclude $p $ is a somewhat green article of clothing if we know both
1: $p$ is a hat.
2: $p$ is precisely the color an emerald takes when viewed at noon on the summer solstice on the equator.
In your question,  1 tells you that $p <2.3$ so you can conclude $p\le 2.4$.  ($p $ is a hat so you can conclude $p $ is an article of clothing.)
And 2 tells you that $-2.2 <p $ so you can conclude $-2.4\le p $.  ($p $ is the color of emeralds so you can conclude $p $ is green.)
Together 1 and 2 tell you $-2.2<p <2.3$ so you can conclude $-2.4\le p\le 2.4$.  (Together you know $p $ is a hat the color of emeralds in a certain condition so you can conclude $p $ is a green article of clothing.)
Strong premise.  Weak result.
Comment: I had thought about it. For example, if you AFFIRM that k <10, then I can affirm that: k <15. However, my problem is that, I think, I CAN NOT affirm that it is "lesser or EQUAL" than 15, since it can take the value 15 and that contradicts the initial statement of k <10.
Comment: However, I think I understand the point. A number k can be between: 10 < k <100, and at the same time, I with that i can affirm that: -10000 <k <100000, regardless of whether there are intermediate values, this is still true, this is what I understood.
Comment: The key word is "less than OR equal" is the "OR".  If $5 < 16$ then $5 \le 16$.  $5 \le 16$ does not mean that $5 =16$.  It doesn't even mean $5$ *might* be less than $16$.  It means that exactly one of the two statements:  A) $5 < 16$ and B) $5=16$ is true.  And one of them *IS* true.  A) is true.  So A OR B is true.
Comment: We are asked to verify "Fred is green or red".  We sneak up on Fred and verify that he is a solid green.  SO we say "Yep, Fred is green so the statement is true:  Fred is green or red".  But then one of us says.  "But he *isn't* red.  So he can't be green OR RED because he isn't red".  Well... the first person is right.  Fred is completely green.  That is a subset of being green OR red.  So GREEN $\implies$ GREEN or RED.
Comment: I understand the point. Where i can get info about " strong premise implying a weak conclusion."
Answer: $ -2.4 \leq p \leq 2.4$
$ -2.7 \leq p < 2.3$
$-2.2 < p \leq 2.6 $
Your answer is common intersection of these inequalities.
$ p \in (-2.2, 2.3)$
Answer: The point is that if you use $1$ and $2$ together you know $-2.2 \lt p \lt 2.3$.  This does allow you to ensure $|p| \le 2.4$ because all numbers in the interval are less than $2.4$ in absolute value.  The fact that there are numbers outside the interval that also qualify does not matter at all.  If I told you that $0.1 \le p \le 0.9$ you could assure me that $|p| \le 2.4$.  You could also make a stronger statement, like $|p| \le 1$ or $|p| \le 0.9$, but that doesn't mean the one with $2.4$ is incorrect.


Prove that if a and b are integers, then there are unique integers q and r such that $a = bq + r$, $-|b|/2 < r \le |b|/2$

Question: Prove that if a and b are integers, then there are unique integers q and r such that $$a = bq + r,$$ with the restriction that$$-|b|/2 < r \le |b|/2$$
Comment: Write *\le* to indicate so. It is nicer to see.
Comment: Note: right side of inequality meant to be less than OR equal to.
Comment: Ah, \le. Thanks.
Answer: Using the division algorithm, we can find $q,r$ such that $a = bq + r$ and $0 \le r < |b|$. If $r \le \frac{1}{2}|b|$, we are done. If not, $\frac{1}{2}|b| < r < |b|$, so we let $r' = r - |b|$, which gives $-\frac{1}{2} |b| < r' < 0$.

If you don't have the division algorithm: Let $S = \{ a - bn \mid N \mid n \in \mathbb{Z} \} \cap \mathbb{N_0}$. It is easy to see it is non-empty, and it's a subset of $\mathbb{N}$, so it has a least element, call it $r$. By the definition of $S$, there is a $q$ such that $a - bq = r$.
Assume, for the sake of contradiction, that $r \ge |b|$. Then we let $r' = r - |b|$, and note that $0 \le r' < r$. We can write $r'$ as a combination of $a$ and $b$: $r' = r - |b| = a - bq - |b| = a - b(q \pm 1)$, depending on the sign of $b$. So $r' \in S$, but this breaks the minimality condition on $r$, so by contradiction, $r < |b|$.

Uniqueness: Let $r$ and $r'$ be two solutions. Then $r = a - bq$ and $r' = a - bq'$. So $r - r' = b(q' - q)$. Since $0 \le r$, $b(q' - q) \le r'$. But the only way for this to happen is if $q' = q$. (Or if it's negative, but then you look at the other inequality).
........
Answer: $r$ is the remainder after $b$ is divided by $qa$. If the remainder is larger than $a/2$ then increase $q$ by 1 and the remainder will become negative, since $r$ can't be more than half a multiple and less than half a multiple. Same concepts apply for negative numbers.
Comment: You can't increase $a$ by $1$, it is a number given.
Comment: Hopefully this fixed it
Answer: Consider
$$S=\{a-nb:n\in\mathbb Z\}$$
there exists a unique $n\in\mathbb Z$  such that
$$-|b|/2 < a-nb \le |b|/2$$
Let $r= a-nb$


Redirect to another page in different project of same solution

Question: So I made a WP8 app and I split them into separate projects, and I put a button that redirects to another app's page but the other page is on a separate project that i have already added. How do I program it so that when I tap that button, it redirects me to another page that is of a different project but the same solution?
the code i used is:
App.RootFrame.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
Comment: http://stackoverflow.com/questions/16506731/how-to-redirect-to-a-page-which-exists-in-specif-project-to-another-page-in-othe?answertab=votes#tab-top
Answer: Try this:
NavigationService.Navigate(new Uri("/TargetProjectName;/TargetPage.xaml", UriKind.Relative));

Answer: Since the file is in a different assembly, you need to specify the name of that assembly.
Suppose your other project is called Assembly2. Then you navigate URI would be:
App.RootFrame.Navigate(new Uri("/Assembly2;component/MainPage.xaml", UriKind.Relative));


Convergence of moment of functional of random variable

Question: Define $X_n$ a continuous random variable that converges in distribution to $X$. Morever, we know that $E[|X_n|^p] \rightarrow E[|X|^p]$ for some $p > 0$.
Then, could we prove that for any continuous function $f$
$$E[|f(X_n)|^p] \rightarrow E[|f(X)|^p]?$$
Or which additional assumptions do we need? Or if $X_n$ is uniformly integrable does it imply that $f(X_n)$ is as well U.I ?
Comment: The limit you ask about doesn't even need to be defined, because all the expectations involved could be infinite.  Consider, for instance, distributions with finite absolute $p$ moments but infinite absolute $2p$ moments and let $f(x)=x^2.$
Answer: This is not true.  Set the probability space $(\Omega, \mathscr{F}, P)$ to be $((0, 1], \mathscr{B}, \lambda)$ and define $X_n = \sqrt{n}I_{(0, n^{-1})}(x)$, $n = 1, 2, \ldots$, $X \equiv 0$, then
\begin{align}
E[|X_n|] = \frac{1}{\sqrt{n}} \to 0 = E[|X|]
\end{align}
as $n \to \infty$.
Let $f(x) = x^2$, which is continuous everywhere in $\mathbb{R}$, then $f(X_n) = nI_{(0, n^{-1})}(x)$, $f(X) = 0$, hence
\begin{align}
E[|f(X_n)|] = 1 \not\to 0 = E[|f(X)|].
\end{align}
I know $X_n$ in this example may not be considered as a strict "continuous random variable", but from measure theory perspective, it is continuous almost everywhere.  Besides, you can easily modify it to be strictly continuous by linear interpolating $(n^{-1}, \sqrt{n})$ and $(2n^{-1}, 0)$, say, and the result should still stand.
Comment: +1 For a continuous example, just let every $X_n$ and $X$ have a Student $t(p-1)$ distribution with $p\gt 2$ and use the same $f.$


joint p.d.f. of stationary time series variables

Question: if a stationary time series verifies that each variable depends only on the variable before it, and the joint p.d.f. of $x_i$ and $x_{i-1}$ is $f(x_{i-1},x_i)$,
which is the joint p.d.f. of $x_i,x_{i+1},x_{i+2}$, and of $x_i,x_{i+1},x_{i+2},x_{i+3}$?
Answer: $$\begin{align}
f_{X_1,X_2,X_3}(a,b,c) &= f_{X_3\mid X_1,X_2}(c\mid X_1 = a,X_2=b)\cdot f_{X_1,X_2}(a,b)\\
&= f_{X_3\mid X_2}(c\mid X_2=b)\cdot f_{X_1,X_2}(a,b) & {\scriptstyle\text{by assumption}}\\
&= f_{X_3\mid X_2}(c\mid X_2=b)\cdot f_{X_2\mid X_1}(b\mid X_1=a)\cdot f_{X_1}(a)
\end{align}$$
in which you know the first two terms on the right side of the last expression. Do you know
the last one?
The calculations for four variables are just an extended version of the calculation given
above.


Compute $I(U), I(V),I(U\cap V)$ and $I(U)+I(V)$.

Question: Let $U=Z(x^2-y)$ and $V=Z(y)$ in $k[x,y]$ where $k$ is a field. I recall that $$Z(I)=\{(x,y)\in k^2\mid \forall f\in I, f(x,y)=0\}$$
and $$I(U)=\{f\in k[x,y]\mid \forall (x,y)\in U, f(x,y)=0\}.$$
For $I(V)$, I have that $$f\in I(V)\iff f(x,0)=0\iff f\in (y).$$
We have that $I(U)=(x^2-y)$ but I don't understand why. Indeed,
$$(x,y)\in Z(x^2-y)\iff \forall f\in (x^2-y), f(x,y)=0\iff x^2-y=0\iff y=x^2,$$
therefore, $$Z(x^2-y)=\{(x,x^2)\mid x\in k\},$$
and thus $$f\in I(U)\iff f(x,x^2)=0$$
but how can I continue ?
For the rest, I think it's fine.
Answer: If $f(x,x^2)=0$ then $y=x^2$ is a root of $g(y)=f(x,y)\in F[x][y]$, therefore, $g(y)=(y-x^2)k(y)\in F[x][y]$ and thus $f(x,y)\in (y-x^2)$.
Answer: I wish to help you. we have theorem: $k[U]\cong k[x,y]/I(U) $, we have $k[U]=k[x,x^2]=k[x]$, then $k[x]\cong k[x,y]/I(U)\Rightarrow I(U)=(y-x^2).$ In similar way we have that $I(V)=(y)$.  and $I(U\cap V)=\sqrt{I(U)+I(V)}$.
In your question $I(U\cap V)=I((0,0))=(x,y)$, and $I(U)+I(V)=(x^2-y,y)=(x^2,y)\Rightarrow \sqrt{I(U)+I(V)}=(x,y)$. we note that $I(U\cap V)\ne I(U)+I(V)$.


SVN ci failes: Commit blocked by pre-commit hook (exit code 255)

Question: I'm trying to commit dirrectory and svn fails with message:
<code>D:\path\file.ext
Commit failed (details follow):
Commit blocked by pre-commit hook (exit code 255) with output:
Got 1 errors:
* Block Merge Conflicts addon failed: Some parts of your commit look
suspiciously like merge
conflict markers.  Please double-check your diff and try
committing again. To really commit, have your admin disable
the 'block merge conflicts' pre-commit hook.
(ref svn07:4hSwdSwjOkKgIp3G)
(ref svn07:Up2uVRcH74KRkoHB)
</code>
Any ideas what it can be and how to fix it?
Thank you in advance!
Answer: Pre-commit hooks are custom scripts installed by the server admin to prevent commits that break whatever rules/standards they have in place. Your commit looks like it's being blocked because you're trying to commit a file that matches some sort of pattern that the hook is blocking.
There's no single answer to this question, since a default subversion server has no pre-commit hooks. You need to talk to the server admin about this.
Comment: >There's no single answer to this question> I'm affraid you're right
Answer: It seems to be saying that you have conflict markers still in your code.  That means lines of ">>>>", "<<<<" and "====".  This is probably because you had a conflict and simply marked it as resolved without actually resolving it.


Ember-data: How DS.attr("number") is supposed to work?

Question: I'm using DS.RESTAdapter, php on server. I have a model UacList:
DS.Model.extend({
    dummyFieldForErrors: DS.attr("string"),
    selected: DS.attr("number"),
    uacs: DS.hasMany("uac")
});

Ember sends request GET /rest/uacLists/1. Server response is:
{
    "uacList":{
        "id":1,
        "selected":32483,
        "uacs":[33618,9678,...,33656]
    },
    "uacs": [...]
}

But Ember Inspector tells me that selected is undefined (other attributes have values they should have according to server response). No matter if there is a quotes ("selected":"32483") or not ("selected":32483), it is undefined anyway. If I define this attribute as a string, it works but I don't like when an integer is defined as a string.
Comment: Does the Ember Inspector tell you that the values is `undefined` or `null`?
Comment: @gjk undefined. Ember inspector tells me, that `{id: 1, dummyFieldsForErrors: undefined, selected: undefined, uacs: }`. But **selected** should be 32483 or other number, returned in server's answer.
Comment: You say that it works if you change it to a string? Judging by the fact that `dummyFieldsForErrors` is also `undefined`, and you have two `uacs` properties in your JSON, it seems like you just have your response JSON formatted incorrectly.
Comment: @GJK dummyFieldForErrors should be undefined. When server returns errors, it should send them in following format: `{"errors":{"attributeName":[/*array of strings*/]}}`, and "attributeName" should be one of attributes, defined in model. That's why I added dummyFieldForErrors to send some general errors from server (if user unauthorized, etc). JSON is formatted according to documentation: http://emberjs.com/guides/models/the-rest-adapter/#toc_sideloaded-relationships.
Comment: There's nothing that I can see here that would cause your issues. Can you create a JSBin that reproduces the issue?
Comment: @GJK I'm afraid not, too much code needed to reproduce this. I hope someone ran into such issue and may explain. For now I'll left this attribute defined as string `selected: DS.attr("string")`
Comment: Does the `uacs:  ` actually contain values? I'm betting that your data isn't being unserialized properly. Try writing a Serializer to inspect your inbound data more closely. http://emberjs.com/api/data/classes/DS.RESTSerializer.html#method_normalize
Comment: @JamieChong Yes, uacs contain values and I use them to render a select element
Comment: What does your template look like?
Comment: @JamieChong `
  {{x-woof}}
  {{t "uacs.header"}}

      {{view "select" content=uacs
      optionLabelPath="content.title"
      optionValuePath="content.id"
      value=selected}}
      {{#if errors.selected}}
        {{#each error in errors.selected}}
          {{error.message}}
        {{/each}}
      {{/if}}

`
Answer: This is intended to be a comment, but my reps not good enough. I guess since you've got this working when the value's a string this isn't any issue, but don't you need to define DS in upper case?
Comment: I thought about that, but I'm assuming the OP just made a mistake when typing the question here. He would have *much* bigger errors if `ds` was undefined.
Comment: Yeah, I agree, no idea otherwise! I'll delete this shortly!
Comment: I use requirejs and this code is inside of module. ds is equal to DS, but it is in local scope
Answer: Just reading the docs here:
http://emberjs.com/api/data/classes/DS.html#method_attr

By default, attributes are passed through as-is, however you can
  specify an optional type to have the value automatically transformed.

So to me this implies that you shouldn't use 'number' or 'string' for your selected attribute.
DS.Model.extend({
    dummyFieldForErrors: DS.attr("string"),
    selected: DS.attr(),
    uacs: DS.hasMany("uac")
});

Comment: They are built-in types, I don't see any reason to not use them except the fact that number does not work properly in my case.
Comment: Hahah, I agree - was thinking out of the box :) This is what the NumberTransform code looks like: https://github.com/emberjs/data/blob/1.0.0-beta.15/packages/ember-data/lib/transforms/number.js#L9 It should definitely be able to handle native integers. So it must be something else.


How preserve values in PHP when the page was refreshed?

Question: For example:
<?php

class Foo
{
    public static $my_static = 0;

    public function staticValue() {
        echo self::$my_static++;
    }
}
$a = new Foo();
$b = new Foo();
$a->staticValue();
$b->staticValue();

?>

After the code executed, the result was 01. But after I refresh the page, the result is still 01. I want to know how to modify the code to obtain the result is 23 when I refresh the page. Thank you in advance.
Comment: save the previous result in session then pass in after every refresh page
Comment: use $_SESSION. not static
Comment: What do you mean by refreshing? It will be good if you provide any scenario. Because if you simply wanna do page refresh the whole script gets loaded again.
Answer: If you want preserve your values you can use sessions like this:
<?php

session_start();

class Foo
{
    public static $my_static;

    public function staticValue() {
        if(!isset($_SESSION['sum'])) {
          $_SESSION['sum'] = 0;
        }

        self::$my_static = $_SESSION['sum'];
        echo self::$my_static++;
        $_SESSION['sum'] = self::$my_static;
    }
}
$a = new Foo();
$b = new Foo();
$a->staticValue();
$b->staticValue();

?>

Read more in:

http://php.net/manual/en/intro.session.php


typescript - object literal with array syntax

Question: I had not come across such a notation:
function(a: number,
sort?: { order: -1 | 1; sortBy: string }[] ){
//function body here
}

Specifially I'm interested in the sort parameter.
I can only understand that sort is an optional argument (I can't even say for sure if it's an object literal since there's no ,).
What does this syntax read? What type of variable is it? Why is there a ; instead of a ,(BTW that is not a typo). What does {...}[] indicate?
Comment: Please consider modifying the code in this question so as to constitute a [mcve] which, when dropped into a standalone IDE like [The TypeScript Playground](https://tsplay.dev/WKkK8W), clearly demonstrates the issue you are facing.  Such code should not have unrelated errors (e.g., `public station function` is not valid). This will allow those who want to help you to immediately get to work solving the problem without first needing to re-create it.  And it will make it so that any answer you get is testable against a well-defined use case.
Answer: The sort parameter is optional as indicated by the ? but if you do supply one it must conform to the type specified to the right of the : which is of type { order: -1 | 1; sortBy: string }[]. That type means it is an array of objects whose shape is { order: -1 | 1; sortBy: string }.
The presence of ; is because in Typescript you can delimit fields of an object type by either ; or , interchangeably.
This is identical but may read clearer to you:
type SortSpecification = {
  order: -1 | 1;
  sortBy: string;
};

const func = (a: number, sort?: SortSpecification[]) => {
  /* ... */
}

And these would all be valid calls to it:
func(42);
func(42, [{ order: 1, sortBy: 'foo' }]);
func(42, [{ order: 1, sortBy: 'foo' }, { order: -1, sortBy: 'bar' }]);

Comment: how would I specify that the order field should be a number or an array of object literals(without specifying any fields) would order: number | {}[] do the trick?
Answer: Let's break it down
{ order: -1 | 1; sortBy: string }[]

The brackets at the end indicate an array. So it's an array of something, where that something is
{ order: -1 | 1; sortBy: string }

The objects in the array must have an order field which is either 1 or -1 and a sortBy field which must be a string.
Finally, as you've pointed out, the ? after the argument name makes it optional. So sort is an optional array of objects which have two fields: order and sortBy.
I certainly understand your confusion, as this is a complicated type signature. If I was writing this, it'd probably make more sense to extract it into an interface or an object type.
type SortParam = { order: -1 | 1, sortBy: string }

SortParam[]

As for the comma versus the semicolon, don't sweat it. Typescript lets you interchange the two in several situations. Use the one you prefer and don't worry about it.
Comment: No, `-1|1` means the value must be a number which is either `-1` or `1`. The `order` field, as written, is required.
Comment: is `;` interchangable in object definitions as well or type specifications?
Comment: how would I specify that the `order` field should be a `number` or an array of object literals(without specifying any fields) would order: number | {}[] do the trick?
Comment: The semicolon thing is just in types; TS tries to maintain compatibility with JS in a lot of situations, including object literals. As for your second question, the answer is [union types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types). If you want that written out in more detail, it's probably worth asking a new question on here, for the sake of organization.
Comment: okay. Just one more clarification, is `order: -1|1` also providing a default value? e.g. nothing was passed in the order field, then -1 would be the default value?


WinRM: ERROR - Failed to authenticate to 172.x.x.x. WinRM::WinRMAuthorizationError

Question: I'm trying to execute some chef commands on a Windows server using Jenkins.
When I run the build on Jenkins to execute the chef commands, I get the error below:
ERROR: Failed to authenticate to 22.214.171.1249 as demo-user
Response: WinRM::WinRMAuthorizationError
Hint: Make sure to prefix domain usernames with the correct domain name.
Hint: Local user names should be prefixed with computer name or IP address.
EXAMPLE: my_domain\user_namer
ERROR: WinRM::WinRMAuthorizationError: WinRM::WinRMAuthorizationError
Build step 'Execute Windows batch command' marked build as failure
Finished: FAILURE

Trying to figure out how to fix this
Answer: I was able to fix the issue
It was caused by my user (demo-user) not belonging to domain name that is allowed to connect from Chef to the Windows Server.
All I had to do was to get a user that was part of my organization domain name, replace demo-user with that user in my chef commands, and then run the Jenkins build again.
This time it worked fine.


Openssh - Allow root to access both sftp and ssh

Question: I want to configure sftp on my server to be accessed by root user.
I changed my configuration of /etc/ssh/sshd_config to:
PermitRootLogin yes
AuthorizedKeysFile  .ssh/authorized_keys
PermitEmptyPasswords yes
ChallengeResponseAuthentication no
Compression no
ClientAliveInterval 15
ClientAliveCountMax 4
#Other options are commented
[...]
Subsystem sftp /usr/libexec/sftp-server

Match user root
ChrootDirectory /
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp

It works and I can connect by sftp to my server, but now I can connect by ssh anymore. I got this message:
This service allows sftp connections only.
The same happen with Match group root
How can I configure sftp to allow root but keeping ssh too?

Update:
Commenting ForceCommand internal-sftp option ssh still works but I cannot connect by sftp.
sshd_config:
Subsystem   sftp    /usr/libexec/sftp-server
Match user root
ChrootDirectory /
X11Forwarding no
AllowTcpForwarding no
#ForceCommand internal-sftp

Error:
user@notebook:~$ sftp root@my_device
Warning: the ECDSA host key for 'my_device' differs from the key for the IP address 'xx.xx.xx.xx'
Offending key for IP in /home/myUser/.ssh/known_hosts:78
Matching host key in /home/myUer/.ssh/known_hosts:93
Are you sure you want to continue connecting (yes/no)? yes
Connection closed.
Connection closed

On the server side:
root@my_device:~# cat /var/log/auth.log | grep ssh
2024-01-17T19:25:21.659884+00:00 my_device sshd[30592]: Accepted none for root from xx.xx.xx.xx port 38024 ssh2
2024-01-17T19:25:21.881328+00:00 my_device sshd[30592]: Received disconnect from xx.xx.xx.xx port 38024:11: disconnected by user
2024-01-17T19:25:21.881997+00:00 my_device sshd[30592]: Disconnected from user root xx.xx.xx.xx port 38024

Note: If I also remove Subsystem   sftp    /usr/libexec/sftp-server as I got a different error when trying to connect by sftp:
subsystem request failed on channel 0
Comment: Can you please provide your running sshd config with `sshd -T`
Answer: The ForceCommand directive only allows root to use sftp, try commenting out that line.
Comment: @Baffer What error do you get? I replicated your settings without the `ForceCommand` line and it works fine for me. You might need to share the rest of your config file, and it also might be good to know what you're actually trying to achieve with these settings. If all you wanted is access with both ssh and sftp you didn't need the `Match user` block
Comment: Already done but didn't work. In that case, root can connect by ssh but not by sftp. I need both
Comment: @Baffer Also remove the susbsytem line, let it use the internal sftp server. You likely made an error in the path to that executeable
Comment: I updated the post with some test with `ForceCommand`. If `ForceCommand` is present, only sftp is allow. If not, only ssh is allow.

On the other hand, `Match user` doesn't seems to change anything if it's set or not (so I'll remove it). But with or without `Match user`, the behavior is the same and depends on `ForceCommand`
Comment: The file `/usr/libexec/sftp-server` doesn't exit. I don't even know why sftp works with my config
Comment: @Baffer That's strange indeed, did you copy that setting from somewhere online? That location isn't universal, for example mine is at `/usr/lib/ssh/sftp-server`. You could try something like `find / | grep sftp-server` to find yours
Answer: The OpenSSH man page sshd_config(5) describes this:

ForceCommand
Forces the execution of the command specified by ForceCommand, ignoring any command supplied by the client and ~/.ssh/rc if present. The command is invoked by using the user's login shell with the -c option. This applies to shell, command, or subsystem execution. It is most useful inside a Match block. The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. Specifying a command of internal-sftp will force the use of an in-process SFTP server that requires no support files when used with ChrootDirectory. The default is none.

As told here, your ForceCommand internal-sftp only allows SFTP.
Furthermore, PermitRootLogin yes is dangerous as it enables password authentication for root, and ChrootDirectory / is not really a limiting chroot jail at all. It is recommended to

use public key authentication for root or disable root login altogether
use sudo instead of direct root login
use public key authentication for any users having sudo privileges
use password for sudo (together with the previous it is effectively an MFA for the escalated privileges).

I keep reminding of these as Server Fault is for questions related to business environments and your current configuration does not demonstrate reasonable practices in this context.
Answer: You can try to run this ansible playbook which checks your ssh configuration and creates a secure ssh configuration.
https://github.com/dev-sec/ansible-collection-hardening/tree/master/roles/ssh_hardening
After running this You then only need to allow rootlogin in the sshd_config and then both ssh and sftp should work
Answer: Well, the problem here was that /usr/libexec/sftp-server doesn't exist in the server side. I added it in the image with a new Yocto build and then I was able to connect by ssh and sftp with root using the default config:
# override default of no subsystems
Subsystem   sftp    /usr/libexec/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#   X11Forwarding no
#   AllowTcpForwarding no
#   PermitTTY no
#   ForceCommand cvs server


Why is this URL PArameter not hiding this div with jQuery?

Question: I am attempting to animate a page div, if the URL has "?success=true" attached.
I have tried multiple methods, to no avail (this is currently placed in the footer).

And I am using it to affect:

Is there something I am missing?
Comment: No server side script to capture the $_GET?
Answer: You've got syntax errors in your if statement:
    if (getParameterByName("success") == "true") {
        $("#success-cover").hide();
    }

Comment: ROOKIE. ERROR.

THANK YOU.


Cannot find class in classpath

Question: I've been reading up on this error but am now confused. I'm trying to run my java test file from the win7 cmd line but am getting that dreaded error cannot find class in classpath.
The script runs fine as a testNG file inside the Eclipse IDE but not from the cmd line.
My classpath dump:
C:\lib\selenium-java-2.37.0.jar;
C:\lib\selenium-server-standalone-2.37.0.jar;
C:\EclipseIDE\ProteinBar\bin;
C:\EclipseIDE\ProteinBar\src\com\proteinbar\staging;
C:\TestNG;

My cmd line test string:
java -cp C:\lib\*;C:\EclipseIDE\ProteinBar\bin org.testng.TestNG DeleteBillingAddress.xml

Thanks for any help...
Comment: Which class is missing?
Comment: `java -cp` ignores/overrides your environment's `CLASSPATH`. You need to use one or the other.
Comment: This class is missing: com.proteinbar.staging.DeleteBillingAddress
Comment: Which would make perfect sense, since that's not on the supplied classpath.
Comment: @Brian - I added C:\EclipseIDE\ProteinBar\src\com\proteinbar\staging to the classpath but no success. Did I add that correctly?
Answer: it doesn't appear that the testng jars are on your classpath.  I'm guessing they live under c:/testng so you'll want to add something to your -cp reflecting that.
Comment: right.  and c:\testng is, in no form, on your classpath.  you have to include those jars on your classpath.  and they're not in c:\lib either, apparently, so that * entry won't grab them either.
Comment: The TestNG jars are located in c:\TestNG;
Comment: I added the testNG jar files to the classpath as c:\TestNG\\*.jar but I get the same results :-(
Comment: My classpath now looks like this:C:\lib\selenium-java-2.37.0.jar;
C:\lib\selenium-server-standalone-2.37.0.jar;
C:\EclipseIDE\ProteinBar\bin;
C:\EclipseIDE\ProteinBar\src\com\proteinbar\staging;
C:\TestNG\*.jar;
C:\lib\*;
C:\Users\rfresh\eclipse-standard-kepler-SR1-win32-x86_64\eclipse\plugins\org.testng.eclipse_188.8.131.5230914_0724\lib
Comment: I finally got it to work from the cmd line with this: java -cp C:\lib\*;C:\EclipseIDE\ProteinBar\bin org.testng.TestNG DeleteBillingAddress.xml -- I did make some classpath edits. My .java files are not in the \bin folder so I really don't know why this works?
Answer: You need to specify the jars individually, e.g.,
java -cp C:\lib\selenium-java-2.37.0.jar;C:\lib\selenium-server-standalone-2.37.0.jar;...
Comment: Not for the last 7 years you haven't. 1.6+ supports the `*` wildcard in the classpath for jar files. `C:\lib\*` picks up both of those jars.
Comment: I added c:\lib\* to the classpath but still the same error: Cannot find class in classpath: com.proteinbar.staging.AddNewAddress. Below is my .xml file that I'm trying to run:
Comment:

Cannot find class in classpath


Fabric js bounding box positioning issue

Question: Bounding box for some custom path is not positioned correctly. I am using fabricjs library please help me how to remove this bug. I am using the following code to generate the path.
var path = new fabric.Path('m138.31999,1l0,29.565c-75.13835,4.16908 -134.31995,48.17229 -134.31999,101.835c0,-9.67107 16.35202,-17.51999 36.5,-17.51999c20.14798,0 36.5,7.84892 36.5,17.51999c0,-9.67107 16.35202,-17.51999 36.5,-17.51999c9.59525,0 18.30284,1.83565 24.81999,4.745l0,144.17499c0,6.44742 -5.23262,11.68002 -11.67999,11.68002c-6.44734,0 -11.68,-5.2326 -11.68,-11.68002l0,-5.84l-23.36,0l0,5.84c0,19.34207 15.6979,35.04001 35.04,35.04001c19.34206,0 35.04001,-15.69794 35.04001,-35.04001l0,-144.17499c6.51714,-2.90935 15.22475,-4.745 24.81999,-4.745c20.14798,0 36.5,7.84892 36.5,17.51999c0,-9.67107 16.35202,-17.51999 36.5,-17.51999c20.14798,0 36.5,7.84892 36.5,17.51999c0,-53.66274 -59.18159,-97.66592 -134.31999,-101.835l0,-29.565l-23.36002,0z');
canvas.add(path);

Answer: You can move the bounding box to your object corner with this code:
path.pathOffset.x = 0;
path.pathOffset.y = 0;

Unfortunately, I couldn't find a way to resize it automatically. You can change bounding box size by path.width and path.height properties but it seems that Fabric will not compute it for you. Maybe you'll need to iterate over path points array to find min/max values for X and Y, so you can compute the BB size on your own.
Comment: `path.class.js` has private method `_parseDimensions` with the similar function, that returns object with calculated fields `left`, `top`, `width` and `height` based on the path commands. However, `left` and `top` are actually coordinates of the center rather than the top left corner.
Answer: This was a bug of the library with some beizer and arcs. Now, since 1.5.0, every known path is handled correctly.


Training a neural network on chess data

Question: I have been writing a chess engine with a friend and the engine itself is really good already (2700+ CCRL). We had the idea to use a neural network to have a better evaluation of positions.
Input to the network
because the output of the network greatly depends on which side has to move, we use the first half of the inputs to parse the position of who has to move and the second half for the opponent. In fact, we have for each piece and for each square an input which would result in 12x64 inputs. We had the idea to also include the opponent king position. So each side had 6x64 inputs and this for each square the opponent king can be -> 6x64x64. In total, this results in 12x64x64 binary input values where at maximum 32 are set.
Layers
The next layer consists of 64neurons where the first 32 neurons only accept inputs from the first half of the input features and the last 32 only accept inputs from the second half of the input features.
It follows a layer with 32 neurons fully connected and the output layer has only a single output.
Activation function
We use LeakyReLU at both hidden layers and a linear activation function at the output.
Training
Initially, I wanted to train the network on about 1 million positions yet this is taking ages. The position itself has a target value in the range of -20 to 20. I am using stochastic gradient descent using ADAM with a learning rate of 0.0001 and MSE as the loss function.
The problem I have is that this is taking a very very long time to even train those 1 million positions. The target is to later train on 300M positions.
I am not sure where I could improve the training progress.
Below are the graphs which show the training progress over 1000 iterations

The change for each iteration looks like this:

I hope someone could give me one or two hints on what I could improve in order to train the network faster. I am very happy for any advice!
Greetings,
Finn
Edit 1
As suggested, I should convert my network to keras. I am having problems getting the sparse input to run.
import keras
from keras.layers import Input, Concatenate, Dense, LeakyReLU
from keras.models import Model
from keras import backend as K
import numpy as np

# trainX1 = tf.SparseTensor(indices=[[0,0], [0,1]], values=[1, 2], dense_shape=[1,24576])
# trainX2 = tf.SparseTensor(indices=[[0,0], [0,1]], values=[1, 2], dense_shape=[1,24576])
#
# trainY = np.random.rand(1)

trainX1 = np.random.random((10000,24576))
trainX2 = np.random.random((10000,24576))

trainY = np.zeros((10000,1))

#input for player to move
activeInput = Input((64*64*6,))
inactiveInput = Input((64*64*6,))

denseActive = Dense(64)(activeInput)
denseInactive = Dense(64)(inactiveInput)

act1 = LeakyReLU(alpha=0.1)(denseActive)
act2 = LeakyReLU(alpha=0.1)(denseInactive)

concat_layer= Concatenate()([act1, act2])
dense1 = Dense(32)(concat_layer)

act3 = LeakyReLU(alpha=0.1)(dense1)

output = Dense(1, activation="linear")(act3)

model = Model(inputs=[activeInput, inactiveInput], outputs=output)
model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])

# print(model.summary())

print(model.fit([trainX1,trainX2], trainY, epochs=1))

If I use sparse=True for the Dense layer, it will throw some exceptions. I am happy if someone could help me creating sparse input vectors.
Comment: @MichaelM I'm saying they should implement it in Torch or similar.
Comment: What hardware is it running on and what do you mean by a "long time" ?
Comment: I implemented the code myself in c++. 1M forward iterations take about 1sec whereas 1M training iterations take about 15sec. I train on a single core on my AMD ryzen 3950x
Comment: Maybe just try it on Colab with GPU? Also, unless you know what you're doing and have enough time for optimizing the code, using ready software like TensorFlow or PyTorch would be more efficient.
Comment: I dont use a GPU. I wrote everything from scratch but I sort of know what I am doing.
I implemented full AVX2 support. I mean the speed itself really isnt the problem I think. The problem is more that its simply not converging as fast as it should
Comment: It looks like you may be able to increase the learning rate... `0.0001` seems awfully slow considering that your network is making significant downward progress... that should at least slightly improve your training speed.
Comment: So no GPU ? Are you using a c++ deep learning framework or have you coded it from scratch?  I would look at comparing it with a modest GPU
Comment: https://github.com/Luecx/Koivisto/tree/nnSearch/src_files/nn This is the code btw. the backprop has eta in it but its actually not used. the training stuff is inside data->Trainer.cpp
Comment: How fast **should** it converge on a single processor ?
Comment: That is a good question. Looking at some graphs of adam for other scenarios, it looks like 200 or 300 iterations should be enough. I mean obviously you cannot compare them like that
Comment: Yeah it's hard to compare like that, which is why I think you should give GPU a go - just to compare first.
Comment: @RobertLong: one cannot compare with GPU if the code is not implemented it GPU languages like CUDA...
Comment: What output training data are you using? Are you simulating full games?
Comment: I used my engine to generate a small test set with about 750k positions which has been evaluated with a depth 8 search. there was some discussion and the result is that a search with a larger depth would create too much noise. basically the network is so small that it wouldnt understand those hidden things
Comment: So I am only training on a single position -> eval depth 8 from the previous engine
Comment: "we use the first half of the inputs to parse the position" You aren't using the word "parse" correctly. You seem to mean "represent". Parsing means extracting meaning from a representation, not creating one.
Comment: @Acccumulation yes you are right. it was the first word that came to my mind. my bad :)
Answer: I think you need to consider running it on a GPU. Google Colab is free and Amazon AWS is very cheap. You seem to know what you are doing so you can probably get up and running with PyTorch very quickly. Once you compare the performance of the same network implemented on GPU vs your single processor setup, you will be in a better to position to know where to go next.
Comment: the problem is that simply putting it onto the gpu wont help most likely. the biggest problem here is the immense size of the input. I managed to handle the sparse input on the CPU and effectively only use about 1000 weights per iteration of the first layer. if I would use tensorflow or pytorch or sth like that, it wouldnt be able to understand that sparse input
Comment: Torch supports sparse tensors
Comment: Yes I did. the error started going up. both for sgd and adam
Comment: mhm i will have a look at it. thank you
Comment: No worries. Good luck, it's an interesting project!
Comment: I got Keras running with gpu support and was wondering how exactly this sparse type can be used in keras/tf.

If you dont mind, have a look at the edit i made :)
Comment: I was talking about Torch not TensorFlow but it should be available in TF. I will take a look when I get home
Comment: Thank you very much :). The thing is that i probably want to use some sort of data loader to eventually train on 300M datapoints which creates sparse inputs... I dont even know where I should start. I will probably try to get pytorch running
Comment: Regarding your edit, did you specify sparse for the dense and input layers? Unfortunately programming questions are off topic here !
Comment: Yes I did but I dont know how to set the matrices to sparse. I will probably transfer this specific question to stackoverflow. thank you for your help :)
Comment: No problem. Also try the tf discussion forum
Comment: I converted the data to keras.... it took about 300 iterations for the loss to go below 5 :)
Comment: Great !!! That's more than a 3 fold improvement. If it's exactly the same network architecture with the same loss, activations, learning rate etc then you must have a bug in your C++ code.  On the other hand, this kind of demonstrates why it's probably not a good idea to roll your own (though I'm very sure it's a great learning experience)
Comment: well its not clear what the reason is. i mean keras etc use a lot of tricks to speed up training. simply the fact that i dont need to give the learning rate says a lot...
Comment: i simply hope that when i transfer the weights, the output will be the same :)
Comment: I assume you tried increasing the learning rate in your code?
Answer: You could also try the CPU-friendly NNUE alternative. It is currently been developed for chess by the Stockfish team and seems to give good results. It is easy to use and train the networks, and it should be much easier than the hard-way. I've been working on the Stockfish team, and I think I could also help you with your engine if you wish (I'm also working on my own chess engine). Regards and good luck!
Comment: thats what we are trying :)
Comment: It would be amazing if you could help us! If you like, you can add me on discord: Luecx#0540
Comment: What language are you using for the engine?
Comment: C++. I also added AVX support
Comment: Okay, fine. Does it support UCI commands?
Comment: yes ofcourse :)

Training a neural network on chess data


How to access the published field in my PHP code?

Question: I am defining a datatype called slider
$nodes = node_load_multiple(array(), array('type' => 'slider'));
foreach($nodes as $slider):

and trying to iterate through each of them. I want to access the field which says if the content is publised or not. I tried this -
$slider->$status == 1

But this is not working.
Does anyone have a solution this problem?
Thanks
Comment: How php works isn't really on topic for this site. Perhaps the question could be moved to stack overflow?
Comment: As @Letharion, this is a PHP question. Drupal doesn't change the PHP syntax to allow `$object->$property`.
Answer: It is
$slider->status == 1

instead of
$slider->$status == 1

Answer: Try EntityFieldQuery to get al nids
 $query = new EntityFieldQuery();
 $result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'mycontenttype')
    ->execute();
 $nodes = node_load_multiple(array_keys($result['node']));
 foreach($nodes as $node){
  if($node->status == 1)
  drupal_set_message('node '.$node->title.' is Active');
 }


Extensions of number fields

Question: Let $L|K$ be an extension of number fields and consider the corresponding (integral) extension of ring of integers: $R_L|R_K$. Note that $R_L$ and $R_K$ are finitely generated over $\mathbb{Z}$, hence they are free $\mathbb{Z}$-modules. Then if $Q\subset R_L$ is a nonzero prime ideal, and we set $P:=Q\cap R_K$, then $R_L|Q$ is a finite field (being a quotient of $(\mathbb{Z}/p\mathbb{Z})^n$ if $R_L\cong\mathbb{Z}^n$ and $p\mathbb{Z}:=Q\cap\mathbb{Z}$). In particular, $(R_L|Q)|(R_K|P)$ is separable.
I can't understand the bold part, in particular when he says "a quotient of"
Comment: Finite integral domains are fields.
Answer: My best guess is that the author means the following.
You have probably proved earlier in the course that $R_L\cong\mathbb{Z}^n$ as an abelian group. Because $p\in Q$, and $Q$ is an ideal, it then follows that
$$
pR_L\subseteq Q\subset R_L.
$$
This implies that
$$
R_L/Q\cong (R_L/pR_L)/(Q/pR_L).
$$
But here $R/pR_L=(\mathbb{Z}^n)/p(\mathbb{Z}^n)=(\mathbb{Z}/p\mathbb{Z})^n,$ so we have just written the field $R_L/Q$ (it's a domain because $Q$ is prime, and as pointed out by Billy, it's then a field) as a quotient of $(\mathbb{Z}/p\mathbb{Z})^n$.

Extensions of number fields


Using a variable to access object member value

Question: I'm trying to access member values of the following class:
public class EditorialDateFormat
{
       public string en; <------ TRYING TO GET ITS VALUE
       public string fr; <------ OR THIS VALUE
       public string Default;<-- OR THIS ONE
 }
public class Params
{
      public string Template;
      public string MainTagID;
      public string[] NavigationFilters;
      public EditorialDateFormat EditorialDateFormat;
}
public class Site
{
      public string Name;
      public string CreationFolder;
      public Params Params;
      public string[] Feed;
      public string Endpoint;
      public string[] TargetDatabases;
}

I could do it easily like :
site.Params.EditorialDateFormat.en(for example) but "en" string is actually saved in a variable.
I tried the following code :
// Myvariable contains "en"
object c = GetPropValue(site.Params.EditorialDateFormat, MyVariable);

public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetMember(propName);
}

But it returns me a MemberInfo object without the member value
I would appreciate some help!
Thanks in advance
Comment: You´re almost there: you have to get the value for the obtained `MemberInfo` on the given instance of your class, something like : `GetMember(propName).GetValue(src, null)`.
Comment: Not sure but you want en value if null then fr and if that's also null then you want default value right?
Comment: Uttam Ughareja : yes that's my expected behaviour !
Answer: You want to read field (public instance field's value), that's why we put GetField:
//TODO: rename the method: it doesn't read property (Prop)
public static object GetPropValue(object src, string propName) {
  return src
    .GetType()
    .GetField(propName, BindingFlags.Public | BindingFlags.Instance)
    .GetValue(src);
}

Answer: public class EditorialDateFormat
{
    private string _en;

    public string en
    {
        get { return !string.IsNullOrEmpty(_en) ? _en : fr; }
        set { _en = value; }
    }
    private string _fr;

    public string fr
    {
        get { return !string.IsNullOrEmpty(_fr) ? fr : Default; }
        set { _en = value; }
    }

    public string Default { get; set; }
}

and you can use it like var c=site.Params.EditorialDateFormat.en
in elegant way
Comment: Thank you for your help!


HP 2920 switch - clear all memory

Question: I'm aware that HP 2920 switches have volatile and non-volatile memory. I've read parts of the manual and have found commands to erase the current custom default configuration, to erase the custom default configuration, and to erase all memory and zeroize the flash. The goal is to take a fully configured switch with lots of application-specific information and to clear all the data out to return it to its original, factory-default state. I've come up with the following steps and wanted to know (a) whether this is sufficient and (b) whether this is necessary to remove all non-factory-default data and settings from the switch:

Erase current startup config using, e.g., erase-startup-config.
Erase default startup config using, e.g., erase-default-config.
Erase and zeroize all user data, e.g., erase all zeroize.
Press Clear + Reset to reset the configs
Remove power to clear out the volatile memory (sufficient for our purposes)

In particular:

If you do step 4, do you need to do steps 1 and 2?
If you do step 3, do you need to do steps 1 and 2?
If all the steps are done exactly as outlined, are the contents of switch memory distinguishable from the contents of a factory default switch - i.e., at they different from the contents before you turned it on for the first time? (I mean, in known, deterministic ways. It seems clear to me that there might be lots of random differences that are uninteresting).

I think the answer to 3. might be that if you have updated the software, then the updates remain installed, but I think that is OK for our case. Are there any other issues?
Edit: For bonus points, is there some command/action I can take whose express purpose is to actually zeroize the whole non-volatile memory, including software and configs in addition to user data, and then some procedure for putting the factory image back onto it? Is this typical? Time to perform the procedure is less important than ease/simplicity.
Comment: What?!? What's the goal? Why isn't a reset enough? Have you tried anything yet?
Comment: @ewwhite The goal is to perform a series of commands that will ensure, to the greatest extent feasible, that the switch is returned to its initial, unconfigured, unused state as far as memory is concerned only. I have not tried this but am trying to understand how this would work at a conceptual level.
Comment: See below... from the product manual.
Answer: To execute the factory default reset on the switch, perform these steps:

Using pointed objects, simultaneously press both the Reset and Clearbuttons on the front of the switch.
Continue to press the Clear button while releasing the Reset button.3.When the Test LED begins to blink, release the Clear button.
  It takes approximately 25 seconds before the Test LED will begin to
  blink.

The switch will then complete its boot process and begin operating withits configuration restored to the factory default settings.
Comment: @Patrick87, to answer your question, it clears the configuration, including saved passwords, and resets to default config.  It doesn't  delete firmware.
Comment: Thanks for this. Does this clear and/or zeroize the non-config data? Does it have any effect on the software or does it leave that alone? I think the answers are no in both cases but I might not understand what the procedure is doing. I think I do understand that this (step 4 in my question) makes steps 1 and 2 unnecessary.
Comment: When I buy a used switch, I reset it to factory using the hardware method then upgrade firmware. That is all. But, HP ProCurve switches have a lifetime warranty. Give support a call to have them address your concerns.

HP 2920 switch - clear all memory


Checking if URL has changed for use within a session check

Question: The code below works to increase the counter for every page a visitor goes too however i'm needing to work out how to make it so it doesn't allow an increase in counts on the same page over one (to stop someone spamming refresh and increasing the view count). Is there a way to check if the URL has changed within a java servlet?
CODE
HttpSession session = request.getSession() ;    // Will create new
    session.setAttribute("timesLoggedIn", 0);
    session.setAttribute("pictureNames", null);
     // session.setAttribute("pictureNames", null);
    Integer accessCount = (Integer)session.getAttribute("timesLoggedIn") ;
    String pictureNames = request.getPathInfo();
    String pathName = (String)session.getAttribute("pictureNames");
    String id = session.getId();

    //start session
    //increment count by one
    //if count already implemented, don't implement.

    out.println(pathName);
      if (accessCount < 1 && pathName == null) {

           out.println("
This is your first visit!
");
           session.setAttribute("timesLoggedIn", 1);
           session.setAttribute("pictureNames", pictureNames);
             Utilities.IncreaseCount(out, pictureName);

        }

      out.println(pathName);

Comment: you are checking `pathName` for only `null` but not if it is changed?
Answer: You can get the current page path with the servlet request API, such as request.getPathInfo()
You could then use this to create a session attribute key unique to the page. If there would be characters in the page path that are not permitted to be part of a session attribute key then you could obviously replace the characters in the string. It would be up to you to determine whether you would want to also consider query parameters as unique pages, e.g. /page1?a=1 vs /page1?a=2
Then it would be trivial in your if/else to say if the key does not exist, put the value there with 1. If the key is already in the session, do not increment it, just read the value to display it.
Be mindful that if you do consider query params unique pages and this would have different keys for /page1?a=1 vs /page1?a=2 it could be potentially dangerous for memory consumption as a nasty use who figures this out could in theory write a script to request many different pages using unique query params which would slowly but surely fill the session with lots of small bit of data but could eventually over a sustained period of time be some sort of denial of service via polluting your session storage.
Comment: I've tried implementing your suggestion. However i'm unable to increment different pictures. My logic for checking if the path has changed must be wrong. Updated my OP with my current thinking
Comment: I'm not sure I follow correctly what the issue you're having now is. In the else block, I think you no longer want to add 1 to `i` because you actually have the value `1` in there. Alternatively, you need not store an int at all any more, you could perhaps put the value `null` in there and just test for the presence or absence of the key - if it's no there put the key, if it is just display "logged in once". What are you trying to do here, e.g. if I hit the URL `/pictures/1` and `/pictures/2` you want to track the fact I've seen that at least once?
Comment: I'm a little confused about why there are counters or the message "You have visited this page " + i + " times! " if you want `i` to always be at most 1? Either I load the page that I've never seen and it says i've been here 0 times or I have been here before and it says 1 even if i've been here 100 times?
Comment: I was just having the messages in for testing to try and help me understand. I'll update my OP with my now current thinking, it increments all the time. Yea to answer your question i want to track that you've hit both pages once, but i don't want you to be able to refresh your page and keep the view count on increasing. I want one view per page, per session


When does $(F,f): (X,A) \rightarrow (Y,B)$ induce isomorphisms on homology?

Question: Consider a map of topological pairs $(F,f): (X,A) \rightarrow (Y,B)$ consisting of a map $F: X \rightarrow Y$ and a map $f: A \rightarrow B$ such that $f$ is the restriction of $F$ from $A$ to $B$. We assume that $F$ and $f$ induce isomorphisms on all homology-modules. How can we show that also $(F,f)$ induces isomorphisms on all homology-modules? I guess one might be able to use functorial properties of the homology functor or some axioms like long exact sequence of a pair.
Answer: Hint: Use the long exact sequence induced on homology and the 5-lemma.
Comment: For what pairs?
Comment: For both. Both pairs $(X,A)$ and $(Y,B)$ have long exact sequences in homology. Write those as two rows, and connect then by vertical arrows which are the maps induced by $F,f$ and $(F,f).$ The diagram commutes by functoriality.


Is there a way of referencing the prior observation's values in SAS/SQL when defining a new variable?

Question: I have a table of repeat customers, and I want to add a flag for each customer id if it's been more than 30 days since the previous purchase. It's arranged by ID and ascending date.
CustomerID        Date
001               02/15/2022
001               03/01/2022
002               01/19/2022
002               02/11/2022
002               03/30/2022
...

I would want to end up with
CustomerID        Date           Flag
001               02/15/2022     N
001               03/01/2022     N
002               01/19/2022     N
002               02/11/2022     N
002               03/30/2022     Y
...

The only way I can think of doing this is by referencing the previous row. Here's the pseudo-code to illustrate what I mean.
IF (CUSTOMERID = PRIOR.CUSTOMERID) AND (DATE - PRIOR.DATE >= 30) THEN FLAG = 'Yes'

However, after looking around some, I'm unsure how to accomplish this in SAS, either in a data step or proc sql. I assume there's some way of saving the value of a previous row, but I'm not familiar with that.
Answer: That is what the LAG() function is for.  The LAG() function returns the value saved from the last time you called it.  So if you call it for every observation then the result is the value from the previous observation.  Just make sure not to skip running the LAG() function on some observation or else the returned value will NOT be the previous observation's value.
data want;
  set have;
  by customerid date;
  if not first.customerid and (date-30 )> lag(date) then flag='YES';
  else flag='NO';
run;

Results
       Customer
Obs       ID             Date    flag

 1       001       2022-02-15    NO
 2       001       2022-03-01    NO
 3       002       2022-01-19    NO
 4       002       2022-02-11    NO
 5       002       2022-03-30    YES

Comment: Thanks! I can't believe I never came across that before.


Ionic Android build throws warnings

Question: Whenever I build my project using Ionic it gives me 1000 of warnings. I have tried many things, changes in the proguard-rules.pro, but none of them seems to be working. I am not sure how to remove those warnings. Some of them are below.
Maybe this is program method 'org.xwalk.core.internal.InMemorySharedPreferences$InMemoryEditor { void apply(); }'
Note: android.support.v4.app.NotificationCompatJellybean accesses a declared field 'icon' dynamically
      Maybe this is program field 'android.support.v4.app.NotificationCompat$Action { int icon; }'
      Maybe this is program field 'android.support.v7.appcompat.R$attr { int icon; }'
      Maybe this is program field 'android.support.v7.appcompat.R$id { int icon; }'
      Maybe this is program field 'com.digits.sdk.android.R$attr { int icon; }'
      Maybe this is program field 'com.digits.sdk.android.R$id { int icon; }'
      Maybe this is program field 'com.facebook.android.R$attr { int icon; }'
      Maybe this is program field 'com.facebook.android.R$id { int icon; }'
      Maybe this is program field 'com.twitter.sdk.android.R$attr { int icon; }'
      Maybe this is program field 'com.twitter.sdk.android.R$id { int icon; }'
      Maybe this is program field 'dk.nodes.ncore.R$attr { int icon; }'
      Maybe this is program field 'dk.nodes.ncore.R$id { int icon; }'
      Maybe this is program field 'io.fabric.sdk.android.services.settings.AppRequestData { io.fabric.sdk.android.services.settings.IconRequest icon; }'
      Maybe this is program field 'io.fabric.sdk.android.services.settings.AppSettingsData { io.fabric.sdk.android.services.settings.AppIconSettingsData icon; }'
Note: android.support.v4.app.NotificationCompatJellybean accesses a declared field 'title' dynamically
      Maybe this is program field 'android.support.v4.app.NotificationCompat$Action { java.lang.CharSequence title; }'
      Maybe this is program field 'android.support.v7.appcompat.R$attr { int title; }'
      Maybe this is program field 'android.support.v7.appcompat.R$id { int title; }'
      Maybe this is program field 'com.digits.sdk.android.R$attr { int title; }'
      Maybe this is program field 'com.digits.sdk.android.R$id { int title; }'
      Maybe this is program method 'com.google.android.gms.internal.zzso { com.google.android.gms.internal.zzsu clone(); }'
      Maybe this is program method 'com.google.android.gms.internal.zzso { java.lang.Object clone(); }'
      Maybe this is program method 'com.google.android.gms.internal.zzsq { java.lang.Object clone(); }'
      Maybe this is program method 'com.google.android.gms.internal.zzsr { java.lang.Object clone(); }'
      Maybe this is program method 'com.google.android.gms.internal.zzsu { com.google.android.gms.internal.zzsu clone(); }'
      Maybe this is program method 'com.google.android.gms.internal.zzsu { java.lang.Object clone(); }'
      Maybe this is program method 'com.google.gson.internal.Excluder { com.google.gson.internal.Excluder clone(); }'
      Maybe this is program method 'com.google.gson.internal.Excluder { java.lang.Object clone(); }'
      Maybe this is program method 'com.google.protobuf.AbstractMessage$Builder { com.google.protobuf.AbstractMessage$Builder clone(); }'
      Maybe this is program method 'com.google.protobuf.AbstractMessage$Builder { com.google.protobuf.AbstractMessageLite$Builder clone(); }'
      Maybe this is program method 'com.google.protobuf.AbstractMessage$Builder { com.google.protobuf.MessageLite$Builder clone(); }'
      Maybe this is program method 'com.google.protobuf.AbstractMessage$Builder { java.lang.Object clone(); }'
      Maybe this is program method 'com.google.protobuf.AbstractMessage$Builder { com.google.protobuf.Message$Builder clone(); }'

And my 'progaurd-rules.pro' as follows
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes Exceptions
-verbose

-dontoptimize
-dontpreverify

-dontnote **

-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepattributes EnclosingMethod
-keepattributes *Annotation*
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class com.google.vending.licensing.ILicensingService
-keep public class com.android.vending.licensing.ILicensingService
-keep public class * extends android.support.v4.app.Fragment
-keep public class * extends android.app.Fragment
-keep public class com.google.** {*; }
-keep public class com.facebook.** {*; }

-ignorewarnings

-dontwarn android.support.v7.**
-keep class android.support.v7.internal.** { *; }
-keep interface android.support.v7.internal.** { *; }
-keep class android.support.v7.** { *; }

-dontwarn android.support.v7.appcompat.** {*;}
-dontwarn com.squareup.okhttp.**
-keep interface android.support.v7.appcompat.** { *; }
-keep class android.support.v7.appcompat.** { *; }

-keep class com.facebook.** {
   *;
}

-dontwarn org.apache.commons.lang3.time.**
-dontwarn dk.nodes.widgets.buttons.**
-dontwarn net.hockeyapp.android.tasks.**

-dontobfuscate
-dontpreverify

-dontnote android.support.v4.app.NotificationCompatJellybean
-dontwarn android.support.v4.app.NotificationCompatJellybean

-dontnote org.apache.commons.lang3.ObjectUtils
-dontwarn org.apache.commons.lang3.ObjectUtils

-dontnote com.google.protobuf.Descriptors$FileDescriptor
-dontwarn com.google.protobuf.Descriptors$FileDescriptor

-dontwarn class * extends com.google.protobuf.GeneratedMessageLite.** { *; }
-dontwarn interface * extends com.google.protobuf.GeneratedMessageLite.** { *; }
-dontnote com.google.protobuf.**
-dontnote com.google.android.**

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

 -keepclassmembers public class * extends android.view.View {
  void set*(***);
  *** get*();
 }

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-keepclassmembers class **.R$* {
  public static <fields>;
  <fields>;
}

-libraryjars libs
#-injars libs/AudienceNetwork.jar
#-injars libs/google-api-client-1.18.0-rc.jar
#-injars libs/google-api-client-android-1.18.0-rc.jar
#-injars libs/google-http-client-android-1.18.0-rc.jar

 # The official support library.
-keep class android.support.v4.** { *; }
-keepclassmembers class android.support.v4.** {
    *;
 }
-keep interface android.support.v4.** { *; }
-keep class android.support.v7.** { *; }
-keepclassmembers class android.support.v7.** {
    *;
 }
-keep interface android.support.v7.** { *; }

# Library JARs.
-keep class com.facebook.** {
   *;
}
-keepclassmembers class com.facebook.** {
    *;
 }

When I build on Android Studio, I dont get warnings. But on terminal, 'ionic android build' I get warnings, that too only on first time after 'ionic state reset'. Those warnings are because of list of Notes displaying.
Reading library jar [/Users/neelavijayakumar/Library/Android/sdk/build-tools/23.0.2/lib/shrinkedAndroid.jar]
Note: android.support.v4.view.ViewPager calls 'Class.getAnnotation'
Note: com.facebook.model.GraphObject$Factory calls 'Method.getAnnotation'
Note: com.facebook.model.GraphObject$Factory$GraphObjectProxy calls 'Method.getAnnotation'
Note: com.google.ads.mediation.MediationServerParameters calls 'Field.getAnnotation'
Note: com.google.android.gms.internal.zzamp calls 'Field.getAnnotation'
Note: com.google.android.gms.internal.zzant calls 'Class.getAnnotation'
Note: com.google.android.gms.internal.zzant calls 'Field.getAnnotation'
Note: com.google.android.gms.internal.zzaoe calls 'Class.getAnnotation'
Note: com.google.android.gms.internal.zzaoj calls 'Field.getAnnotation'
Note: com.google.android.gms.internal.zzaon$zza calls 'Field.getAnnotation'
Note: com.google.gson.FieldAttributes calls 'Field.getAnnotation'
Note: com.google.gson.FieldAttributes calls 'Field.getAnnotations'
Note: com.google.gson.internal.Excluder calls 'Field.getAnnotation'
Note: com.google.gson.internal.Excluder calls 'Class.getAnnotation'
Note: com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory calls 'Class.getAnnotation'
Note: com.google.gson.internal.bind.ReflectiveTypeAdapterFactory calls 'Field.getAnnotation'
Note: com.google.gson.internal.bind.TypeAdapters$EnumTypeAdapter calls 'Field.getAnnotation'
Note: com.pushwoosh.internal.request.RequestManager$1 calls 'Class.getAnnotation'
Note: io.fabric.sdk.android.Fabric calls 'Class.getAnnotation'
Note: io.fabric.sdk.android.Kit calls 'Class.getAnnotation'
Note: org.xwalk.core.extension.JsStubGenerator calls 'Method.getParameterAnnotations'
Note: retrofit.RestMethodInfo calls 'Method.getAnnotations'
Note: retrofit.RestMethodInfo calls 'Class.getAnnotations'
Note: retrofit.RestMethodInfo calls 'Method.getParameterAnnotations'
Note: acidhax.cordova.chromecast.Chromecast calls 'Method.getGenericParameterTypes'
Note: android.support.v4.app.NotificationCompatJellybean calls 'Field.getType'
Note: com.digits.sdk.android.ActivityClassManagerFactory$ThemeAttributes calls 'Field.getType'
Note: com.digits.sdk.android.ThemeUtils calls 'Field.getType'
Note: com.facebook.model.GraphObject$Factory$GraphObjectProxy calls 'Method.getGenericReturnType'
Note: com.google.android.gms.internal.zzanr calls 'Class.getGenericInterfaces'
Note: com.google.android.gms.internal.zzanr calls 'Class.getGenericSuperclass'
Note: com.google.android.gms.internal.zzanr calls 'Class.getTypeParameters'
Note: com.google.android.gms.internal.zzant calls 'Field.getType'
Note: com.google.android.gms.internal.zzaoj calls 'Class.getGenericSuperclass'
Note: com.google.android.gms.internal.zzaoj calls 'Field.getGenericType'
Note: com.google.android.gms.internal.zzaoj calls 'Field.getType'
Note: com.google.android.gms.internal.zzaoo calls 'Class.getGenericSuperclass'
Note: com.google.android.gms.internal.zzapd calls 'Field.getType'
Note: com.google.gson.FieldAttributes calls 'Field.getGenericType'
Note: com.google.gson.FieldAttributes calls 'Field.getType'

For the first time, there are many getting updated, from second time, all are up-to-date so I dont get warnings. This is detailed analysis on the issue. Also I forgot to mention that these are from AAR libraries that I use in my ionic project. Please help me on this.
Comment: Try ionic platform rm android , ionic platform add andrid
Comment: yes, tried.. Doesnt work..
Comment: @Neela Welcome back. Though i m not an expert in this, i guess setting -dontnote option setting in proguard should help you supress the warning. Check out these links - http://proguard.sourceforge.net/manual/usage.html#dontnote http://stackoverflow.com/questions/6068902/how-to-suppress-maybe-this-is-program-method-warnings-from-proguard Let me know if it helps
Comment: @Gandhi yes I have tried them. Now I have a doubt, I am making changes in "proguard-rules.pro", is that right? What is "proguard.cfg"? Am I need to make changes there? I dont have this file in my project.
Comment: @Neela As i said earlier, i m not an expert in this as i dont have hands on experience in this. Check this out - http://stackoverflow.com/questions/20514881/where-do-i-find-proguard-cfg-in-my-project I guess making change in the property file is good enough
Comment: @Neela Did you managed to suppress those warnings?
Comment: @Gandhi it doesn't work
Comment: @Neela Could you post what exactly u tried out?
Comment: @Gandhi, I have editted the question, please check..
Comment: I suggest you reinstall IONIC on your computer to avoid all these Errors
Comment: I have tried in 2 or 3 computer, In all I am getting these errors..
Comment: @Neela wil check on this Neela. But you gotta help me out in testing as I dont use ionic. Take care
Comment: @Gandhi Okay. Also warnings are from AAR libraries that I used in the project..
Comment: Thanks guys, I got it work..
Comment: @Neela Glad you cracked it Neela, But -dontnote attribute is still applicable rite?
Comment: yes.. proguard settings are applicable still..
Answer: Fixed all warnings, I am sure I have tried this earlier, but now it works.
Changed Gradle version on the ionic as "2.0.0"
And gradle wrapper distribution url as "http\://services.gradle.org/distributions/gradle-2.10-all.zip"
it just works..
Answer: To add up to the answer, proguard setting too is still required.
-dontnote option setting in proguard should help suppress the warnings. For more info on dontnote option, please check out official doc.

Ionic Android build throws warnings


Diferença entre teste de aceitação e teste de sistema

Question: Na prática, qual a diferença entre o teste de aceitação e teste de sistema? E como fazê-los?
Answer: Teste de Validação

O software está montado como um pacote e a validação do mesmo é realizada através de uma série de testes caixa preta
finalidade:

demonstrar a conformidade aos requisitos funcionais e de desempenho
verificar se a documentação está correta

duas possibilidades:

aceito
não está totalmente de acordo com os requisitos: negociar com o usuário

engloba o Teste de Aceitação: realizado pelo próprio usuário
no caso de software desenvolvido para vários usuários:

teste alfa: realizado pelo usuário no ambiente do desenvolvedor
teste beta: realizado pelo usuário em seu próprio ambiente

Teste de Sistema

considera o software dentro do seu ambiente mais amplo (todos os aspectos de interação com ele, como outro hardware, software, pessoas, etc.)
corresponde a uma série de testes que tem por objetivo verificar se todos os elementos do sistema foram integrados adequadamente e realizam corretamente suas funções

teste de segurança: tem por objetivo verificar se todos os mecanismos de proteção protegem realmente o software de acessos indevidos.
teste de estresse: tem por objetivo confrontar os programas com situações anormais de freqüência, volume ou recursos em quantidade.
teste de desempenho: tem por objetivo testar o tempo de resposta do sistema e é aplicado, geralmente, para sistemas de tempo real

Teste Unitário

concentra-se no módulo
utiliza a técnica de teste estrutural
pode ser realizado em paralelo para vários módulos
aspectos considerados
Geralmente, um programa não é um módulo único, mas formado de diversos módulos que, para efeito do teste de unidade devem ser testados separadamente

Teste de Integração

constrói-se, de uma forma sistemática, a estrutura do programa realizando, ao mesmo tempo, testes para detectar erros de interface
embora os módulos, depois do teste de unidade, funcionem corretamente de forma isolada, o teste de integração é necessário pois quando colocados juntos, várias situações inesperadas podem acontecer

Fonte: Resumo de aula de Engenharia de Software.

Como faze-los, vai depender de varias variáveis, como, tipo de tecnologia, ambiente de controle de projeto, equipe de homologação, capacitação técnica,  entre outros fatores.
Comment: Pesquisei um pouco mais sobre e achei alguns dados para ajudar a complementar: Teste de sistema testa os requisitos técnicos e a especificação do sistema. O de aceitação, por sua vez, assim como vc bem citou, valida o sistema de acordo com a necessidade do usuário final.
Comment: Trabalho em uma empresa que os processo são bem definidos, mas não posso passar os detalhes nem a ordem, mas faz diferença fazer os 2 além do *teste de integração*, que acho muito importante, se quiser posso complementar a resposta sobre o teste de integração...
Comment: Se não fosse abusar da sua boa vontade, seria interessante. Complementaria bastante o assunto.
Comment: Adicionei teste de integração e teste unitário ;)


Register a domain with NIC

Question: I recently bought a .es domain for the purpose of creating a domain hack.  I registered the domain with esreg.com (SANE Systems, apparently).  My card was charged, but the domain is listed as not registered.  I have not yet been able to get in contact with them.
Their website seems to have a small form to register the site and to specify the nameservers, but when I fill it out it says "You have to specify the NIC handles first."  I don't know how to get those.  They have for example a box that says "Owner" with an example of SK86-ESNIC-F4.  I have another website so I may have this information, but I don't know how to get it.
Comment: Tried contacting their support?
Comment: @LucasKauffman yes, their phone number doesn't work and they haven't replied to my email (only been a day) so maybe it's a scam
Comment: were you able to solve this issue? I registered a .es name today esreg.com and am experiencing the same issue. Emailed them but no answer yet. Thanks.
Comment: @xbora I was unable to get in contact with them either by email or phone.  I called my bank and they reverted the charge.  I would have liked the domain, but I'm not paying for nothing either.  Let me know if you can get it to work.
Comment: I believe it is scam. I've tried to register a domain with them, they would not do that, neither would they answer email, and the phone on the site is a phone of a shop of some sort.
Answer: The DNS authority in Spain is NIC.ES
They maintain a list of authoried regirstrars
I am afraid, esreg.com is not listed here so be careful and take your measures, it could be an untrusted site. I have asked directly to NIC.ES to confirm this issue, awaiting for response. Will update with their response.
Comment: Just confirmed by NIC.ES. esreg.com is not an authorized registrar!

Register a domain with NIC


Will it break SOLID principle?

Question: I'm trying to write a generic method which get called and based on object type it should set indicators.

Will it break any solid principles?
Is there a better way of doing it?

I was working on one of the features where I have 3 lines of business like Car, Van and Bike.
I have IVehicle interface which is handling all the common implementation between the 3 lines of business.
Now, I have to set two common indicator Car and Van but for Bike, I want to set some different indicator. I want to create an object of this class once but it handle based on type of line business.
If write this method like this will it break any SOLID principles? If it is incorrect, can you please suggest an alternative?
Note: INDICATOR_B should be true in all LOB
function populateIndicator() {
  if (_motorObject typeis Car or _motorObject typeis entity.Van) {
    _motorObject.INDICATOR_A = true
  }

  if (_motorObject typeis Bike) {
    _motorObject.INDICATOR_C = true
  }

  _motorObject.INDICATOR_B = true
}

Comment: This should be a polymorphic method *in* IVehicle.
Comment: whatever programming language this is, it does not look like java
Comment: edited the language but added java for better reach @GyroGearless
Comment: is _motorObject passed in any way as parameter to this object or the class owning the method?
Comment: @DavidGuida _motorobject is coming from abstract class. I have created a abstract on top of my implementation class.
Comment: sorry, but the design is not clear. Would you mind updating your original post and include more details?
Comment: also, without entering too much into the reasoning, you could evaluate replacing all those boolean INDICATOR_X with a single enum.
Answer: Short version: use polymorphism to implement populateIndicator method.
Checking types in the base class breaks Liskove substitution principle. If you have a duplicate code for assigning like  _motorObject.INDICATOR_B = true you can use template method pattern.
abstract class VehicleBase{

   public void populateIndicator(){

      conceretePopulateIndicator();
      // common code for all derived classes
      _motorObject.INDICATOR_B = true;
   }

   protected abstract void conceretePopulateIndicator();

}

public class Bike: VehicleBase{

    protected override void conceretePopulateIndicator(){
        _motorObject.INDICATOR_C = true
    }
}

this design won't break any rules.
Answer: You can use rule factory here. You can define three rules. Each rule will accept type which will have one of two values Four Wheeler/Two Wheeler. You can set indicator accordingly in rule. It will not break SOLID principle.
Answer: Yes it will break open-closed principle.
You can create interface with function populateIndicator() and default implementation _motorObject.INDICATOR_B = true And other classes Car, Van, Bike in you case should implement interface and override default method in their own way in case it applicable

Will it break SOLID principle?


What is a qualified/unqualified name in Python?

Question: In Python: what is a "qualified name" or "unqualified name"?
I've seen it mentioned a couple of times, but no explanation as to what it is.
Answer: It is the path from top-level module down to the object itself.
See PEP 3155, Qualified name for classes and functions.
If you have a nested package named foo.bar.baz with a class Spam, the method ham on that class will have a fully qualified name of foo.bar.baz.Spam.ham. ham is the unqualified name.
A qualified name lets you re-import the exact same object, provided it is not an object that is private to a local (function) namespace.
Comment: Classes are objects; modules (objects too!) have a qualified name, that is what you use when you use an absolute import. Qualified names are not as formal as you think they are; the terms are not that ridgidly defined.
Comment: Are objects the only thing that have qualified names? Or can classes also have them? (Or is a class an object as well?)
Comment: Does a module have a qualified name?
Comment: And what is the difference (if any) between a qualified name and a fully qualified name?


How to keep program running without exiting when wrong option is chosen?

Question: I am creating a library management system. I have a few menus for which the user can select an option but when the wrong option is chosen it should display an error message and ask the user to select another option. Currently after the user selects an option which is not available, the program exits.
This is some of my code:
while(1)
    {
        int mainSelect;
        int studentOption;
        int dvdOption;
        int bookOption;
        char name[30];

        // Ask the user to select an option
        cout << "****************************************************" << endl;
        cout << "*******************  Main Menu  ********************" << endl;
        cout << "****************************************************" << endl;
        cout << "*                                                  *" << endl;
        cout << "* PROGRAM          DESCRIPTION                     *" << endl;
        cout << "* ------------------------------------------------ *" << endl;
        cout << "*                                                  *" << endl;
        cout << "*   1              DVD                             *" << endl;
        cout << "*                                                  *" << endl;
        cout << "*   2              Books                           *" << endl;
        cout << "*                                                  *" << endl;
        cout << "*   3              Students                        *" << endl;
        cout << "*                                                  *" << endl;
        cout << "*   4              EXIT                            *" << endl;
        cout << "*                                                  *" << endl;
        cout << "* ------------------------------------------------ *" << endl;
        cout << "*                                                  *" << endl;
        cout << "****************************************************" << endl;

        // Read user selection
        cin.getline( name, 80);
        mainSelect = name[0];

        // Switch statement to select between the options
        switch (mainSelect)
        {
          case '1':
            break;
          case '2':
            break;
          case '3':
            break;
          case '4':
            exit(0);
            break;
          case '6':
            cout << "Invalid selection!" << endl;
            break;
          default:
            cout<<"Incorrect selection. Please select from the given options." <<endl;

        }

Also I have several options such as Add a new book, delete a book. When the user selects add a new book option and after adding a book the program exits. How I can make it after the user adds a book the system goes back to the menu.
This is some of my code showing the switch case for the Book menu:
else if (mainSelect == '2')
        {
            cout << "****************************************************" << endl;
            cout << "*******************  Book Menu  ********************" << endl;
            cout << "****************************************************" << endl;
            cout << "*                                                  *" << endl;
            cout << "* PROGRAM          DESCRIPTION                     *" << endl;
            cout << "* ------------------------------------------------ *" << endl;
            cout << "*                                                  *" << endl;
            cout << "*   1              Issue a book                    *" << endl;
            cout << "*                                                  *" << endl;
            cout << "*   2              Return a book                   *" << endl;
            cout << "*                                                  *" << endl;
            cout << "*   3              Add a new book                  *" << endl;
            cout << "*                                                  *" << endl;
            cout << "*   4              Update a book                   *" << endl;
            cout << "*                                                  *" << endl;
            cout << "*   5              Delete a book                   *" << endl;
            cout << "*                                                  *" << endl;
            cout << "*   6              Search for a book               *" << endl;
            cout << "*                                                  *" << endl;
            cout << "*   7              Show all books                  *" << endl;
            cout << "*                                                  *" << endl;
            cout << "*   8              Return to the previous Menu     *" << endl;
            cout << "*                                                  *" << endl;
            cout << "*   9              Exit                            *" << endl;
            cout << "*                                                  *" << endl;
            cout << "* ------------------------------------------------ *" << endl;
            cout << "*                                                  *" << endl;
            cout << "****************************************************" << endl;

            cin.getline(name, 80);
            bookOption = name[0];

            switch(bookOption)
            {
              case '1':
                book2.issueBook();
                break;
              case '2':
                book2.returnBook();
                break;
              case '3':
                book2.insertBook();
                break;
              case '4':
                book2.updateBook();
                break;
              case '5':
                book2.deleteBook();
                break;
              case '6':
                char barcode[6];
                cout<<"Enter The book barcode: " <<endl;
                cin>>barcode;
                book2.searchBook(barcode);
                break;
              case '7':
                book2.showallBooks();
                break;
              case '8':
                break;
              case '9':
                exit(0);
                break;
             }
          }

Answer: bool processed = false;
while(!processed)
{
    cin.getline( name, 80);
    mainSelect = name[0];
    switch(mainSelect)
    {
        case '1':
            processed = true;
            break;
            ...
        case '5':
        default:
            processed = false;
            break;
    }
}

Comment: Thanks that works but with 1 problem when I enter 6 or 7 or 8 it displays error message and waits for user selection but when I enter 10 or 11 it goes to the DVD menu.
Comment: don't forget to set `processed = true;` when it is processed. Or you can use false logic and set `processed = true;` immediately after entering while-loop. And set to false in default or error cases.
Answer: You can add a default statement in you switch's body.
...
label:

cin.getline( name, 80);
mainSelect = name[0];

switch(){
    .....
    default: goto label;
    ......
}
......

Comment: When I do that it just keeps on typing "Incorrect selection. Please select from the given options." repeatedly.
Comment: You should move `label:` to the line where you read the input symbol
`label:
cin.getline( name, 80);`
Comment: But `goto` should be never used. Unless there are no other options (which I never saw)
Comment: @teivaz what other ways can I do it?
Answer: All I would do is put the main menu in a do while loop, as long as the user doesn't select exit (4) then the program should execute as many times as the user needs.
do {
//main menu
//switch statement that lets them add books, etc.
} while (mainSelect != 4)

This is how I did it for a similar project of mine.


REST post plugin broken from Drupal 8.4.5 to 8.5

Question: I just upgraded my Drupal installation from 8.4.5 to 8.5
Now my REST plugin is not getting any data on POST.
My client post like this:
POST /rgptemprest?_format=hal_json HTTP/1.1
Host: 10.10.10.1:443
Authorization: Basic ****REPLACED******
Content-Type: application/hal+json
Accept: application/hal+json
User-Agent: ESP8266
Connection: close
Content-Length: 108

{"netcard":"997800940160","DS18B20":"28ADBCE70800008C","battery":"2952","temperature":"23.375","rssi":"-33"}

On my drupal server I have a plugin
with this code (not complete)
public function post(array $data = [])
{
    var_dump($data);
    if (!empty($data))
    {

....
And here I see the difference
on 8.4.5 it show an array of the data sent:
array(5) {
  ["netcard"]=>
  string(12) "997800940160"
  ["DS18B20"]=>
  string(16) "28ADBCE70800008C"
  ["battery"]=>
  string(4) "2952"
  ["temperature"]=>
  string(6) "23.500"
  ["rssi"]=>
  string(3) "-33"
}

but on 8.5 it's empty
array(0) {
}

What has changed between 8.4.5 and 8.5? And what do I need to change?
Comment: I do not think you are doing anything wrong. When I look at the Request content the data is there. It is just not being transferred to the post() parameter for some reason.
Answer: Wim Leers found the answer:
Change this:
public function post(array $data = [])

to:
public function post(array $data)

Comment: This worked for me as well.