In the example in [over.ass]/2 why does *bptr = dobj2; call D::operator=(const B&)?

Question: [over.ass]/2
I can understand why bptr->operator=(dobj2); calls D& operator= (const B&) and why dobj1 = dobj2; calls the implicitly-declared D::operator=(const D&). But I'm not so sure about *bptr = dobj2;.
Example:
struct B {
    virtual int operator= (int);
    virtual B& operator= (const B&);
};
struct D : B {
    virtual int operator= (int);
    virtual D& operator= (const B&);
};

D dobj1;
D dobj2;
B* bptr = &dobj1;
void f() {
    bptr->operator=(99); // calls D::operator=(int)
    *bptr = 99; // ditto
    bptr->operator=(dobj2); // calls D::operator=(const B&)
    *bptr = dobj2; // ditto
    dobj1 = dobj2; // calls implicitly-declared D::operator=(const D&)
}

Comment: Yes, but you are never going to need one in real code. Especially if we cannot tell what it does, and how it interferes with the compiler generated default assignment operators.
Comment: Perhaps you should make clear that a) the code is abstracted from the standard, and b) what you expect the code to do, and why you don't understand what it does.
Comment: `*bptr = dobj2;` is just another, more compact way to write `bptr->operator=(dobj2);` I don't quite grasp the nature of your confusion.
Comment: **[over.match.oper]/2** and in particular Table 12 "Relationship between operator and function call notation"
Comment: Virtual assignment operators are *extremely* unusual. Think Unicorns.
Comment: But they are virtual functions just like any other virtual function.
Comment: If you could show me this, using a standard quote I would appreciate.
Answer: Polymorphism happens when you have a Base pointer or reference to a derived instance and calls a virtual member function on it.
In your examples
bptr->operator=(99); // calls D::operator=(int)
bptr->operator=(dobj2); // calls D::operator=(const B&)

A base pointer points to a derived instance is calling the virtual functions => Invoke polymorphism => the derived versions will be called.
*bptr = 99; // ditto
*bptr = dobj2; // ditto

This is simply
(*bptr).operator=(99);
(*bptr).operator=(dobj2);

Or a base reference to a derived instance is calling the virtual functions => Invoke polymorphism => the derived versions will be called.
dobj1 = dobj2; // calls implicitly-declared D::operator=(const D&)

No more polymorphism since the caller(dobj1) is not a (base) reference/pointer. Invoked the D::operator=(const D&) generated by the compiler, which also calls
the operator = of the base class automatically.
virtual B& operator= (const B&);

Comment: I think I have found the answer in the Standard: [expr.unary.op]/1(http://eel.is/c++draft/expr.unary.op#1)
Comment: @curiousguy this is really helpful!! Thanks for the clarification!!
Comment: But how do you show that `*bptr` is a D object and not a B object? I know that's very basic, but I'm exhausted to try to find this in the spec by myself. Could you help me with that?
Comment: See this explanation https://stackoverflow.com/a/3082442/9281750. You can treat *bptr as a B& to an D object. Thus, it invokes the polymorphism.
Comment: I would like to find in the Standard something similar to what sbi said in his answer: `*ptr doesn't result in an object, but in a reference Base& to the object`., so far to no avail.
Comment: In other words, I'd like to know where in the Standard does it say that the dynamic type of the `*bptr` object is D, not B? As I said before I'm very tired. I must get some sleep.
Comment: *bptr gets what is pointed to by bptr, and what sits there is a D. The static type should be a B(&), but why would its dynamic type be a B when the object is a D...As others have mentioned, it's just the same/another way of writing bptr->operator=(dobj2); Sorry if this is still confusing, and I also do not find any helpful documentations.
Comment: @Ayrosa "_in a reference Base&_" This would be incorrect: in C++ **expressions never have reference type**. Expression can have types mentioning a reference somewhere, like "pointer to function type returning a reference to int", just not reference type. The expression `*bptr` just has type `B`.
Comment: @gchen "_The static type should be a B(&),_" The concept of reference just doesn't work that way in the C++ type system, or in C type system (which doesn't have references, but which is similar just more restricted); there is in fact a common C/C++ basic principle of the type system which is grounded on expressions have both a type and a lvalue-ness or rvalue vs. lvalue (or something). When something is usually a rvalue but something is declared with a reference type, it's a lvalue.
Answer:
But I'm not so sure about *bptr = dobj2;.

From over.match.oper#tab:over.rel.op.func
Both:
*bptr = dobj2; // ditto
dobj1 = dobj2; // calls implicitly-declared D::operator=(const D&)

are the same in context but represented differently as:
Expression:
a=b

As member function:
(a).operator= (b)


Should we validate max length on string fields?

Question: We have a validation in our application limiting user first and last name length to 255 characters. Is there any technical reason we ought to be doing this? I'm wondering if there is maybe any security concern or risk we put ourselves at by not limiting the length of strings. We're using Postgres  text columns.
Comment: If this is a business constraint, then yes you should reflect that in a database constraint as well. If you are indexing the columns you probably should limit the length as well. Note that there is no optimization whatsoever for column defined as `varchar(255)` over a column defined as `varchar(260)` or `varchar(301)` - that `255` is a left-over "magic number" that does have any performance impact
Comment: Related: https://stackoverflow.com/questions/8295131
Answer: Text = variable unlimited length.. If you put limiter why don't use varchar(255)?
For security concern and performance put limiter are good. If your database file heavy and if someone spams to your text, the data type exceeds 8 KB.. That will put heavy in your db and for worst scenario it can Break Down..
EDIT :
As Documentation says:

If you desire to store long strings with no specific upper limit, use
  text or character varying without a length specifier, rather than
  making up an arbitrary length limit.

Back to your original question "Should we validate max length on string fields"?
When see documentation said.. It would be better you make as Varchar(255) rather than Varchar without length specifier and do limiter in application side
And for performance:

Long strings are compressed by the system automatically, so the
  physical requirement on disk might be less. Very long values are also
  stored in background tables so that they do not interfere with rapid
  access to shorter column values.

I will say great for Postgresql :)
Comment: The PostgreSQL docs actually suggest that `text` is no less performant, though, if you need something variable length, and may be better since they don't need to check the length before storing a value. See the Tip here: https://www.postgresql.org/docs/10/datatype-character.html
Comment: @lobati yes.. I am already read that.. about performance which is great `postgresql`.. And said `If you desire to store long strings with no specific upper limit, use text or character varying without a length specifier, rather than making up an arbitrary length limit.`..
Comment: I can't see how you could "break down" the database by supplying long strings.
Comment: Yes.. I want to remove that @a_horse_with_no_name but if i remove the first argument i show i think that's not good.. That's just my speculation.. If i am wrong you can dv me.. :)


Inserting well over 100,000 records into SQLite

Question: I have a database that needs to be updated periodically.  My employer wants to keep a base instance of it in MS Access, and update one in a local SQLite table.
I've been able to grab all of the data out of the MS Access table (into XML), but when I try to insert it into the SQLite table, I get the error that there are too many terms in the compound select statement.
I know that SQLite limit compound select inserts to 500, but this database is over 150,000 rows.  I'm at a loss for how to get the data moved over.
Anyone have any thoughts?
Here is the code that I was trying to use:
var sqlItem:String="INSERT INTO items (itemID,barcode,desc,brandNum,size,units,multQty,multPrice,price,brand,cat01,catSub,cost,srp,lastPriceChangeDate,lastScanDate,addDate,chgDate) ";
for each(var i:XML in itemList.item){
    sqlItem=sqlItem+"SELECT "+
    parseInt(i.itemID,10)+","+
    parseInt(i.barcode,10)+","+
    "\""+i.description+"\","+
    parseInt(i.brandNum,10)+","+
    "\""+i.size+"\","+
    "\""+i.units+"\","+
    parseInt(i.multQty,10)+","+
    "\""+i.multPrice+"\","+
    "\""+i.price+"\","+
    "\""+i.brand+"\","+
    "\""+i.cat01+"\","+
    "\""+i.catSub+"\","+
    "\""+i.cost+"\","+
    "\""+i.srp+"\","+
    "\""+i.lastPriceChangeDate+"\","+
    "\""+i.lastScanDate+"\","+
    "\""+i.addDate+"\","+
    "\""+i.chgDate+"\""+
    " UNION ";
}
sqlItem=sqlItem.substring(0,sqlItem.length-7);
itemStmt.text=sqlItem;
try{
    itemStmt.execute();
}catch(error:SQLError){
    trace("Update USER Database - ERROR: "+error.detailID +" - "+error.details );
}

Here is an example of the XML that I am reading into the database:
<items>
    <item>
        <itemID>1234</itemID>
        <barcode>01111111111111</barcode>
        <description>Product Description</description>
        <brandNum>1</brandNum>
        <size>1</size>
        <units>oz.</units>
        <multQty>1</multQty>
        <multPrice>0.85</multPrice>
        <price>0.85</price>
        <brand>Product Brand</brand>
        <cat01>Product Category</cat01>
        <catSub>(none)</catSub>
        <cost>0.10</cost>
        <srp>0.95</srp>
        <lastPriceChangeDate>1/9/2009 3:32:29 PM</lastPriceChangeDate>
        <lastScanDate>1/9/2009 3:32:29 PM<lastScanDate>
        <addDate/>1/9/2009 3:32:29 PM<addDate/>
        <chgDate>1/9/2009 3:32:29 PM</chgDate>
    </item>
    <item>
        <itemID>1234</itemID>
        <barcode>01111111111111</barcode>
        <description>Product Description</description>
        <brandNum>1</brandNum>
        <size>1</size>
        <units>oz.</units>
        <multQty>1</multQty>
        <multPrice>0.85</multPrice>
        <price>0.85</price>
        <brand>Product Brand</brand>
        <cat01>Product Category</cat01>
        <catSub>(none)</catSub>
        <cost>0.10</cost>
        <srp>0.95</srp>
        <lastPriceChangeDate>1/9/2009 3:32:29 PM</lastPriceChangeDate>
        <lastScanDate>1/9/2009 3:32:29 PM<lastScanDate>
        <addDate/>1/9/2009 3:32:29 PM<addDate/>
        <chgDate>1/9/2009 3:32:29 PM</chgDate>
    </item>
</items>

Comment: Once you get an XMLListCollection of your item Elements; just use a for loop and increment the counter variable, like this: counter+= 500 in each iteration .  That counter is, in essence, the first element of the insert statement.
Comment: IS this as simple as "Loop over the source data with a step of 500"?
Comment: It probably could be, but I'm not sure how I could loop through the XML data every 500 records.  I had thought about trying something like that, but I was not successful at getting it for loop properly...
Comment: Thanks Flextras, that worked...  I tried something similar, but couldn't get it to work, yesterday.  I just stuck a counter inside the for each loop to execute the query every 495 records.  Thanks for the assist...
Answer: Try this solution it works!!! I have tested this solution even in Web Sql DB based on sqlite
select sqlite_version()
3.6.19
INSERT INTO items (val)
select * from
(select 1  val  union all
 select 2   val union all
 select 3   val union all
 select 4   val union all
 ...
 select 500 val
)
union all
select * from
(select 501  val    union all
 select 502 val union all
 select 503 val union all
 select 504 val union all
 ...
 select 1000    val
)
union all
select * from
(select 1001  val   union all
 select 1002    val union all
 select 1003    val union all
 select 1004    val union all
 ...
 select 1500    val
)
...


Infinitely many primes p that are not congruent to 1 mod 5

Question: Argue that there are infinitely many primes p that are not congruent to 1 modulo 5.
I find this confusing.  Is this saying $p_n \not\equiv 1 \pmod{5}$?
To start off I tried some examples.
$3 \not\equiv 1 \pmod{5}$
$5 \not\equiv 1 \pmod{5}$
$7 \not\equiv 1 \pmod{5}$
$11 \equiv 1 \pmod{5}$
$13 \not\equiv 1 \pmod{5}$
$17 \not\equiv 1 \pmod{5}$...
If this is what the question is asking I've come to the conclusion that this is true.   Either way, I've got no clue how to write this as a proof.
Comment: Surely $11 \equiv 1 \bmod{5}$.
Comment: Maybe this is like using a steam-hammer to crack nuts, but you can derive it from this theorem: http://en.wikipedia.org/wiki/Dirichlet%27s_theorem_on_arithmetic_progressions
Comment: @lhf Wow.  That was foolish of me.  Thank's for pointing that out.
Answer: You can follow the Euclid proof that there are an infinite number of primes.  Assume there are a finite number of primes not congruent to $1 \pmod 5$.  Multiply them all except $2$ together to get $N \equiv 0 \pmod 5$.  Consider the factors of $N+2$, which is odd and $\equiv 2 \pmod 5$.  It cannot be divisible by any prime on the list, as it has remainder $2$ when divided by them.  If it is prime, we have exhibited a prime $\not \equiv 1 \pmod 5$ that is not on the list.  If it is not prime, it must have a factor that is $\not \equiv 1 \pmod 5$ because the product of primes $\equiv 1 \pmod 5$ is still $\equiv 1 \pmod 5$
Comment: Well we can discard the prime $2$ and consider only odd primes, it doesn't change the outcome of the theorem.
Comment: I don't think you can get away easily by adding $2$ or $3$ because they ARE divisible by primes that are not $1 \bmod 5$.
Comment: @fretty I second that. I don't immediately see how to deal with 2 and 3.
Comment: You would have to show that this number is not a perfect power of the number you added.
Comment: @fretty still don't see how this is enough. What if it is a product of the number I added and several other primes that are 1 mod 5?
Comment: I think there is also a problem with this number being divisible by $5$.
Comment: @Dan Shved: That is not a problem, the contradiction comes from $p_i |2$ or $p_i|3$ for some $i$. You thus have to show that the constructed number is NOT JUST divisible by such a prime.
Comment: My advice is to prove something stronger using Ross' advice. Prove that there are infinitely many primes congruent to $4 \bmod 5$.
Comment: @fretty Could you expand on that (about powers of 2)? I took the product $N$ of all the primes who are not congruent to 1 (mod 5). Now I am looking at the number $N+2$, which is congruent to 2 (mod 5). Then I should look at the prime factors of $N+2$. And what do I do about them, how do I proceed?
Comment: Well the way the usual proof goes is that you want there to exist a prime factor of N+2 that is not $1 \bmod 5$, then it must be one of the primes on your finite list and so divides $2$. The "and so it divides 2" bit is usually the contradiction but here your prime could actually be 2 for all you know!
Comment: Oh but I have been silly because we may assume N+2 to be odd!
Comment: It's actually even.
Comment: @fretty OK, that seems to work.
Comment: @fretty:  right you are.  I have updated it.
Comment: $N+2$ might actually be $1$ ($\bmod$ $5$).
Comment: @WimC:  no, because $N \equiv 0 \pmod 5$ as 5 is a prime.
Comment: @RossMillikan: fair enough.
Comment: @Ross I think you should add further details to the proof. I cannot tell which way you intend it to be completed.
Comment: @BillDubuque:  is this what you were thinking?
Answer: Hint $\rm\ \ 5n^2\!-n\: $ has a larger set of prime factors $\rm\not\equiv 1\ mod\ 5\:$ than does $\rm\:n.$
Comment: This uses $\rm\:5n\!-\!1\:$ (vs. Ross' $\rm\:5n\!+\!2)\:$ to get a new prime $\rm\not\equiv 1\pmod 5\ \ $


Pegando valores do array

Question: Tenho o seguinte array:
array(2) {
  [0]=>
  array(2) {
    ["username"]=>
    string(6) "User01"
    ["quant"]=>
    string(1) "6"
  }
  [1]=>
  array(2) {
    ["username"]=>
    string(5) "Teste"
    ["quant"]=>
    string(1) "3"
  }
 [2]=>
  array(2) {
    ["username"]=>
    string(5) "xxXxx"
    ["quant"]=>
    string(1) "5"
  }
}

Como faço para pegar todos os campos "username" e listar, "User01, Teste, xxXxx"
Achei uma funçao que lista somente pelo id do array:
  $resultado[0][username];
  echo $resultado;
  User01

So imprimi o valor definido la[0], mas quero que imprima todos os username.
Aqui esta o code completo, mas so imprimi o ulitmo regitro.
$sql = 'SELECT username, COUNT(*) AS quant FROM acessos WHERE hora > :hora GROUP BY username';
$statement = $pdo->prepare($sql);
$statement->bindValue(":hora", date('H:i:s', strtotime('-1 minutes')));
$statement->execute();
$resultado = $statement->fetchAll(PDO::FETCH_ASSOC);

//var_dump($resultado);
foreach($resultado as $item){
    $dados = $item["username"];
}
 echo "-> " . $dados;
 -> xxXxx

Comment: Se você leu minha resposta, deve ter percebido que o `echo` tem que ficar **dentro do _loop_**.
Comment: Abra outra pergunta com este problema específico, por favor. Aliás, se a resposta solucionou seu problema, você pode marcá-la usando o **✓** no lado esquerdo da resposta.
Comment: Funcinou certo, so queria saber qual formatação pra ficar "User01, Teste, xxXxx" Obrigado pela paciencia :)
Answer: Faça um loop pra percorrer todos os itens do array mais externo.
foreach($array as $item){
    echo $item["username"] . PHP_EOL;
}

Veja funcionando no repl.it.

Pegando valores do array


Cauchy-Riemann conditions implied by harmonicity and orthogonal gradients?

Question: If I have two functions $\eta:\mathbb{R}^2\to\mathbb{R}$ and $\xi:\mathbb{R}^2\to\mathbb{R}$ for which the following relations hold:
$$
\begin{align}
\left( \frac{\partial\xi}{\partial x} \right)^2 + \left( \frac{\partial\xi}{\partial y} \right)^2 &= \left( \frac{\partial\eta}{\partial x} \right)^2 + \left( \frac{\partial\eta}{\partial y}\right)^2 \neq 0\,,\\
\frac{\partial^2\xi}{\partial x^2} + \frac{\partial^2\xi}{\partial y^2} &= \frac{\partial^2\eta}{\partial x^2} + \frac{\partial^2\eta}{\partial y^2} = 0\,,\\
\frac{\partial\xi}{\partial x}\frac{\partial\eta}{\partial x} + \frac{\partial\xi}{\partial y}\frac{\partial\eta}{\partial y} &= 0\,.
\end{align}$$
Do these conditions imply that these two functions satisfy Cauchy-Riemann conditions?
$$
\begin{align}
\frac{\partial\xi}{\partial x} &= \frac{\partial\eta}{\partial y}\,,\\
\frac{\partial\xi}{\partial y} &= -\frac{\partial\eta}{\partial x}\,.
\end{align}
$$
If so, how to show that? If not, is there some simple condition that would need to be added?
Comment: Note that if $u$ is real harmonic and $v$ is a harmonic conjugate, $-v$ is also orthogonal in the sense above while not changing the equality of the sum of squares of $v_x^2+v_y^2=u_x^2+u_y^2$; the relations above imply that for any $w$ harmonic satisfying them instead of $\pm v$, one has $w_x^2=v_x^2, w_y^2=v_y^2$ and the signs of the solutions match in both equations; since the common zero set of $v_x=v_y=0$ is discrete (zero set of nonconstant entire function), it follows that indeed $w=v+C$ or $w=-v+C$ globally; so one needs an extra condition that separates $v$ from $-v$
Comment: @Conrad I am not sure that I understand. If $v$ is a harmonic conjugate, then already one assumes that the C-R conditions are satisfied because the resultant $f(z) = u + iv$ needs to be holomorphic or not? Also, in the first condition, are you saying that it implies that $u_x^2=v_x^2$ and $u_y^2=v_y^2$?
Comment: The point is that $-v$ (which doesn't satisfy C-R) works too and only those two $v,-v$ work (up to additive constants)
Comment: @Conrad Why does $v$ work or how do the conditions imply that? I do not understand your statement that one needs to have $w_x^2=v_x^2,\, w_y^2=v_y^2$. What I do not see is that if you have the orthogonality condition and Laplace equations for $u$ and $v$ how it implies that $u_x^2 = v_x^2$ and $u_y^2=v_y^2$ (which at least I think is that you are saying).
Comment: posted as an answer to make things clear
Answer: A proof for the statement that it $u,w$ are real harmonic and satisfy the two conditions above:
$u_x^2+u_y^2=w_x^2+w_y^2$ (and not identically zero) and $u_xw_x+u_yw_y=0$ then if $v$ is a harmonic conjugate of $u$ we have $w=v+C$ or $w=-v+C$ and conversely those functions work, so one needs an extra condition on $w$ to ensure it is a harmonic conjugate and not a negative of such, for the C-R to hold wr $u,w$.
First, we note that by C-R if $w= \pm v+C$ the identities work.
Then taking $v$ a conjugate of $u$ and substituting the C-R equations in the orthogonality relation, we get $w_xv_y=v_xw_y$ while also $v_x^2+v_y^2=w_x^2+w_y^2$
But now assume at a point $w_y(z) \ne 0$ then it follows that $v_y(z) \ne 0$ (otherwise we must have $v_x(z)=0$ but then $w_x^2(z)+w_y^2(z)=0$ contradicting $w_y(z) \ne 0$) so we get at $z$:
$w_x^2/w_y^2=v_x^2/v_y^2$ or adding $1$ to each side $(w_x^2+w_y^2)/w_y^2=(v_x^2+v_y^2)/v_y^2$ and since the numerators are equal and non zero, we get $w_y^2(z)=v_y^2(z)$ so $w_y = \pm v_y$
If $w_y(z)=0$ then automatically $v_y(z)=0$ (since if it would not, then $w_x(z)=0$ and then the sum of squares is zero etc) so the equality holds everywhere.
By the same reasoning $w_x= \pm v_x$ everywhere and of course, if we are at a non-zero value of both $v_x, v_y$ the signs must coincide which means that $w_y=v_y$ or $w_y=-v_y$ on any connected component of the complement of $v_x=0$ (set being same with $w_x=0$ by the above, while the common zeroes of $v_x,v_y$ are discrete of course as they are zeroes of a non-constant analytic function $(u+iv)'$); but now $w_y+v_y$ is a real harmonic function and same with $w_y-v_y$ so if either is zero on any open set, it is zero in the plane, hence we must have the same sign everywhere and then the same holds for $w_x,v_x$ and we are done as we get that either $w=v+C$ or $w=-v+C$


Criar um índice pesquisando parte do texto apenas

Question: Gostaria de criar um índice pesquisando apenas parte do texto.
x <- c(4, 1, 6, "ab", 2, 1, "aa")

which(x == "a")

No vetor acima, por exemplo, gostaria que o retorno fosse
[1] 4 7

Ou seja, retornar todas as linhas que contém a letra "a", independente se tiver mais alguma coisa, linha ou letras.
Comment: Benvindo ao StackOverflow em Português!
Experimente utilizar grep("a", x) e grepl("a", x)
Answer: Como já indicado nos comentários, grep e suas variantes servem para isso:
grep("a", x)
#> [1] 4 7

A opção value mostra os valores:
grep("a", x, value = TRUE)
#> [1] "ab" "aa"

Use grepl para retornar um vetor lógico. Veja a ajuda para expressões regulares (?regex) se precisar de padrões mais elaborados.


How to replace an XML node via python

Question: I am new in python and I have a - maybe - stupid problem with XML files (yep, I've tried to google the solution but without results).
I have to write a program which will replace/switch two things, so first of all, here is the XML data, it looks like this:
<data='qwerty'>
    <name_it>some_name</name_it>
</data>

<next_data='next_qwerty'>
    <name_it>another_name</name_it>
</next_data>

<next_next_data>
...
</next_next_data>
<next_xyz_data>...
etc.

How in python i could change some_name to be in data=''?
So it should be like this:
<data='some_name'>                            #changed from 'qwerty' to some_name
    <name_it>some_name</name_it>
</data>

<next_data='another_name'>                    #changed from 'next_qwerty' to another_name
    <name_it>another_name</name_it>
</next_data>

If it's a stupid question, sorry about that, but I truly googled it and I cannot find a solution.
UPDATE:
Here is the few lines of python code that I wrote:
from xml_file import data

new=""

f = io.StringIO(data)  # data loading
for r in f:
    row = r.rstrip()
    if 'name_it' in row:
        change = row[row.index('name_it')] # maybe kind of len() or something
    if "<data>" in row and change:
        idx = row.index("<data>") + 6
        new += row[:idx] + change + "name_it=\n"
        change = ""
    else:
        new += row + "\n" # new line

And here is true XML data:
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="Setup">
    <testcase classname="Configuration" name="xxx">
        <data>abc_qwe</data>                       #change_me_to_"xxx"
    </testcase>
    <testcase classname="Configuration" name="yyy">
        <data>xyzzzz</data>                        #change_me_to_"yyy"
    </testcase>
</testsuite>

There are many of the  signs.
Just <data>...</data> name should be in name="..."
Alright, so here are the content of files.
First of all I am generating CSV file:
Type,Name,Request Count,Failure Count,Median Response Time,Average Response Time,Min Response Time,Max Response Time,Average Content Size,Requests/s,Failures/s,50%,66%,75%,80%,90%,95%,98%,99%,99.9%,99.99%,99.999%,100%
POST,---ON START---LOGIN,33,0,2023.709774017334,2037.008133801547,2023.709774017334,2058.631658554077,6587.515151515152,0.24352046353820625,0.0,2000,2000,2000,2000,2100,2100,2100,2100,2100,2100,2100,2100
GET,Aggregations,15,0,4,5.305735270182292,3.652334213256836,11.571884155273438,6174.2,0.11069111979009376,0.0,4,5,7,7,9,12,12,12,12,12,12,12
GET,Alarms,5,0,5,4.584074020385742,3.754138946533203,5.759000778198242,6173.8,0.03689703993003125,0.0,5,5,5,6,6,6,6,6,6,6,6,6
GET,Analysis Templates,16,0,7,7.806003093719482,3.8690567016601562,13.520479202270508,6174.625,0.11807052777610001,0.0,9,11,11,11,12,14,14,14,14,14,14,14
GET,Boiler Efficiency,15,0,6,6.464735666910808,3.6771297454833984,15.489578247070312,6174.2,0.11069111979009376,0.0,6,6,8,11,11,15,15,15,15,15,15,15
GET,Configuration,14,0,5,6.087354251316616,3.6630630493164062,12.647390365600586,6174.428571428572,0.1033117118040875,0.0,5,6,8,11,11,13,13,13,13,13,13,13

Then, I want to change it to be a XML:
import _csv
from locust_script import methods_count
with open('locust_stats.csv') as f, open('locus_statistics.csv', 'w') as out:
    for line in f:
        if not line.isspace():
            print(line.strip())
            out.write(line)

stats = open('locus_statistics.csv')
csv_f = _csv.reader(stats)
data = []
for row in csv_f:
    data.append(row)

def convert_row(row, methods):
    case_name = methods[0]
    del methods[0]

    return """
            <testcase classname="test_perf" name="%s">
                <Type>%s</Type>
                <Name>%s</Name>
                <Request_Count>%s</Request_Count>
                <Failure_Count>%s</Failure_Count>
                <Median_Response_Time>%s</Median_Response_Time>
            </testcase>""" % (case_name, row[0], row[1], row[2], row[3], row[4])
report_save = open('parsed.xml', 'w')
case_name = methods_count()
report_save.write("<testsuite name='performance'>"+''.join([convert_row(row, case_name) for row in data[1:1000]])+"</testsuite>")
report_save.close()

Finally, I want to have parsed XML, so as I wrote above, I have trying to use this kind of script:

from xml_file import data

new=""

f = io.StringIO(data)  # data loading
for r in f:
    row = r.rstrip()
    if 'name_it' in row:
        change = row[row.index('name_it')] # maybe kind of len() or something
    if "<data>" in row and change:
        idx = row.index("<data>") + 6
        new += row[:idx] + change + "name_it=\n"
        change = ""
    else:
        new += row + "\n" # new line

So my intention is here - i think :) -:
            <testcase classname="test_perf" name="%s">
                <Type>%s</Type>
                <Name>%s</Name>

name=""
should be the same as <Name> HERE </Name>
Comment: start by sharing 1) A valid xml document 2) python code that shows what you did so far
Comment: I think XML structure it's not necessarly in here. I've updated my question post with python code.
Comment: You can do it using XML parsing. If you will share a valid XML doc - I will be able to guide you.
Comment: Here you go, I've putted in few lines of junit report :)
Answer: Below:
import xml.etree.ElementTree as ET

xml = '''<testsuite name="Setup">
    <testcase classname="Configuration" name="xxx">
        <data>abc_qwe</data>
    </testcase>
    <testcase classname="Configuration" name="yyy">
        <data>xyzzzz</data>
    </testcase>
</testsuite>'''

root = ET.fromstring(xml)
test_cases = root.findall('.//testcase')
for test_case in test_cases:
    test_case.find('./data').text = test_case.attrib['name']

ET.dump(root)

output
<testsuite name="Setup">
    <testcase classname="Configuration" name="xxx">
        <data>xxx</data>
    </testcase>
    <testcase classname="Configuration" name="yyy">
        <data>yyy</data>
    </testcase>
</testsuite>

The other way (set the value of the name attribute with the text of data)
import xml.etree.ElementTree as ET

xml = '''<testsuite name="Setup">
    <testcase classname="Configuration" name="xxx">
        <data>data_1</data>
    </testcase>
    <testcase classname="Configuration" name="yyy">
        <data>data_2</data>
    </testcase>
</testsuite>'''

root = ET.fromstring(xml)
test_cases = root.findall('.//testcase')
for test_case in test_cases:
    test_case.attrib['name'] = test_case.find('./data').text

ET.dump(root)

Comment: I see the point, but what if I have 1000 testcases? Maybe some iteration over them? Thank you for the solution.
Comment: As you can see, the code does not care if you have 2 testcases or 1000. If  my solution helps - feel free to vote up.
Comment: You are ofcourse right, but what's about this iteration in `new_values` list?
If we will have 1000 values I need to add their names manually so there is no point here :/
Check this out:
`new_values=[1,2,3,4,5,1231231,avasvas,qweeqw,123123526354,34342342...n]`
Comment: Only you (or the logic of your software) can tell the logic of replacing the values. Try to explain the logic of the replacement and maybe there is a smart way to do it.
Comment: Updated one more time. Sorry for the mess
Comment: So data should be the same as the value of the name attribute?
Comment: That's right. Excelly.
When you see these:
```

new_val_1
```
`new_val_1` should be in `name=` attr
Comment: one more thing, how to do it vice versa?
I mean - now we have  named from testcase name=...,
So how i need to modificate your script to testcase name=...from ?
I've tried something like that but it is not working:
```
root = ET.fromstring(xml)
test_cases = root.findall('./data')
for test_case in test_cases:
    test_case.find('.//testcase').text = test_case.attrib['name']
```
Comment: Now you want to change the value of  name attribute according to the text of data?
Comment: Yes, that's right. How to make a modification? I am quite new in XML parsing :/
Comment: One, and the last question.
I want to grab some data from another file and assign it to `xml=` variable, how to make it happen?
I was trying to do it like this, but receiving IObuffer err:
```
import xml.etree.ElementTree as ET

with open('report.xml', 'rb') as xml:
    root = ET.fromstring(xml).read()
    test_cases = root.findall('.//testcase')
    for test_case in test_cases:
        test_case.attrib['name'] = test_case.find('./data').text

ET.dump(root)
```
Comment: Read a file: see https://docs.python.org/3/library/xml.etree.elementtree.html?highlight=elementtree#module-xml.etree.ElementTree  `import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()`

How to replace an XML node via python


Good upper bound on ratio of binomial coefficients

Question: What is the asymptotic behavior of $n/2+k/2 \choose k$/$n\choose k$ for $k\le n/2$. Can we show that it goes down (sub)exponential in $k$ i.e. $n/2+k/2 \choose k$/$n\choose k$ $\le c^{-k^{\epsilon}}$ for some fixed constant $c>1$ and $\epsilon>0$? For $k\le n/2$, we can upperbound $n/2+k/2 \choose k$/$n\choose k$ by $\frac{3n/4 \choose k}{n \choose k}$, can we get a (sub)exponential in $-k$ upper bound on $\frac{3n/4 \choose k}{n \choose k}$? Thanks.
Comment: standard approximations and numerical experiments suggest that the right hand side decreases sub-exponentially
Comment: @kodlu is there a good estimate for the decrease, like say $c^{-k^{\epsilon}}$ for some small $\epsilon$? What if we look at the ratio of $\frac{3n/4 \choose k}{n \choose k}$, can we give a good upper bound on this?
Comment: @user1131274 Do you mean (constants) $c, \epsilon$ are independent of $n, k$?
Answer: $$\frac{{n/2+k/2 \choose k}}{{n \choose k}} =\prod_{j=0}^{k-1} \frac{L-j}{n-j} \tag1$$
where $L=n/2+k/2 < n$
Now, the factors inside the product are decreasing. Hence we get the upper bound
$ (L/n)^k=c^{-k}$
with $c=2n/(n+k)=\frac{2}{1+t}$ where $t=k/n$
For the record, the (first order) Stirling approxmation gives
$$\frac{{n/2+k/2 \choose k}}{{n \choose k}} \approx (1-t^2)^{n/2} \left(  \frac{1+t}{4(1-t)} \right)^{k/2} $$
Edited:
I tighter bound can be found be bouding each term in $(1)$. I get
$$\frac{{n/2+k/2 \choose k}}{{n \choose k}} \le d^{-k}$$
with
$$d = \frac{2 }{1+t} \exp\left( \frac{(t-1/n)(1-t)}{2 (1+t)} \right) \approx \frac{2 }{1+t} \exp\left( \frac{t(1-t)}{2 (1+t)}\right) $$
Answer: Using the gamma function$$A=\frac{\binom{\frac{k+n}{2}}{k}}{\binom{n}{k}}=2^{n-k}\frac{ \Gamma \left(\frac{n-k+1}{2} \right) \Gamma \left(\frac{n+k+2}{2}
   \right)}{\sqrt{\pi } \,\Gamma (n+1)}$$ Assuming $n\gg k$, take logarithms and use Stirling approximation to obtain
$$\log(A)=-k \log(2)+\frac{k (k+1)}{2 n}\Bigg[ 1-\frac{1}{2 n}+\frac{k (k+1)}{6 n^2}-\frac{k^2+k-1}{4
   n^3}+O\left(\frac{1}{n^4}\right)\Bigg]$$ which gives good bounds since alternating.
Using $n=25$ and $k=10$, this truncated series gives
$$\log(A) \sim \frac{2078153}{937500}-10 \log (2)=-4.71478$$ to be compared to the exact value
$$\log(A)=-\log \left(\frac{2097152}{18879}\right)=-4.71029$$ which, for $A$, corresponds to a relative error of $0.45$%.
Comment: Thanks. I only know that $k\le n/2$ and want a good upper bound on the ratio. I was thinking of bounding the ratio with $\frac{3n/4 \choose k}{n \choose k}$ and then upper bounding $\frac{3n/4 \choose k}{n \choose k}$ with $c^{-k^{\epsilon}}$ for some fixed small constant $\epsilon$. A bound of $c^{-k^{\epsilon}}$ would be sufficient for my need. Can we get such a bound? Thanks again.
Answer: Following @leonbloy, you can get an explicit bound in terms of $k$ as follows. Note that $\frac{L-j}{n-j}=1-\frac{n-L}{n-j}$. Then, using the estimate $1-x\le e^{-x}$ which holds for all positive $x$ we get an estimate of the form
$$
e^{-\sum_{j=0}^{k-1} \frac{n-L}{n-j}}.
$$
A very rough bound that you can use here now is just noting that $\frac{n-L}{n-j}\ge \frac{n-L}{n} = \frac{n/2-k/2}{n}= \frac{1}{2}-\frac{k}{2n}\ge \frac{1}{4}$ where in the last inequality we have used that $n\ge 2k$. Hence, we have the following bound
$$
\frac{\binom{n/2+k/2}{k}}{\binom{n}{k}}\le e^{-\sum_{j=0}^{k-1} \frac{1}{4}}=e^{-k/4}.
$$
Comment: $\frac{n-L}{n-j}\ge \frac{n-L}{n-(k-1)}$ should be $\frac{n-L}{n-j}\le \frac{n-L}{n-(k-1)}$?
Comment: That's totally true, thanks!, I have just fixed it


binary, hexadecimal to decimal conversion.

Question: I've one point that couldn't wrap in my mind when we talk about (binary, octal, hex) to decimal conversions?
For example, to convert binary 011 to decimal we multiply each bits starting from the LSB by the power of 2.
$011 = (1*2^{0})+(1*2^{1})+(0*2^{2}) = 3$
octal to decimal $356 (base 8) = (6*8^{0})+(5*8^{1})+(3*8^{2}) = 238$
same thing for hex to decimal.
Here is my question, there is no such thing related to decimal for converting those numbers to decimal. So how could multiplying by their base starting from LSB convert it to decimal. That doesn't make sense.
Comment: see [this](https://math.stackexchange.com/questions/1262109/why-do-we-divide-or-multiply-by-2-when-converting-binary) might help. Also please use mathjax.
Answer:
Writing a number in base two means writing it as a weighted sum of powers of two: $a_0 2^0 + a_1 2^1 + a_2 2^2 + a_3 2^3 + \ldots + a_n 2^n$. Once you've described the number as a sum like this, you know how to write it in base two: you just put all the coefficients together in order $(a_n\ldots a_3a_2a_1a_0)$.
Writing a number in base eight means writing it as a weighted sum of powers of eight: $b_0 8^0 + b_1 8^1 + b_2 8^2 + b_3 8^3 + \ldots + b_n 8^n$. Once you've described the number as a sum like this, you know how to write it in base eight: you just put all the coefficients together in order $(b_n\ldots b_3b_2b_1b_0)$.
If you wanted to, you could express a number in base ten as a weighted sum, too. You could write $c_0 10^0 + c_1 10^1 + c_2 10^2 + c_3 10^3 + \ldots + c_n 10^n$. Then the representation in base ten is just $c_n\ldots c_3c_2c_1c_0$.
This doesn't do much, of course. The number 1423 can be written as $3\cdot 10^0 + 2\cdot 10^1 + 4\cdot 10^2 + 1\cdot 10^3$. If you put the coefficients together, you get 1423 in base ten, exactly as you started with.


Ionic: Fazer o botão confirmar retornar ao primeiro erro do formulário

Question: Olá, estou com um projeto em ionic/firebase e tem nele um formulário com cerca de 31 questoes e preciso que nesta tela ao clicar para concluir ao invés de voltar para o topo como segue nesta função que está no código this.content.scrollToTop(); eu necessito que ele retorne para a primeira questão inválida. OBS: já tentei muitos tutoriais na internet .
Segue abaixo um trecho do meu .TS:
  enviar(abertura: Abertura) {
    if (this.form.form.invalid) {
      let confirmAlert = this.alertCtrl.create({
        title: 'Parece que há alguma questão sem marcar!',
        message: 'Para proseguir, marque o que está faltando!',
        buttons: [
          {
            text: 'Voltar',
            handler: () => {
              console.log('Voltar clicado');
              this.content.scrollToTop();
            }
          },
        ]
      });
      confirmAlert.present();
    }

Comment: Já tentou colocar foco no elemento inválido?
Answer: Em vez de usar a função this.content.scrollToTop(), você pode usar this.content.scrollTo(x, y, duracao). Para encontrar a posição y do elemento, você pode usar a propriedade offsetTop.
Comment: renata no caso eu teria que colocar uma posição x em cada questão?
Comment: Como você identifica a questão que não foi respondida? Nessa função você pode identificar o elemento em que buscará o offsetTop.
Comment: entendi obgd, vou tenatr executar o codigo
Answer: Pode usar HTML puro com hyperlink segue exemplo:
Crie o atributo em suas perguntas

Pergunta 1

quando você quiser navegar para a pergunta 1 crie um hyperlink dinamicamente
Pule para pergunta 1


Required environment variables for JDK 17

Question: I am trying to install java to my Windows 11 machine but when I try run
java -version in the command prompt, I get 'java' is not recognized as an internal or external command.
In my computer's System variables I have a PATH variable with a link to C:\Program Files\Java\jdk-17\bin. I have looked at Oracle's installation instructions here but it seems like it should be plug and play so to speak.
Are there additional environmental variables that I am missing or possibly I am pointing the path variable to the wrong location?
Comment: There is nothing else.  `PATH` should be all you need to make `java -version` work.  So check that your update to `PATH` is correct.  What happens when you run `C:\Program Files\Java\jdk-17\bin\java -version` ?
Comment: Did you close and reopen your terminal after the installation? Also, many tools rely on `JAVA_HOME` being set, but that's not needed here. And to be somewhat pedantic, Java doesn't require _any_ environment variables to be set. Setting the `PATH` is a convenience, and it's _other tools_ that may rely on `JAVA_HOME`. Some APIs in Java may use certain environment variables _if they are set_ (using default values if they aren't), but that will be documented for each individual API.
Comment: You seem to confuse environment variables needed for Java to execute with environments variables needed for your command line to find the Java executable. It seems that you want the later but the subject points to the former.
Answer: After closing and reopening the command promt works.


How can I access ngOffline directive in a component instead of html

Question: I'm using this npm library https://www.npmjs.com/package/ng-offline to alert end user when offline.

You're offline. Check your connection!

stackblitz here: https://stackblitz.com/edit/angular-ngoffline-npm?file=src%2Fapp%2Fapp.component.html
Works great - BUT I want to open a modal with this ngOffline directive, so I'm trying to access the directive from my angular 11 component but not sure how to approach this, any help on this would be greatly appreciated.
Is there away for me to open a ngx-bootstrap modal from the html with this directive?
Answer: Because the ng-offline module isn't exporting things as you might expect (i.e. you can't inject a standalone NgOfflineDirective for you to use without having it in your html file), you could add a block like this (where you've used #trigger to identify your ngOnline element):
import { AfterContentChecked, Component, ElementRef, OnDestroy, ViewChild } from '@angular/core';
import { BehaviorSubject, Subscription } from 'rxjs';
import { distinctUntilChanged, filter } from 'rxjs/operators';

@Component({ ... })
export class YourClass implements AfterContentChecked, OnDestroy {
  offline$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>();
  subscription: Subscription;

  @ViewChild('trigger') trigger: ElementRef;

  constructor() {
    this.subscription = this.offline$.pipe(
      distinctUntilChanged(),
      filter((offline: boolean) => offline),
    ).subscribe(() => this.showModal());
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  ngAfterContentChecked() {
    if (
      this.trigger &&
      this.trigger.nativeElement
    ) {
      this.offline$.next(this.trigger.nativeElement.style.display === "none");
    }
  }

  showModal() {
    console.log('Show your modal here.');
  }
}

Comment: thanks for the answer, as it it an angular application - I tried your answer but used hostlistener instead but unfortunately couldn't get it to work - @HostListener("window:ngOffline", ["$event"])
  openOfflineModal() {
    this.offlineModal.show();
  }
Comment: Okay, but I literally added that line into your typescript and it worked as expected. :/
Comment: it does open an alert but does not use the library I am using from npm also your solution picks up the local/browser network whereas the ngOffline package on npm detects if you have no wifi/internet - I need to open a modal using the package from npm mentioned above in a component instead of the html - do you have any other suggestions? - I'd be delighted to hear them, thanks for the help so far ;)
Comment: I actually pulled that line out of the source for `ngOffline`. It looks like there's an additional poll to a URL to check response headers.
Comment: I have updated the stackblitz with your code and trying to hide/show the modals based on the wifi connection - initially with your code - the modal was displaying when connected to the internet but I want to show the modal when the user gets disconnected - it'd be great if you could fork my stackblitz and share the link - I'm missing something small but can't see it - really appreciate the help you've given me so far
Comment: Ah. I'm sorry that I was confusing. The `display === "none"` should be paired with an `ngOnline` element. If you are targeting an `ngOffline` directive, you'd use `display === "inherit"`.
Comment: thank you so much - works perfect - Now I need to hide the modal when back online, thanks again


Modify PRODUCT_BUNDLE_IDENTIFIER in project.pbxproj of Xcode

Question: I'm trying to modify the project.pbxproj file of Xcode project using sed shell command on Mac Terminal to replace a string. I want to replace the field -
PRODUCT_BUNDLE_IDENTIFIER = com.example.71b9b4f2
to
PRODUCT_BUNDLE_IDENTIFIER = com.example.14a32d1e
Command used -
sed -i 's/com.example.71b94f2/com.example.14a32d1e/g' project.pbxproj
which produces the following output error-

sed: 1: "project.pbxproj": extra characters at the end of p command

I was earlier using Plistbuddy shell command to modify the field CFBUNDLEIDENTIFIER in info.plist but that doesn't change $(PRODUCT_BUNDLE_IDENTIFIER) in Xcode 7 build settings anymore.
My main aim is to modify the PRODUCT_BUNDLE_IDENTIFIER field of BUILD SETTINGS in Xcode using command line or any script.
Answer: OSX requires the extension to be explicitly specified. The workaround is to set an empty string:
sed -i '' 's/com.example.71b94f2/com.example.14a32d1e/g' project.pbxproj

Comment: found an alternative solution as well using [mod-pbxproj](https://github.com/kronenthaler/mod-pbxproj). Will share a detailed answer on how to use this as well for others.
Comment: Yup. Tried that, didn't work in this case. Already found this [here](http://myshittycode.com/2014/07/24/os-x-sed-extra-characters-at-the-end-of-l-command-error/)
Comment: it's weird because i just tried and it works for me on my macbook pro
Comment: do you mind using python script? i can write python script for you


Forecasting adjustment factor in the gas consumption formula supplied by industry

Question: I am trying to model gas consumption in France. The industry publishes a formula to use for this. A simplified version looks like this consumption = K * f(x), where K is an adjustment factor, where they try to correct themselves for the error on the model f(x). These K values are published every day.
Using this formula it is simply a matter of plugging the data into f(x). However, I dont know what the K values will be. I have the data for the published K values for the past 9 years, and they look like this:

Hence I would like to model the K values, at least for the short term though long term would be useful too.
What is the best way of tackling this problem?
I am thinking ARIMA though I think it may be correlated with weather too.
Useful info:

The data is auto-correlated
You can see seasonality in the plot
The data is stationary
Suspect correlation with weather
I have data for a 14 day weather forecast
Answer: I would form a daily model between consumption (the k values ) and weather . Arima models that include predictor variables both user-specified and identified from the data can be very useful ... they are sometimes referred to ARMAX models or Transfer Function Models or Dynamic Regression models. Data analysis might suggest monthly effects , holiday effects , day-of-the-week effects , day-of-the-month effects , week=of-the-month effects , long-weekend effects et al. and perhaps some memory effects.
I would search for "daily data" in SE for example Simple method of forecasting number of guests given current and historical data to get a flavor of this kind of approach


What map API for android suits my application

Question: I´m making an app that requires the locations of all users that are signed into it and displaying all of their locations to each other on a map.
What tool can you recommend me for the job?
Comment: How about the one the question is tagged with?
Answer: For creating such an app you need to have a PHP server that would first store the geocoordinates of all the users who are currently signed in in a MySQL database. Once you have that part of information you have to convert that database data into JSON object and create your own API/URL which can be requested via an Android client using HTTP. This would populate the maps of all your users with markers displaying their current location.
For implementation details please take a look at the following tutorial.
Answer: You can use google maps api for android (here), and have your app ask for device's current location when user signed on, then post the geo location to a server, finally display the available info using maps marker.


Proper way in PHP to format/escape a string for use in XML

Question: I have a number of fields that are completed by a user on a form and are then sent to a web service via SOAP.  When I build my XML to pass along the user entries, it generally works without issue.  However, I'm running into issues in a few cases where the API fails and I know it's related to characters within what the user entered.
Is there a proper way to escape a string to be sent via XML?  I've read many threads talk about using htmlspecialchars() and then just as many saying that's bad practice.  I also just recently realized that I should probably change the encoding to UTF-8?
I'm sure I will probably get down voted for this post as I admittedly don't have much expertise in XML.  Looking for the best practice here so my call to this API is as reliable as possible and sincerely appreciate any guidance.
Here's the XML snippet:
//BUILD FIELD DATA
$xmlStr = "<?xml version=\"1.0\" encoding=\"us-ascii\"?>
<record>
<field Name=\"dateCreated\" Text=\"".$DATE_CREATE."\" />
<field Name=\"purpose\" Text=\"".$PURPOSE."\" />
<field Name=\"comments\" Text=\"".$COMMENTS."\" />
<field Name=\"terms\" Text=\"".$TERMS."\" />
</record>";

Comment: I don't have an answer, I just wanted to say no one should be down-voting you for your lack of knowledge. You wouldn't be here if you knew everything. Votes are supposed to reflect the quality and relevance of the question. I too have seen several string escape questions, [one I asked and answered myself](http://stackoverflow.com/questions/12699037/how-to-display-special-characters-in-php/12784217). I'm not at all an expert, so good luck to you!
Comment: @philtune Thank you!  I sincerely appreciate that!
Comment: Encoding to UTF-8 is a good idea, especially if you will be receiving input in multiple languages.
Comment: Where are you validating the input in PHP?
Answer: I would recommend you look into using the XMLWriter functions for building XML documents. This PHP manual page on XMLWriter has a nice simple usage example in the user-contributed notes section: http://php.net/manual/en/function.xmlwriter-open-memory.php. If I remember correctly the XMLWriter function will escape some characters for you.
You could also look into wrapping the contents of XML elements with CDATA tags like so:
<field Name="purpose"><![CDATA[ Here's < some " crazy !/> characters! ]]></field>

Which basically tells XML to not parse anything inside of the CDATA tags
You should also be cleaning up any user input you accept to make sure you avoid malicious behavior by the bad guys. I recommend looking into filter_var. It's not bulletproof, but it will definitely help. I use the following in some of my code to clean up inputs to my PHP scripts:
function cleanInput($input){
    if(gettype($input) == 'array'){
        foreach($input as $key => &$val){
            $key = cleanInput($key);
            $val = cleanInput($val);
        }
    }else{
        $input = filter_var(trim($input), FILTER_SANITIZE_SPECIAL_CHARS);
    }
    return $input;
}
$_POST = array_map("cleanInput", $_POST);
$_GET = array_map("cleanInput", $_GET);

Hope that helps you get started.
Comment: This really helped me out - I sincerely appreciate the help!


the way to get a datetime from datetime + float on odoo

Question: i want to know session_finish from session_start + duration. the session_start  type is date and the duration is float.
@api.onchange('session_start')
def onchange_session_start(self):
    for record in self:
        if self.session_start is not None :
            self.session_finish = self.session_start + self.duration

Comment: Does this code work? If not, what is the _complete_ error message.
Comment: Float field duration is of datetime type? Ex. duration: 3.5 minutes like
Comment: @DyZ thats is not work:( . this the error : TypeError: coercing to Unicode: need string or buffer, float found
Comment: @rahulmehra the `duration` type is `Float`,, ex. duration 9,5 = 9 hour 30 mins
Answer: if the session start is a datetime object then you can add the duration using timedelta function
import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.

if not then convert the data to datetime
Comment: `datetime.datetime(100,1,1,11,34,59)` can u explain this number ??
Comment: this is the format of datetime object
 import datetime
datetime.datetime.now()
output: datetime.datetime(2018, 2, 15, 15, 9, 54, 556721)
Comment: datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
Comment: okaay, but can u give example with my case?, the datetime is not datetime.now() , but i have `session_start` . thank u ^_^
Comment: the field `session_start` type  is datetime
Comment: and the field `duration` is float
Answer: You need to convert duration then add it to session_start as pointed by @Burmese pythis:
class TestModel(models.Model):
    _inherit = "test.model"

    @api.onchange('session_start')
    def onchange_session_start(self):
        if self.session_start:
            session_start = fields.Datetime.from_string(self.session_start)
            interval = datetime.timedelta(seconds=(self.duration * 3600))
            self.session_finish = fields.Datetime.to_string(session_start + interval)

    session_start = fields.Datetime("Session start")
    duration = fields.Float("Duration")
    session_finish = fields.Datetime("Session end")


GCP - Windows Activation

Question: I'm using a GCP-VM instance with Windows Server 2019 Datacenter Edition installed normally, suddenly Windows is not activated more and i can't do it.
I tried to active windows in control panel, but i had the message below:

In my revenue i have a fee for windows license, so i don't know what is happening.
Answer: According to GCP documents click here and click here , you need to recheck configure routes and firewall rules in your VPC network to allow access to kms.windows.googlecloud.com (184.108.40.206).
Furthermore I attached this document click here , as I think it will be useful regarding your request and you will be able to troubleshoot the issue.
Comment: I use the commands `cscript \windows\system32\slmgr.vbs /skms 126.96.36.199:1688` and `cscript \windows\system32\slmgr.vbs /ato` and it's work, thanks!

GCP - Windows Activation


System of Pythagorean Quadratics

Question: I have a system of quadratics, obtained from three mechanical links, fixed at one end and free at the other. The intersection point of the three free ends is required.
$AC=\sqrt{(A_x-C_x)^2+(A_y-C_y)^2+(A_z-C_z)^2}$
$BC=\sqrt{(B_x-C_x)^2+(B_y-C_y)^2+(B_z-C_z)^2}$
$FC=\sqrt{(F_x-C_x)^2+(F_y-C_y)^2+(F_z-C_z)^2}$
Where C_x,y,z are the unknowns. I am halfway through solving by substitution and it is really messy. Does anyone know of a slightly more elegant way of solving these? Any techniques I should research. I want to avoid doing it numerically if possible.
Many Thanks
James
Comment: What is a mechanical link?
Comment: Just an arm or lever - these ones are fixed by ball joints at one end and free to move at the other.
Answer: So basically what you have are three circles and you want to find the point where they intersect. I am going to show you how to use linear algebra to solve your problem with an example.
Suppose that your three circles are: $C_1=(-3, 50), r_1=41$, $C_2=(11,-2), r_2=13$, and $C_3=(13,34), r_3=25$. Let us write the equations of the three circles:
\begin{align*}
x^2 + 6x + 9 + y^2 - 100y + 2500 &= 1681\\
x^2 - 22x + 121 + y^2 + 4y + 4 &= 169\\
x^2 - 26x + 169 + y^2 - 68y + 1156 &= 625
\end{align*}
After re arranging them we have:
\begin{align*}
x^2 + y^2 &= -6x + 100y - 828\\
x^2 + y^2 &= 22x - 4y + 44\\
x^2 + y^2 &= 26x + 68y - 700
\end{align*}
And finally this can be transformed in the following linear system:
\begin{align*}
-6x + 100y - 828 &= 22x - 4y + 44\\
-6x + 100y - 828 &= 26x + 68y - 700
\end{align*}
which reduces to:
\begin{align*}
-28x + 104y &= 872\\
-32x + 32y &= 128
\end{align*}
whose solution is: $(6,10)$. The tale of the story is the following, The system of linear equations is solely formed from the data: centers and radii.
Comment: I really like the quadratic to linear transformation - but how do you get to the two solutions from the quadratics? I am actually dealing with spheres instead of circles - but the concept of what you say seems to still follow. Thanks for providing such a detailed explanation.
Comment: Having had a closer look at this - The method you propose works for the first case of eliminating the quadratic components but does not for the second. I think this is because my initial x,y,z coordinates for the three known root points are a mix of positive and negatives from the coordinate origin. This must mean that in some cases the required solution requires using the positive quadratic solution and in other cases the negative quadratic solution is required. I am guessing this method is equivalent to using the positive quadratic solutions?
Comment: Ok fantastic - I have just worked it all the way through and can now see what was happening. If you substitute the linear expressions for x y and z back into the original quadratics - you get your two solutions out. Thanks very much. Exactly what I was looking for.
Answer: Squaring and reordering the equations yields:
$$\begin{array}{ccccccccc}
C_x^2 + C_y^2 + C_z^2 & = & 2A_xC_x & + & 2A_yC_y & + & 2A_zC_z & + & |AC|^2 - (A_x^2+A_y^2+A_z^2) \\
C_x^2 + C_y^2 + C_z^2 & = & 2B_xC_x & + & 2B_yC_y & + & 2B_zC_z & + & |BC|^2 - (B_x^2+B_y^2+B_z^2) \\
C_x^2 + C_y^2 + C_z^2 & = & 2F_xC_x & + & 2F_yC_y & + & 2F_zC_z & + & |FC|^2 - (F_x^2+F_y^2+F_z^2) \\
\end{array}$$
Let $A_r = |AC|^2-(A_x^2+A_y^2+A_z^2)$ (and similarly for $B_r$ and $F_r$). Subtracting the last equation from the previous two reduces this to:
$$\begin{array}{ccccccc}
2(A_x-F_x)C_x & + & 2(A_y-F_y)C_y & + & 2(A_z-F_z)C_z & = & F_r - A_r \\
2(B_x-F_x)C_x & + & 2(B_y-F_y)C_y & + & 2(B_z-F_z)C_z & = & F_r - B_r \\
\end{array}$$
This is an under-determined system of equations which can be solved to obtain the general solution in the form $(C_x,C_y,C_z)=(P_x+v_xt,P_y+v_yt,P_z+v_zt)$ for some point $P=(P_x,P_y,P_z)$ and vector $(v_x,v_y,v_z)$, where $t$ can be any real number. Plugging these into any of the first three equations above yields a quadratic equation with unknown $t$, solving of which should be easy enough (and the solution can be used to obtain $(C_x,C_y,C_z)$ afterwards).
If you're going to implement this on a computer, there are a few corner cases that might need to be considered (e.g. some coordinates of the points being equal, thus resulting in zero coefficients in the system of equations; solutions not existing; ...).
Comment: Hi Peter. This looks really promising -thanks very much for taking the time. I am struggling to follow you from the two under-determined equations to your general solution, but am still working on it. Would you be able to suggest any resources I could have a look at to better follow this? Thanks again. James

System of Pythagorean Quadratics


Python optparse make_option() equivalent in argparse

Question: From the OPTPARSE library reference:
option_list = [
    make_option("-f", "--filename",
                action="store", type="string", dest="filename"),
    make_option("-q", "--quiet",
                action="store_false", dest="verbose"),
    ]

parser = OptionParser(option_list=option_list)

Like the above example, I want to make a option list using make_option and pass it to a decorator which instantiates the parser and adds the arguments.
How can this be achieved in argparse? Is there a way to populate the parser other than parse_args()?
Comment: What do you mean by "pass it to a decorator".  I don't see any decorators here ... Also, I don't think that `parse_args` populates the parser.  `add_argument` populates the parser.
Comment: It is interesting that using `option_list` is deprecated, and that it is suggested to "use `add_option()` after creating the parser instead."  http://docs.python.org/2/library/optparse.html#creating-the-parser
Answer: You can give argparse.ArgumentParser a list of parent parsers:
parent = argparse.ArgumentParser(add_help=False)
parent.add_argument('-f','--filename')
parent.add_argument('-q','--quiet',action='store_false',dest='verbose')

parser = argparse.ArgumentParser(parents=[parent])
...
namespace = parser.parse_args()

Answer: def process_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--filename', dest='filename', type=string, action='store')
    args = parser.parse_args()
    return args

if __name__ == '__main__':
    args = process_args()


VS Code with c++ ext on macOS cannot debug my code

Question: I installed the plugin and written an default configuration, but breakpoints and callstack does not bound to vs code.
launch.json:
{
  "version": "0.2.0",
  "configurations": [

    {
      "name": "(lldb) Launch",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}/${fileBasenameNoExtension}.o",
      "args": [],
      "stopAtEntry": true,
      "cwd": "${fileDirname}",
      "environment": [],
      "externalConsole": true,
      "MIMode": "lldb"
    }
  ]
}

tasks.json:
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build",
      "command": "clang++",
      "args": [
        "-Wall",
        "-std=c++17",
        "-g",
        "-o",
        "${fileBasenameNoExtension}.o",
        "${fileBasename}",
      ],
      "options": {
        "cwd": "${fileDirname}"
      },
      "problemMatcher": {
        "owner": "cpp",
        "fileLocation": [
          "relative",
          "${fileDirname}"
        ],
        "pattern": {
          "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
          "file": 1,
          "line": 2,
          "column": 3,
          "severity": 4,
          "message": 5
        },
      },
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "presentation": {
        "echo": true,
        "reveal": "never",
        "focus": false,
        "panel": "shared",
        "showReuseMessage": true,
        "clear": false
      }
    }
  ]
}

output (app just executed w/o on breakpoint stopping):
Loaded '/Users/mxtnr/xp/coursera-cpp/practices/1.o'. Symbols loaded.

Execute debugger commands using "-exec <command>", for example "-exec info registers" will list registers in use (when GDB is the debugger)

The program '/Users/mxtnr/xp/coursera-cpp/practices/1.o' has exited with code 0 (0x00000000).

What am I doing wrong?
Comment: VSCode C/C++ referrence: https://code.visualstudio.com/docs/languages/cpp
Comment: VSCode debug referrence: https://code.visualstudio.com/docs/editor/debugging#_breakpoints
Answer: @atombit, just, replace g++ by clang++!


Running a Java Thread in intervals

Question: I have a thread that needs to be executed every 10 seconds. This thread contains several calls (12 - 15) to a database on another server. Additionally, it also accesses around 3 files. Consequently, there will be quite a lot of IO and network overhead.
What is the best strategy to perform the above?
One way would be to use the sleep method along with a while loop, but that would be a bad design.
Will a class similar to Timer be helpful in this case? Also, would it be better to create a couple of more threads (one for IO and one for JDBC), instead of having them run in one thread?
Comment: Why is the sleep a bad design? Granted it won't be every 10 seconds, rather every 10+n seconds. But you can't guarantee 10 seconds anyway if one of the passes takes 12 seconds to complete. If you're just trying to minimize load on the server, it makes little difference whetehr it a sleep or timer.
Comment: I was referring the sleep along with the while loop, as a bad design. Since, it might not be very intuitive to decide on the when and how of terminating the thread.
Answer: I find that a ScheduledExecutorService is an excellent way to do this.  It is arguably slightly more complex than a Timer, but gives more flexibility in exchange (e.g. you could choose to use a single thread or a thread pool; it takes units other than solely milliseconds).
ScheduledExecutorService executor =
    Executors.newSingleThreadScheduledExecutor();

Runnable periodicTask = new Runnable() {
    public void run() {
        // Invoke method(s) to do the work
        doPeriodicWork();
    }
};

executor.scheduleAtFixedRate(periodicTask, 0, 10, TimeUnit.SECONDS);

Comment: If you were not using a single threaded executor, I might be inclined to wrap the doPeriodicWork() call in a "synchronized (this)" block just to be safe.
Comment: That would certainly protect; declaring doPeriodicWork as synchronized would accomplish the same thing and probably be a little cleaner.  That being said, there are probably smaller critical sections within doPeriodicWork that could be protected individually if moving to a thread pool.
Comment: @GregCase: If you change `periodicTask` while `executor` is running, how do you get `executor` to update itself to use the latest `periodicTask` at runtime?
Comment: @ThreaT: There's no way to swap out the Runnable instance directly.  You have 2 options:  Cancel (using the ScheduledFuture returned by schedule) and re-submit with the new Runnable, or set up your Runnable instance to have state such that it delegates to another object instance then swap that object instance out on the fly.  Note if you do this your Runnable will likely not be able to be an anonymous inner class like the example in the answer; you will need to at a minimum declare a field storing the delegate instance and keep the reference around somewhere to be able to update that field.
Answer: One option is to create a ScheduledExecutorService to which you can then schedule your job:
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
ex.scheduleWithFixedDelay(...);

If you did decide to have multiple threads, then you can create a ScheduledExecutorService with more threads (again, via the Executors class).
In terms of how many threads and what you put in each thread, in terms of performance, I'd say this depends on:

for your particular application, can one thread genuinely "do work" while another one is waiting for I/O?
would your multiple threads ultimately "thrash the same resource" (e.g. read from files in different locations on the same dsk) and thus slow one another down, or would they be simultaneously hitting different resources?
Answer: Have a look at the Timer and TimerTask classes.  They are exactly what you want.
You can make a TimerTask implementation that takes your thread object in a constructor.
The run method will then call the threads run method.
// Perhaps something like this
Timer t = new Timer();
t.scheduleAtFixedRate(yourTimerTask, 0, 10 * 1000);
// Hopefully your task takes less than 12 seconds

Comment: 10 Chars is just a suggestion!
Comment: I just tried to enter "! ." and I get the dreaded "Please enter at least 10 characters." under the input box when I click on AddComment. It doesn't actually enter the comment. How'd you do that??
Comment: If you type !.  you can trick the system.  It seems to count space as a character and then remove extra ones when it feels like it.
Comment: Yeah, you can't put spaces at the start or end, they need to be in the middle! Who wrote this crap?    :-)

Running a Java Thread in intervals


Argument 'fn' is not a function got string

Question: I have a part in my angular application on which I've binded a controller,
since then I got the Argument 'fn' is not a function Error, can anyone look at my code and explain why I got that Error?
I would be very gratefull :)
html-markup:

  <fieldset>
    <legend>{{ 'MESSAGES' | translate }}</legend>
  </fieldset>

{{ message }}

controller:
(function() {
  'use strict';

  var controllers = angular.module('portal.controllers');

  controllers.controller('MessageController', ['$scope', 'MessageService', '$rootScope', function MessageController($scope, MessageService, $rootScope) {
    $rootScope.MSG = MessageService.getMessages();

    $rootScope.$watch('MSG', function(newValue) {
      $scope.MSG = newValue;
    });
  }]);
}());

Service:
(function() {

  'use strict';

  var messageServices = angular.module('portal.services');

  messageServices.factory('MessageService', ['MessageData', 'localStorageService', 'UserService'], function(MessageData, localStorageService, UserService) {
    return new MessageService(MessageData, localStorageService, UserService);
  });

  function MessageService(MessageData, localStorageService, UserService) {
    this.messageData = MessageData;
    this.localStorageService = localStorageService;
    this.userService = UserService;
  }

  MessageService.prototype.getMessages = function() {
    var locale = this.userService.getUserinfoLocale();
    var messages = this.localStorageService.get(Constants.key_messages + locale);
    if (messages !== null && messages !== undefined) {
      return JSON.parse(messages);
    } else {
      return this.messageData.query({
        locale: locale
      }, $.proxy(function(data, locale) {
        this.save(Constants.key_messages + locale, JSON.stringify(data));
      }, this));
    }
  };

  MessageService.prototype.save = function(key, value) {
    this.localStorageService.add(key, value);
  };

}());

data:
(function() {
  'use strict';

  var data = angular.module('portal.data');

  data.factory('MessageData', function($resource) {
    return $resource(Constants.url_messages, {}, {
      query: {
        method: 'GET',
        params: {
          locale: 'locale'
        },
        isArray: true
      }
    });
  });
}());

order of js files in html head:

Comment: possibly something to do with jQuery, as in when you are adding a plugin to jQuery with `$.fn.extend({...`. maybe you haven't include jQuery lib
Comment: jQuery is the first script that's added in my head tags, I'll edit the question with the order of the js files
Answer: The problem was in using the 'wrong' syntax to create the service
instead of using:
messageServices.factory('MessageService',
    ['MessageData','localStorageService', 'UserService'],
    function(MessageData, localStorageService, UserService){
        return new MessageService(MessageData, localStorageService, UserService);
    }
);

I had to use:
messageServices.factory('MessageService',
    ['MessageData','localStorageService', 'UserService',
    function(MessageData, localStorageService, UserService){
        return new MessageService(MessageData, localStorageService, UserService);
    }
]);

I closed the array with parameters to soon, and since I'm still learning I didn't see it directly, anyhow I hope I can help others who stumble upon this.
Comment: or
```config('someFactory', 'otherFactory', superFunction)```
instead
```config(['someFactory', 'otherFactory', superFunction])```
Comment: This is really nasty. In my case, I mistakenly put one service outside the square bracket (so all the parenthesis and brackets are matched well), and it took me long long time to figure it out because I refactored a lot of codes. So, again, you get this same meaningless error message when you have something like: `app.factory('x', 'y', ['z', function(y, z) {...}]);` (notice y is outside of square bracket). The worst of all, it doesn't tell you which file has this problem. so if you have changed a lot of files, go figure.
Comment: In my case removing dependency names in square brackets helped. Like so `.factory('historyentries', function($http){}` instead of `.factory('historyentries', ['$http'],  function($http)`
Comment: Those lines no needed, if you removed it then it's automatically works `'MessageData','localStorageService', 'UserService'],`
Answer: Today I got the same kind of error doing that silly mistake:
(function(){

  angular
    .module('mymodule')
    .factory('myFactory', 'myFactory');   // <-- silly mistake

  myFactory.$inject = ['myDeps'];
  function myFactory(myDeps){
    ...
  }

}());

instead of that:
(function(){

  angular
    .module('mymodule')
    .factory('myFactory', myFactory);   // <-- right way to write it

  myFactory.$inject = ['myDeps'];
  function myFactory(myDeps){
    ...
  }

}());

In fact the string "myFactory" was brought into the injector who was waiting for a function and not a string.
That explained the [ng:areq] error.
Answer: The above answers helped me considerably in correcting the same issue I had in my application that arose from a different cause.
At built time, my client app is being concatenated and minified, so I'm writing my Angular specifically to avoid related issues. I define my config as follows
config.$inject = [];
function config() {
    // config stuff
}

(I define a function, $inject it as a module and declare what it is).
And then I tried to register the config just as I registered other modules in my app (controllers, directives, etc..).
angular.module("app").config('config', config); // this is bad!

// for example, this is right
angular.module("app").factory('mainService', mainService);

This is wrong, and gave me the aforementioned error. So I changed to
angular.module("app").config(config);

And it worked.
I guess the angular devs intended config to have a singular instance and by so having Angular not accept a name when config is registered.
Comment: It is the same for the Run method! Thank you very much for sharing this!
Answer: I had the same issue and In my case the problem was with angular-cookies.js file. It was in folder with other angularjs scripts and when I have used gulp to minify my js files the error occured.
Simple solution was just to place the angular-cookies.js file to another folder, outside the selected folder to minify js files.
Answer: My case
  let app: any = angular.module("ngCartosServiceWorker"),
    requires: any[] = [
      "$log",
      "$q",
      "$rootScope",
      "$window",
      "ngCartosServiceWorker.registration",
      PushNotification
    ];
  app.service("ngCartosServiceWorker.PushNotification");

I forgot to add requires Array as parameters to service like this
app.service("ngCartosServiceWorker.PushNotification", requires);


Enforcing lock screen after idle time via GPO

Question: I run a network of computers and I would like enforce a GPO which locks the screen after a predefined idle time. I can't find this setting, I can only find a screen saver idle time setting, how can I get a log-out screen accomplished?
Thanks.
Comment: Total agreement with everybody else here-- you're mixing terminology. Do you want to lock the workstation or force the user to logoff? (If you did want forced logoff, which I'd highly recommend against, have a look at: http://support.microsoft.com/kb/314999)
Answer: Actually I found (and tested) in Windows Server 2012 R2, under:
Computer Configuration>Policies>Windows Settings>Security Settings>Local
Policies>Security Options>

And open item Interactive logon: Machine inactivity limit
Explanation:

Interactive logon: Machine inactivity limit.
Windows notices inactivity of a logon session, and if the amount of
  inactive time exceeds the inactivity limit, then the screen saver will
  run, locking the session.
Default: not enforced.
Comment: This works great for Windows 10 clients, but Windows 7 doesn't work with this. :/
Comment: compare the results of gpresult /h gpo.htm command result for each Windows version
Answer: Well, through Group Policy you can force to lock down a workstation via a password protected screensaver, but not to log it off. The GPO settings for locking down a workstation via screensaver can be found at:
Administrative templates\control panel\display\password protect the screen saver and screen saver timeout.
Comment: On Windows Server 2008 or above they are: User Configuration > Policies > Administrative Templates > Control Panel > Personalization
Comment: To disable this setting through the registry, the path is `HKCU:\software\policies\microsoft\windows\Control Panel\desktop`
Comment: This setting don't exist in windows 2008. Which version are your using?
Answer: The more direct solution you are likely looking for is located in:
Group Policy Management / Group Policy Editor
Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > Security Options
Microsoft Network Server: Amount of idle time required before suspending session.
Comment: The description says that applies to SMB sessions
Answer: In my french version of W2K8, I have in :
GPO > Strategy > Administration Model > System > Power Management > Screensaver options > Ask for a password when computer wake up

It should do the trick...
PS : the translation of GPO entries is approximative
Answer: For Windows XP, Vista and 7, you only can locked the workstation with the User Configuration > Policies > Administrative Templates > Control Panel > Personalization feature. This GPO feature already apply to the newer operating systems, but some Windows 8.1 and 10 versions are having issues with it. So, for those Windows versions I'd take advantage of the Interactive logon option.
You should be careful when applying both, Screensaver with password and Interactive logon: Machine inactivity limit, as they may come in conflict and lead to unexpected results for Windows 8 and later versions.
Interactive logon: Machine inactivity limit gpo feature only apply to Windows 8 and later versions.
But all depends of your environment and the Windows versions you have deployed in your domain.
Answer: To force a lock enforce the screen saver with the "require a password..." option. Logging out is a whole different thing. Which are you after?
Comment: Agree that the question mixes terms - though I'll go so far as to recommend a lock vs. log-out or you're going to zap a lot of user work.
Answer: On Windows Server 2008 these settings can be found in:
User Configuration > Policies > Administrative Templates > Control Panel > Personalization
Answer: Create a new GPO then edit it and go to: Computer Config>Policies>Windows Settings>Security Settings>Local Policies>Security Options and find Interactive logon: Machine inactivity limit. Set that to whatever time you want and it will lock the PC after it hits that timer.
Comment: I dont see `Interactive logon: Machine inactivity limit` in the list? What version of SBS is this for?


Javascript/Angular is changing my number

Question: I was bored and was playing with angular filters, and I've noticed that angularjs will change the number if you use | number filter, which shouldn't affect my number in anyway, but somehow if I filter 9999999999999999 it will change it to 10000000000000000, while if I filter 9999999999999998 it will leave it as it is 9999999999999998.
Plunker example
I am very curious and looking forward to know, what makes javascript/angularjs filter to change my number by 1 unit?
Comment: That is actually JS problem, try `var n = 9999999999999999;`
Comment: Javascript only has 64-bit floats - and you've ran out of floating-point precision.
Comment: Welcome to floating point numbers.
Comment: Why this happens? If a bank will use javascript, it could bring a bug to the whole system.
Comment: JavaScript really got your number on that one!
Comment: @PHPLover people who code with really big (and really small) numbers will run in to this type of problem quite often and there are libraries for most, if not all, languages to deal with these issues
Comment: Good js practices for money and other floating points where precision needs to be exact, is to not use floating point numbers, but multiply/divide everything back to an integer before doing maths. For numbers bigger than the limit, you can use strings and arrays to represent really big numbers. Writing a module to do maths with arrays is quite trival.
Answer: That is actually JS problem, try var n = 9999999999999999; and it is related to: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER


SwingWorker: Syntax error on token "execute" -?

Question: I'm trying to use a SwingWorker but for some reason at worker.execute(); I receive the following error:

"Syntax error on token "execute", Identifier expected after this
  token"

That doesn't help much, it's a generic error, and no matter how stupid it might be, it's been torturing me for hours.. I've seen that moving SwingWorker somewhere else outside the class may fix it, but I don't understand how and why and why it should not work like this! Ugh!
public class App {

    private App() {  // CONSTRUCTOR

        final int WINHSIZE = 2000;
        final int WINVSIZE = 2000;

        class Enjoy extends JPanel  {

            @Override
            public void paintComponent(Graphics g) {
                g.drawLine(0, 0, 2000, 2000);
            }

            class MyExecutor extends SwingWorker<Void,Void> {

                @Override
                protected Void doInBackground() {
                    return null;
                }

                @Override
                protected void done(){ // runs on EDT

                }
            }

            MyExecutor worker = new MyExecutor();
            worker.execute(); // What the hell is going wrong here?

        }

        Runnable runner = new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame("Title");
                JPanel panel = new Enjoy();
                JScrollPane myScrollPane = new JScrollPane(panel);
                f.add("Center", myScrollPane);
                f.pack();
                f.setVisible(true);
            }
        };

        SwingUtilities.invokeLater(runner);

    }

    public static void main(String[] args) {
        new App();
    }
}

Thanks.
Answer: worker.execute(); must be inside some method, it can't be directly within the scope of your Enjoy class.
Comment: @jj_ This is wrong Java syntax in general. Statements must be inside a method, constructor or initializer block.
Comment: @jj_ The only exception to that rule is when you call the methods as an initialization of a class member. So `private int foo = bar();` can appear inside a class and outside a method, but `bar()` can't.
Comment: @jj_ In that case the compiler assumes you wanted to declare multiple members of the same type. While `String s = "something"; b = s.substring(3);` is invalid, `String s = "something", b = s.substring(3);` is valid - since it declares two String members.
Comment: Why??? is this a specific case or what? Is this wrong Java syntax in general? As I said in question, I'd like to know the reason behind it...
Comment: `it can't be directly within the scope of your Enjoy class.` for what reason exactly?
Comment: so basically you can't call functions form inside a class and outside a method, in Java ?
Comment: Thanks. I understand. About that, while trying stuff at some point I did: `something  = worker.execute();` At that point Eclipse stops marking it as an error and instead it marks as error the line just before it, on the `;` and the error becomes: `Syntax error on token ";", , expected`. How is this explained?
Comment: One more thought, since we're here: would it be a bad idea in my case to put the SwingWorker .execute() method in the SwingWorker constructor, like so `public MyExecutor(){ this.execute();  }` ? Makes sense?


Convergence of probabilistic process

Question: Take a random vector $V$ of length $n$ where $V_i \in [m]$.  Define a random process as follows. Repeatedly pick two indices $i, j \in [n]$ uniformly at random and let $V_i := V_j$ (that is change the value at index $i$ to be the value at index $j$). How can you prove that this eventually converges to a vector with all entries the same with probability $1$?
Answer: The quickest way is to notice that if the sequence of pairs $(2,1), (3,1), \dots, (n,1)$ ever occurs then $V_1$ will be copied to all entries in the vector.
As the choices of pairs are iid the sequence will occur eventually with probability one.

Convergence of probabilistic process


Estrutura Package IntelliJ

Question: Boa tarde, pessoal.
Sou novo com o Intellij, ainda estou me habituando, no entanto, gostaria de saber se tem como mudar essa estrutura de exibição dos arquivos no package. Segue a estrutura:

Queria deixar que as classes viessem antes das subpastas, algo parecido com isso:
<code>br.com.loja
  LojaAppApplication
  LojaAppApplication
  Controller (pasta)
    Arquivos de Controller
    ....
  Models (pasta)
    Arquivos de Models
    ....
</code>
Não sei se é possível, mas já agradeço.
Answer: Não há essa opção no IntelliJ.
As únicas opções possíveis são:

exibir as pastas acima dos arquivos (conforme ilustrado no print) ou;
exibir o conteúdo em ordem alfabética (misturando arquivos e pastas).

Fonte: https://www.jetbrains.com/help/idea/project-tool-window.html
Comment: Aaah, blz. Obrigado. Com tempo eu me acostumo então.

Estrutura Package IntelliJ


Spring dispatcher not redirecting to the next page

Question: In my project the spring dispatcher is not redirecting to the next page, the following is my project
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:component-scan base-package="com.go.controller" />
    <mvc:annotation-driven />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".html" />
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/GoAnalyserDB" />
        <property name="username" value="postgres" />
        <property name="password" value="toor" />
    </bean>

</beans>

I have created the pages in the /WEB-INF/pages but still it is not redirecting to that page.
My controller class
package com.go.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class GoScrapperRouter {

    public GoScrapperRouter(){
        System.out.println("-------Inside thr GoScrapperRouter-------");
    }

    @RequestMapping("/logInSuccess")
    public ModelAndView logInSuccessFn(){
        System.out.println("inside startAnalyser controller loginsuccess");
        ModelAndView model = new ModelAndView("profile");
        return model;
    }

}

my jsp file

<form class="form-signin" action="logInSuccess">
                  Email address
                  <input type="text" class="input-block-level" placeholder="Email address" ng-model="userName">
                  Password
                  <input type="password" class="input-block-level" placeholder="Password" ng-model="password">
                  <button class="btn btn-large" type="submit" >Login</button>

               </form>

When i click the button, the control goes to the controller function and prints the text
"inside startAnalyser controller loginsuccess",
but it is not redirecting to the next page present in WEB-INF/pages/
my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Go Scrapper</display-name>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <welcome-file-list>
    <welcome-file>new.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

</web-app>

Comment: Can you add your project directory structure to know if everything is correct. Is this your profile page is html or jsp?
Answer: Can you please try below approach:
@RequestMapping("/logInSuccess")
    public String logInSuccessFn(){
                System.out.println("inside startAnalyser controller loginsuccess");
                //ModelAndView model = new ModelAndView("profile");
                return "profile";
            }


XMLWriter - setting DoNotEscapeUriAttributes and OutputMethod

Question: I'm trying to create an XMLWriter with the following properties:
OutputMethod = XmlOutputMethod.Html
DoNotEscapeUriAttributes = true

OutputMethod cannot be set using this:
var stringBuilder = new StringBuilder();

var xslCompiledTransformObj = new XslCompiledTransform();
xslCompiledTransformObj.Load(typeof(TransRep));

XmlWriterSettings settings = new XmlWriterSettings() {
                                 DoNotEscapeUriAttributes = true,
                               //OutputMethod = xslCompiledTransformObj.OutputSettings.OutputMethod
                              };

var xmlWriter = XmlWriter.Create(stringBuilder, settings);

This sets xslCompiledTransformObj.OutputSettings.OutputMethod to XmlOutputMethod.Xml (the default)
DoNotEscapeUriattributes cannot be set using this method:
var stringBuilder = new StringBuilder();

var xslCompiledTransformObj = new XslCompiledTransform();
xslCompiledTransformObj.Load(typeof(TransRep));

//The following line does not work:
//xslCompiledTransformObj.OutputSettings.DoNotEscapeUriAttributes = true;
var xmlWriter = XmlWriter.Create(stringBuilder, settings);

This sets xslCompiledTransformObj.OutputSettings.OutputMethod to XmlOutputMethod.Html
and DoNotEscapeUriAttributes is false
Answer: The XmlOutputMethod is not public, and changing it via other mechanisms (such as reflection) will not have an expected result.
As explained by MSDN:  "This setting is set by the XSLT processor and is used internally by Visual Studio."


Do zero inflated continuous covariates cause "problems" in binary logistic regression?

Question: I am trying to do a logistic regression to look at the relationship between the number of cigarettes smoked by subjects in a sample (0-60 per day) and a yes/no outcome. As a lot of people in the sample are non-smokers, there are lot of zeros for the continuous covariate.
I have a few questions about this:

Is this correctly described as a zero-inflated continuous covariate?
Will this cause "problems" in the logistic regression e.g. affect the validity of the coefficients etc.
Should a stratified be carried out on smokers and non-smokers instead?

Thanks
Answer: If the zero-inflation is extreme, it will cause problems, not because it violates assumptions but because of the sense of the regression. I think it will cause problems here. Many studies use two smoking variables: Yes/No and then number (just among smokers).
Logistic regression in its usual form assumes that the relationship is linear in the logit; that is, the difference in the logit between 0 and 1 cigarettes is the same as between 1 and 2:
$f(z) = \frac{1}{1 + e^{-z}}$
where
$z = \beta_0 + \beta_1 + ... \beta_p$
Such a linear relationship seems unlikely here (although you don't say what your DV is)
One could use a spline of B instead (see, e.g. this article.  If I recall, Frank Harrell's book discusses these models as well. However, a yes/no + number analysis might be easier to interpret.
Comment: Ps: I agree a linear relationship is probably unlikely. I have a number of zero inflated covariates like this and just want to get a sense of some of the issues with dealing with such data. Many thanks again.
Comment: Hi Peter, many thanks for your insights. You say that many studies include two smoking variables. Do you mean they have a model of the form: y=B0+B1(SMOKER)+B2(CIGARETTES) per day (wouldn't the fact that CIGARETTES=0 for all SMOKER=0 cause instabilities)? Or that they do a stratified analysis  y=B0+B1(CIGARETTES) just using the data on smokers?
Comment: I think they mostly do stratified analyses.
Comment: You would set up the model as y=B0+B1(NONSMOKER)+B2(CIGARETTES). This would give y=B0+B1 for non-smokers and y=B0+B2(CIGARETTES) for smokers (on the logit-scale, of course).
Answer: (Reinforcing Peter Flom's answer) In marketing, the standard is to model whether they buy the product (yes/no, logistic) and then the number of purchases among those who buy the product. A third variable would be the average size of the purchase.  In line with this, you'd have a yes/no on smoker and then only among smokers model the number of cigarettes.
These analyses do not always point in the same direction; it's not unusual for advertising to increase the number of buyers but have little effect on how often they buy, for example.
Comment: Hi thanks for the feedback.  I'm actually using "number of cigarettes" as a predictor rather than an outcome. How would you guys in marketing deal with this?
Answer: Since nobody's mentioned it, you could also think of your data as the result of a two step process, e.g. some personal facts determine whether a subject smokes, and then some possibly different facts determine how the intensity of smoking affects the question outcome.
This approach puts in the domain of explicit selection models, of which Heckman and Tobit regression are familiar examples for continuous dependent variables.  The statistical issues arise due to the possibility of correlated errors in the two steps.  There exist relatively straightforward extensions to probit models to cover your categorical dependent variable: try googling 'double probit' for details.  I think this would be the model class corresponding to @zbicyclist's answer.


Complete Load Balancing solution

Question: I have a Laravel web application based on MariaDB, PHP, Nginx, and ubuntu 20.04. To ensure that my website is always online under heavy traffic, I decided to establish load balancing between my servers. I'm using the Galera cluster for the database and Rsync for the file synchronization. But I don't want to have only one Nginx reverse_proxy server to distribute traffic between my servers. Because it's risky since if the reverse proxy server goes down, it will take down the whole website.
So here is the question, How can I distribute the traffic between two Nginx reverse proxies? The two Nginx reverse proxy servers should point to my website domain
Answer: You put two haproxy servers in front of the nginx servers, of which only one handles the traffic, the other one is kept in standby by keepalived.
Comment: What if the traffic takes down the HAproxy server??
Comment: That's not traffic, that needs a DDOS, against which you can perhaps - perhaps! - protect your site with a CDN.  Does your site generate enough to pay for that?  Also, Laravel will go down long before HaProxy or Nginx.
Comment: I thought your question was "How can I distribute ...".
Comment: using cdn is fine but here is my question. If the first haproxy goes down for any reason(other than ddos). how can I set the first server's IP to second one?? as you know changing server IP address need time to be available to internet dns servers.
Comment: That is, as I said, the task of keepalived.  In case of a problem, the standby system takes over the service IP address.  No DNS involved.
Comment: Don't forget you need two routers from different ISP's too.
Comment: Do you have any tutorial articles for that?? Can you share it to me please??
Comment: No I don't.  I used this setup in production for years before I retired.  Nothing could bring it down apart from bad programming on the backends.
Comment: Tools used:  keepalived, haproxy, varnish, nginx or apache in front of different backend system.

Complete Load Balancing solution