What's the best way to add an alert box to a link in D7

Question: I have a link, which is rendered via the l function. It's a link which calls a function that deletes a node. Before the function is called, I want an alert box to pop up and give the user the option to 'Cancel' or 'Confirm'. Adding this as an argument to the l function works:
array('attributes' => array('onclick' => 'return confirm("Are you sure?")'))

...but is there an existing function, or something, that does a nicer job?
I'd rather not add a contrib module for such a small task.
Answer: no there is no js related function in drupal 7 that provides a functionality like that. just make sure that custom setup you have there is in your template.php
Answer: There are no built-in functions for client-side JS UI confirmation prompts.
If you're want to rely on just Drupal core for node deletion prompts you can use the built-in deletion forms (assuming the user has permissions to access it) and use the destination query parameter to redirect the user back to where they need to be:
$nid = 123;
$return_path = 'admin';
l(t('Remove Node'), 'node/' . $nid . '/delete', ['query' => ['destination' => $return_path]]);


Changing order of expectation for a double expectation

Question: I have an equation with two expectations, which looks like the follows:
\begin{align}
   E_{o} E_{z} (\sum_{i=1}^{m} f_1(o_i) * f_2(z_i)) \\
\end{align}
Where $o$ is a discrete random variable with finite number of states, and $z$ is a continuous random variable.
Now my question is, can I swap the order of the expectation, i.e. take expectation w.r.t $z$ first, then w.r.t $o$ ? Is the following assumption valid?
\begin{align}
   E_{o} E_{z} (\sum_{i=1}^{m} f_1(o_i) * f_2(z_i)) = E_{z} E_{o} (\sum_{i=1}^{m} f_1(o_i) * f_2(z_i))
\end{align}
My end goal is to move expectation w.r.t. $o$ inside the summation with $i$.
Answer: Whether you can exchange integrals is a matter of Fubini's Theorem and its various close associates. The short answer is that it depends on your function $f$ and the distribution of the random variable $z$.
Two conditions you might check, either of which would be sufficient to guarantee that you can exchange the integrals:

Is $f$ nonnegative?
Assuming a no on the above -- that is, $f$ has negative values -- is $E_0 E_z \left(  \left| \sum_{i=1}^m f(o_i) * f(z_i) \right| \right)$ finite?

For checking condition 2, the sum being finite and $o_i$ being finitely supported means that everything rests on the mapping of $f(z_i)$. If $f(z_i)$ is bounded, for instance, then you're fine.
Failing that, things get more technical; the counterexamples on the linked Wikipedia article may be illuminating.
Comment: Thank you, Aaron, for your reply. I was checking the form of my equation again and I think I made a mistake. I have two functions, one dependent on $o$ and the other one on $z$. The first function (of $o$) is an indicator function and the second function (of $z$) is basically a parameterized log-likelihood function, with a neural network with a softmax layer at the end. Softmax can give close to zero value if the input is very large, in that case, log-likelihood can be close to infinity.
Comment: Happy to help. I won't pretend to understand all the details of what you've said, but you might be in good shape -- if $f$ is really just a log-likelihood, then perhaps it's non**positive**, which is just as good as nonnegative for Fubini's Theorem purposes. (Proof: Negate it.) The only concerning case would be if $f(z_i)$ can assume *both* large positive *and* large negative values.


SQL Left join with having clause

Question: So I am having this sql code:
select stone_number,stone_size,stone_shape,stone_weight
from stone
left Join stone_price stp on stp.id_stone = stone.id_stone
group by stone_number,stone_size,stone_shape,stone_weight
having  avg(stp.price) < stp.price;

Sqldeveloper returns: not a group by expression tho I still have group by in my code.
My goal is to get stone items which price is higher then average price of all stones.
Comment: [Is it true that using INNER JOIN after any OUTER JOIN will essentially invalidate the effects of OUTER JOIN?](https://stackoverflow.com/a/55111083/3404097)
Answer: You can do that with a window function:
select *
from (
  select stone_number,stone_size,stone_shape,stone_weight,
         stp.price,
         avg(stp.price) over () as avg_price
  from stone
    left Join stone_price stp on stp.id_stone = stone.id_stone
)
where price > avg_price;

Note that the condition on the outer joined table essentially turns your outer join into an inner join. If you also want to include rows that did not have a match in stone_price you need
where price is null
   or price > avg_price;

Otherwise you can just change the left join to a "plain" join

Another option is a simple sub-select:
select stone_number,stone_size,stone_shape,stone_weight,
from stone
  left Join stone_price stp on stp.id_stone = stone.id_stone
where stp.price > (select avg(price) from stone_price);

Answer: One approach is to use a stored procedure, You could set a variable like this:
DECLARE @average_price INT
SET @average_price = (SELECT Avg(stone_price) from stone

Then in your SELECT statement
select stone_number,stone_size,stone_shape,stone_weight
from stone
left Join stone_price stp on stp.id_stone = stone.id_stone
WHERE stone_price > @average_price

Comment: That is not valid for Oracle
Comment: That seems like a good idea, I never saw or done that only some basic SQL but I get the idea. I'm working in SqlDeveloper and I get error at @ when declaring the variable: Encountered the symbol "@" when expecting one of the following:

   begin function pragma procedure subtype type
 current cursor delete
   exists prior
Comment: Oh right... this is SQL for SQL Server. But that would be one approach to take in Oracle. Declare a variable, get the average and then use that in the where clause.

SQL Left join with having clause


Agrupamento de objetos de um array por datas equivalentes

Question: Bom dia,
estou com uma dúvida onde tenho um array de objetos da seguinte forma, por exemplo:
var producao = [{data: '2019-12-19', producao_ok: 10, producao_nok: 20}, {data: '2018-10-01', producao_ok: 5, producao_nok: 1}, {data: '2019-12-19', producao_ok: 100, producao_nok: 2}, {data: '2018-10-01', producao_ok: 100, producao_nok: 10}, {data: '2019-12-19', producao_ok: 10, producao_nok: 20}];

Existe alguma forma de, por exemplo com o reduce, fazer o somatorio dos valores de producao_ok e producao_nok por agrupamento de datas, tendo em mente que não  tenho ideia das datas iniciais e finais do objeto?
exemplo de resultado esperado após inserir em um array novo:
var objetoNovo = [{data: '2019-12-19', producao_ok: 120, producao_nok: 42}, {data: '2018-10-01', producao_ok: 105, producao_nok: 11}];

Comment: Já considerou usar uma estrutura de dados chave/valor, por exemplo um map?
Answer: Adaptando a resposta da pergunta "how to group by and sum array of object?" para o seu exemplo, podemos utilizar a função reduce do array para obter um objeto com chaves de acordo com o campo que você que agrupar e somando os demais valores. Depois disso é possível utilizar a função Object.values para obter os valores selecionados previamente.

const producao = [{
  data: '2019-12-19',
  producao_ok: 10,
  producao_nok: 20
}, {
  data: '2018-10-01',
  producao_ok: 5,
  producao_nok: 1
}, {
  data: '2019-12-19',
  producao_ok: 100,
  producao_nok: 2
}, {
  data: '2018-10-01',
  producao_ok: 100,
  producao_nok: 10
}, {
  data: '2019-12-19',
  producao_ok: 10,
  producao_nok: 20
}];

const reduzir = (acumulador, { data, producao_ok, producao_nok }) => {
  // Se ainda não existir o registro no agrupamento
  if (!acumulador[data]) {
    acumulador[data] = {
      data,
      producao_ok: producao_ok,
      producao_nok: producao_nok,
    };
  } else {
    acumulador[data].producao_ok += producao_ok;
    acumulador[data].producao_nok += producao_nok;
  }

  return acumulador;
};

const agrupar = (conjunto) => {
  return Object.values(conjunto.reduce(reduzir, {}));
};

console.log(agrupar(producao));

Object.values
O método Object.values() retorna um array com os valores das propriedades de um dado objeto, na mesma ordem provida pelo for...in laço (sendo a diferença que o laço for-in também enumera as propriedades na cadeia protótipos).

reduce
O método reduce() executa uma função reducer (provida por você) para cada membro do array, resultando num único valor de retorno.
Exemplo:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
Comment: Cara, era exatamente isso! Valeu demais!


SQL (MySQL) vs NoSQL (CouchDB)

Question: I am in the middle of designing a highly-scalable application which must store a lot of data. Just for example it will store lots about users and then things like a lot of their messages, comments etc. I have always used MySQL before but now I am minded to try something new like couchdb or similar which is not SQL.
Does anyone have any thoughts or guidance on this?
Comment: I wish this wouldn't have to be closed. These questions are important to ask, but for some reason they don't belong in SO.
Comment: Gah, CW. And I was hoping to get some real rep and some street cred here. :-)
Comment: can you explain a little more about your data set?
Answer: Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic
  transmission and NoSQL databases are
  like manual transmission. Once you
  switch to NoSQL, you become
  responsible for a lot of work that the
  system takes care of automatically in
  a relational database system. Similar
  to what happens when you pick manual
  over automatic transmission. Secondly,
  NoSQL allows you to eke more
  performance out of the system by
  eliminating a lot of integrity checks
  done by relational databases from the
  database tier. Again, this is similar
  to how you can get more performance
  out of your car by driving a manual
  transmission versus an automatic
  transmission vehicle.
However the most notable similarity is
  that just like most of us can't really
  take advantage of the benefits of a
  manual transmission vehicle because
  the majority of our driving is sitting
  in traffic on the way to and from
  work, there is a similar harsh reality
  in that most sites aren't at Google or
  Facebook's scale and thus have no need
  for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.
Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.
Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)
I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL
Comment: The process of scaling SQL solutions is the process of removing features and relationships. So I don't think this is an entirely fair assessment. Also, I wouldn't group NoSQL databases together like this, Cassanda for instance focuses solely on scaling *up* while CouchDB is concerned with scaling the api *down* and making it easy to use and attempts to allow that api to scale as far up as possible.
Comment: Thanks for the post! The link "I Can't Wait for NoSQL to Die" doesn't work for me, you may want to check it.
Comment: Might this be the link to the quote? http://www.25hoursaday.com/weblog/2010/03/29/TheNoSQLDebateAutomaticVsManualTransmission.aspx
Comment: Ah, yes indeed. I missed that he made it a public blog post as well. I'll update the post.
Comment: "you have traded a well-enumerated list of limitations and warts for a newer, poorly understood list of limitations and warts" - [I Can't Wait for NoSQL to Die](http://www.memonic.com/user/dorian/folder/internet-tidbits/id/1HiG)
Comment: the Fighting the NoSQL mindset article is now a 404 :/^^
Comment: @treyBake Unfortunately, this is the fleeting nature of the Internet persistence... :-(
Answer: Seems like only real solutions today revolve around scaling out or sharding. All modern databases (NoSQLs as well as NewSQLs) support horizontal scaling right out of the box, at the database layer, without the need for the application to have sharding code or something.
Unfortunately enough, for the trusted good-old MySQL, sharding is not provided "out of the box". ScaleBase (disclaimer: I work there) is a maker of a complete scale-out solution an "automatic sharding machine" if you like. ScaleBae analyzes your data and SQL stream, splits the data across DB nodes, and aggregates in runtime – so you won't have to!
And it's free download.
Don't get me wrong, NoSQLs are great, they're new, new is more choice and choice is always good!! But choosing NoSQL comes with a price, make sure you can pay it...
You can see here some more data about MySQL, NoSQL...: http://www.scalebase.com/extreme-scalability-with-mongodb-and-mysql-part-1-auto-sharding
Hope that helped.
Answer: One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent.
Flexible to use
Comment: You should back-up your opinion to "best" because Couchbase, Cassandra, AeroSpike, etc and all databases that support the features you mention.

SQL (MySQL) vs NoSQL (CouchDB)


How to use other languages in an HTML file?

Question: I know how to use Javascript in an HTML file, via the  elements. But is there a way to do this with languages besides Javascript, like Python, C++, or Java?
P.S. I have seen something like


Limit of a Sequence via Monotone Convergence Theorem

Question: I'm working on the following problem:
Let $\{ a_n \}_{n \geq 1}$ be a sequence of real numbers with $a_1 > -2$, $a_{n+1} = \sqrt{a_n + 2}$. Show that (i) $|a_{n+1} - 2| \leq \frac{1}{2} |a_n - 2|$, and (ii) find the limit of $a_n$ as $n \rightarrow \infty$.
My attempt:
First, we show that $a_{n+1} = \sqrt{a_n + 2} > 0$ via induction. Accordingly, when $n=1$,
$$ a_{2} = \sqrt{a_1+2} > \sqrt{-2+2} = 0. $$
Now, suppose $a_{k+1} > 0$ for some $k$. Then,
$$a_{k+2} = \sqrt{a_{k+1} + 2} >^{I.H.} \sqrt{2} > 0. $$
Thus, $a_{n+1} > 0$ for all $n$. Now, suppose $a_1 \neq 2$, and observe that
\begin{align*}
\frac{1}{2} |a_n - 2| &= \frac{1}{2} |(a_{n+1}^2 - 2) - 2| \\
&= \frac{1}{2}|(a_{n+1} - 2)(a_{n+1}+2)| \\
&> \frac{1}{2}(2) |a_{n+1} - 2| \qquad a_{n+1} > 0\\
&= |a_{n+1} - 2|. \\
\end{align*}
Moreover, suppose $a_1 = 2$. Then, $\{ a_n \}$ is a constant sequence with $a_n = 2 \forall n$, so
$$ |a_{n+1} - 2| = 0 = \frac{1}{2}|a_n - 2|. $$
Combining these cases, it must hold that
$$ |a_{n+1} - 2| \leq \frac{1}{2} |a_n - 2|. $$
Concerning the limit, it can be shown that $\{ a_n \}$ is convergent, as a bounded monotone increasing sequence when $a_1 < 2$, a bounded monotone decreasing sequence when $a_1 > 2$, and as a constant sequence when $a_1 = 2$. We claim that $a_n \rightarrow 2$ as $n \rightarrow \infty$. Accordingly, let
$$ \lim_{n \rightarrow \infty} a_{n+1} = \lim_{n \rightarrow \infty} a_n = a. $$
Then,
\begin{align*}
a &= \lim_{n \rightarrow \infty} a_n \\
&= \lim_{n \rightarrow \infty} \bigg( a_{n+1}^2 - 2 \bigg) \\
&= a^2 - 2 \\
\Rightarrow 0 &= a^2 - a - 2 \\
\Rightarrow a &= -1, 2. \\
\end{align*}
Since the sequence is real-valued by assumption, it follows that $a_n \rightarrow 2$ (or, alternatively, $a_{n+1} > 0 \forall n \geq 1$).
As far as I can tell this seems like a valid solution, but I'm not proving (ii) in the way the writer of the question intended, as I don't use the result (i). I understand that result (i) tells us that each successive term has a distance from 2 that is less than or equal to half the distance of the previous term to 2, so this in itself seems to affirm that the limit must be 2. Is there a better way to approach this problem that utilizes this result?
Thanks!
Answer: Using the inequality you proved you have,
$$|a_{n+1}-2|<\frac{1}{2}|a_{n}-2|$$
You showed $\{a_n\}$ converges to some limit $a$ so taking limits gives
$$\lim\limits_{n\to\infty}|a_{n+1}-2|<\lim\limits_{n\to\infty}\frac{1}{2}|a_{n}-2|\\
|a-2|<\frac{1}{2}|a-2|\\
\implies |a-2|=0\\
\implies \lim\limits_{n\to\infty}a_n=2$$
You can also show $\{a_n\}$ converges, without using MCT, directly from the inequality. You can show by induction that $|a_{n}-2|<\frac{1}{2^{n-1}}|a_1-2|$ for $n\geq 2$ and the right hand side goes to $0$ as $n\to\infty$.
The nice thing about these two ways is you naturally avoid the artifact $\lim\limits_{n\to\infty}a_n=-1$, but solving for the limit using the recursive definition for $a_{n+1}$ is completely valid too.
edit: here is the induction proof that the limit exists. We first show that $|a_{n}-2|<\frac{1}{2^{n-1}}|a_1-2|$ for $n\geq 2$.
Base case: $n=2$. By the inequality you showed,
$$|a_2-2|<\frac{1}{2}|a_1-2|$$
Assume that $|a_{k}-2|<\frac{1}{2^{k-1}}|a_1-2|$ for some $k>2$. Then, by the inequality you showed,
$$|a_{k+1}-2|<\frac{1}{2}|a_k-2|<\frac{1}{2}\left(\frac{1}{2^{k-1}}|a_1-2|\right)=\frac{1}{2^{k}}|a_1-2|$$
and the induction proof is complete.
So, we have $|a_{n}-2|<\frac{1}{2^{n-1}}|a_1-2|$ for all $n\geq 2$. Taking limits on both sides gives,
\begin{align}
\lim\limits_{n\to\infty}|a_{n}-2|&<\lim\limits_{n\to\infty}\frac{1}{2^{n-1}}|a_1-2|=0
\end{align}
By continuity of absolute value we have $\lim\limits_{n\to\infty}a_n=2$. We didn't assume the limit exists at any point.
Comment: Thanks for this! What I'm still a bit concerned with here is making the assumption that $a_n$ actually converges. I suppose that contextually, being asked to find the limit implies that the limit exists?
Comment: I wouldn't assume it exists, that can get you into trouble. You can prove existence from the inequality as I showed above, just use induction.
Comment: Ah, I see. Thank you!


Prove that $T$ is an isomorphism if and only if $T(\beta)$ is a basis for $W$.

Question: Let $V$ and $W$ be $n$-dimensional vector spaces, and let $T:V\rightarrow W$ be a linear transformation. Suppose that $\beta$ is a basis for $V$. Prove that $T$ is an isomorphism if and only if $T(\beta)$ is a basis for $W$.
I know how to prove this question, but there is one part that I didn't quite understand that I need some help.
===========================
First suppose that $T$ is an isomorphism and let $\beta$ = {$\beta_1$,$\beta_2$,....., $\beta_n$}
Show that $\beta$ is linearly independent, which means
$$\sum_{i=1}^n a_iT(\beta_i) = 0$$ only when all $a_i=0$, where $a_i$ are scalars.
Note that $\sum_{i=1}^n a_iT(\beta_i)=T(\sum_{i=1}^n a_i\beta_i) = 0$, which implies $\sum_{i=1}^n a_i\beta_i$ is within the null space of $T$
and $\sum_{i=1}^n a_i\beta_i=0$ since $T$ is an isomorphism.
This is where I stuck, someone told me that " $\sum_{i=1}^n a_i\beta_i=0$ since $T$ is an isomorphism." But I don't understand why, can anyone explain to me?
Comment: "Show that  is linearly independent" is wrong it should be T()
Answer: Note that if $T$ is an isomorphism, it is injective (that is, one-to-one).  A linear transformation is injective if and only if its nullspace consists only of the $0$ vector.
So, for $\sum_{i=1}^n a_i \beta_i$ to be in the null space of $T$ (or in the null space of any injective linear map), we must have $\sum_{i=1}^n a_i \beta_i=0$.


Extract particular value from .txt file and place in excel

Question: I need to extract particular data from a text file and place it in Microsoft excel, where a template is already ready.
Example of my text file content:
     (3space)    (2s)   (2s)         (3s)                 (18s)
[key]   0.00-34.00  sec  2.08 minute   526 km/sec                  auto
[key]   0.00-34.00  sec  1.88 minute   474 Km/sec                  auto
[key]   0.00-34.00  sec  1.49 minute   376 km/sec                  auto
[key]   0.00-34.00  sec  1.25 minute   316 km/sec                  auto
[key]   0.00-34.00  sec  3.05 minute   771 km/sec                  van
[key]   0.00-34.00  sec  2.79 minute   705 km/sec                  van
[key]   0.00-34.00  sec  2.83 minute   715 km/sec                  van
[key]   0.00-34.00  sec  2.83 minute   716 km/sec                  van

and excel sheet template looks like: excel sheet is ready with headings,rows and columns
and this template will be created manually.
Expected:
1.The value in .txt file with km/sec and auto should be listed in second column
2.The value in .txt file with km/sec and van should be listed in third column
ex:this is how the expected template should look like :template after the values entered
added:
When i want to read from 3 files and place the value in single template :
instance-1 from file1
instance-2 from file2
instance-3 from file3
for instance 1 i made the following changes:
 Const strFile = "C:\file1.txt"

        ' Row Array
    Dim vntFR As Variant: vntFR = Array(89, 89)
    ' Column Array
    Dim vntCC As Variant: vntCC = Array(2, 8)

want to know How to proceed with file2 and file3
Comment: I'd suggest you to use `Split()` function
Answer: One possible way would be to use File I/O, together with Mid. Something like this seems to work on your sample data:
Sub sGetDistanceData(strFile As String)
    On Error GoTo E_Handle
    Dim intFile As Integer
    Dim strInput As String
    Dim lngVan As Long
    Dim lngAuto As Long
    intFile = FreeFile
    Open strFile For Input As intFile
    lngVan = 6    ' the first row of van data
    lngAuto = 6    ' the first row of auto data
    Do
        Line Input #intFile, strInput
        If Mid(strInput, 68, 4) = "auto" Then
            ActiveSheet.Cells(lngAuto, 2) = Mid(strInput, 38, 5)
            lngAuto = lngAuto + 1
        ElseIf Mid(strInput, 68, 3) = "van" Then
            ActiveSheet.Cells(lngVan, 3) = Mid(strInput, 38, 5)
            lngVan = lngVan + 1
        End If
    Loop Until EOF(intFile)
sExit:
    On Error Resume Next
    Reset
    Exit Sub
E_Handle:
    MsgBox Err.Description & vbCrLf & vbCrLf & "sGetDistanceData", vbOKOnly + vbCritical, "Error: " & Err.Number
    Resume sExit
End Sub

I've kept separate counts of the number of Van/Auto data imported, just in case there are an unequal number.
Regards,
Answer: Data From Text File
Sub DataFromTextFile()

    ' Text File Address
    Const strFile = "C:\Test1.txt"
    Const cCriteria As Long = 67  ' Criteria Position
    Const cPosition As Long = 38  ' Target Position
    Const cChars As Long = 5      ' Target Chars

    ' Criteria Array
    Dim vntC As Variant: vntC = Array("auto", "van")
    ' Row Array
    Dim vntFR As Variant: vntFR = Array(6, 6)
    ' Column Array
    Dim vntCC As Variant: vntCC = Array(2, 3)

    Dim vntL As Variant           ' Criteria Length Array
    Dim vntR As Variant           ' Target Row Counter Array
    Dim LB As Long                ' Array Lower Bound
    Dim UB As Long                ' Array Upper Bound
    Dim i As Long                 ' Array Element Counter
    Dim t As Long                 ' Total Records Counter
    Dim lngFile As Long           ' Text File Number
    Dim strLine As String         ' Current Line (in Text File)

    ' Calculate Lower and Upper Bounds.
    LB = LBound(vntC): UB = UBound(vntC)

    ' Resize Criteria Length Array to the size of Criteria Array.
    ReDim vntL(UB) As Long
    ' Calulate the length of each element in Criteria Array and write
    ' the calculated values to Criteria Length Array.
    For i = LB To UB: vntL(i) = Len(vntC(i)): Next i
    ' Resize Target Row Counter Array to the size of Criteria Array.
    ReDim vntR(UB) As Long

    ' Aquire Text File Number.
    lngFile = FreeFile()          '

    ' Write Text File to memory.
    Open strFile For Input As #lngFile
        ' Loop through lines of Text File.
        Do While Not EOF(lngFile)
            ' Write current line of Text File (from memory) to Current Line.
            Line Input #lngFile, strLine
            ' Loop through elements of Arrays.
            For i = LB To UB
                ' Check if Current Criteria is found at current Target Position.
                If Mid(strLine, cCriteria, vntL(i)) = vntC(i) Then
                    ' Count Target Row by increasing the current value
                    ' of the current element in Target Row Counter Array.
                    vntR(i) = vntR(i) + 1
                    ' Write Current Target Value to ActiveSheet.
                    Cells(vntFR(i) + vntR(i) - 1, vntCC(i)) _
                      = Trim(Mid(strLine, cPosition, cChars))
                    ' Count Total (All) Records so far.
                    t = t + 1
                    Exit For
                End If
            Next i
        Loop
    Close #1

    MsgBox "Total Records Found: " & t, vbInformation

End Sub

All those arrays are not for speed, but to be able to easily change the values of the variables or more importantly to add more criteria values e.g.:
' Criteria Array
Dim vntC As Variant: vntC = Array("auto", "van", "bike", "plane")
' Row Array
Dim vntFR As Variant: vntFR = Array(6, 6, 6, 6)
' Column Array
Dim vntCC As Variant: vntCC = Array(2, 3, 4, 5)

EDIT
This version consists of DataFromText where you change the names of the text files and the column pairs respectively, and of a NEW version of DataFromTextFile
where I have already changed the row numbers to 89 as requested. Best rename or delete the old version of DataFromTextFile.
Option Explicit

Sub DataFromText()

    Dim vntFiles As Variant   ' Files Array
    Dim i As Long             ' Arrays Elements Counter

    ' Files
    vntFiles = Array("C:\Test1.txt", "C:\Test2.txt", "C:\Test3.txt")
    ' If you add more files, you have to add more column pairs and increase
    ' the ubound of vntColumns i.e. the number in braces.
    Dim vntColumns(2) As Variant

    ' Column Pairs
    vntColumns(0) = Array(2, 8)
    vntColumns(1) = Array(3, 9)
    vntColumns(2) = Array(4, 10)

    For i = 0 To UBound(vntFiles)
        DataFromTextFile CStr(vntFiles(i)), vntColumns(i)
    Next i

End Sub

Sub DataFromTextFile(FilePath As String, TargetColumns As Variant)

    ' Text File Address
    Dim strFile As String
    strFile = FilePath
    Const cCriteria As Long = 67  ' Criteria Position
    Const cPosition As Long = 38  ' Target Position
    Const cChars As Long = 5      ' Target Chars

    ' Criteria Array
    Dim vntC As Variant: vntC = Array("auto", "van")
    ' Row Array
    Dim vntFR As Variant: vntFR = Array(89, 89)
    ' Column Array
    Dim vntCC As Variant: vntCC = TargetColumns

    Dim vntL As Variant           ' Criteria Length Array
    Dim vntR As Variant           ' Target Row Counter Array
    Dim LB As Long                ' Array Lower Bound
    Dim UB As Long                ' Array Upper Bound
    Dim i As Long                 ' Array Element Counter
    Dim t As Long                 ' Total Records Counter
    Dim lngFile As Long           ' Text File Number
    Dim strLine As String         ' Current Line (in Text File)

    ' Calculate Lower and Upper Bounds.
    LB = LBound(vntC): UB = UBound(vntC)

    ' Resize Criteria Length Array to the size of Criteria Array.
    ReDim vntL(UB) As Long
    ' Calulate the length of each element in Criteria Array and write
    ' the calculated values to Criteria Length Array.
    For i = LB To UB: vntL(i) = Len(vntC(i)): Next i
    ' Resize Target Row Counter Array to the size of Criteria Array.
    ReDim vntR(UB) As Long

    ' Aquire Text File Number.
    lngFile = FreeFile()          '

    ' Write Text File to memory.
    Open strFile For Input As #lngFile
        ' Loop through lines of Text File.
        Do While Not EOF(lngFile)
            ' Write current line of Text File (from memory) to Current Line.
            Line Input #lngFile, strLine
            ' Loop through elements of Arrays.
            For i = LB To UB
                ' Check if Current Criteria is found at current Target Position.
                If Mid(strLine, cCriteria, vntL(i)) = vntC(i) Then
                    ' Count Target Row by increasing the current value
                    ' of the current element in Target Row Counter Array.
                    vntR(i) = vntR(i) + 1
                    ' Write Current Target Value to ActiveSheet.
                    Cells(vntFR(i) + vntR(i) - 1, vntCC(i)) _
                      = Trim(Mid(strLine, cPosition, cChars))
                    ' Count Total (All) Records so far.
                    t = t + 1
                    Exit For
                End If
            Next i
        Loop
    Close #1

    MsgBox "Total Records Found: " & t, vbInformation

End Sub

Comment: Hi, This worked for a single file, to read data from text file and place it in a template prepared. Can i know how to modify the above code to read data from multiple files(test1,test2,test3) from the same path and i have multiple templates ready in the same excel one below the other.
Comment: Look at the constants and see what has to be changed. Obviously the filename and probably the first column. If that's all, then the sub can be written to have those arguments similar to the other solution. Please come back to me if you think some other constants will change.


AttributeError: 'str' object has no attribute 'values'

Question: I have the following code:
Source: Matplotlib overlapping annotations / text
import matplotlib.pyplot as plt
from adjustText import adjust_text
import numpy as np
together = [(0, 1.0, 0.4), (25, 1.0127692669427917, 0.41), (50, 1.016404709797609, 0.41), (75, 1.1043426359673716, 0.42), (100, 1.1610446924342996, 0.44), (125, 1.1685687930691457, 0.43), (150, 1.3486407784550272, 0.45), (250, 1.4013999168008104, 0.45)]
together.sort()

text = [x for (x,y,z) in together]
eucs = [y for (x,y,z) in together]
covers = [z for (x,y,z) in together]

p1 = plt.plot(eucs,covers,color="black", alpha=0.5)
texts = []
for x, y, s in zip(eucs, covers, text):
    texts.append(plt.text(x, y, s))

plt.xlabel("Proportional Euclidean Distance")
plt.ylabel("Percentage Timewindows Attended")
plt.title("Test plot")
adjust_text(texts, only_move='y', arrowprops=dict(arrowstyle="->", color='r', lw=0.5))
plt.show()

It does plot but i keep getting this error:
AttributeError: 'str' object has no attribute 'values'

Could you please advise why am i getting this error?
Full Error Traceback:
runfile('C:/Users//untitled3.py', wdir='C:/Users/')
Traceback (most recent call last):

  File "C:\Users\\untitled3.py", line 27, in <module>
    adjust_text(texts, only_move='y', arrowprops=dict(arrowstyle="->", color='r', lw=0.5))

  File "C:\Users\\anaconda3\lib\site-packages\adjustText\__init__.py", line 439, in adjust_text
    if not any(list(map(lambda val: 'x' in val, only_move.values()))):

AttributeError: 'str' object has no attribute 'values'

Comment: only_move (dict, default {'points':'xy', 'text':'xy', 'objects':'xy'}) – a dict to restrict movement of texts to only certain axes for certain types of overlaps. Valid keys are 'points', 'text', and 'objects'. Valid values are '', 'x', 'y', and 'xy'. For example, only_move={'points':'y', 'text':'xy', 'objects':'xy'} forbids moving texts along the x axis due to overlaps with points. - From https://adjusttext.readthedocs.io/en/latest/
Comment: It looks like `only_move` should be a dictionary instead of a string.
Comment: The problem is in the parameters expected by `adjust_text()`. You pass in a string `only_move='y'` but the function  expects something else. Since we don't have details on what this function is, its not something we can debug. Read this function's documentation to see what that parameter should be.
Comment: Please add the **full** error traceback formatted as code to your question!
Comment: @KlausD. I have updated the question with full error traceback as requested.
Answer: This error popped up because, the only_move you have provided is a string, but it expects a dictionary. In the last line of your error screenshot you can see only_move.values(), from where the error pops up.
PFB example:
adjust_text(texts, x, y, arrowprops=dict(arrowstyle="->", color='r', lw=0.5),
        autoalign='', only_move={'points':'y', 'text':'y'})

For your reference:
https://adjusttext.readthedocs.io/en/latest/Examples.html


Estimate $\hat{\beta}$ in linear regression for given data

Question:
For data $x=\begin{bmatrix} 1 \\  2 \\  3 \end{bmatrix}$ and $y=\begin{bmatrix} 4 \\  5 \\  3 \end{bmatrix}$, fit a linear model $y=ax+b+\varepsilon$ using the formula $\hat{\beta}=\left ( X^TX\right)^{-1}X^TY$.

This exercise should be really simple, but I have some doubts about my reasoning.
Let $Y_i = \beta_0 + \beta_1X_i+\varepsilon$ describe the i-th sample. The matrix of regressors is  $X=\begin{bmatrix} 1 & 1 & 1 \\  1 & 2 & 3\end{bmatrix}$.
Therefore $\left ( X^TX\right)^{-1} = \begin{bmatrix} 14 & 6\\  6 & 3 \end{bmatrix}^{-1} = \begin{bmatrix} \frac{7}{3} & 1\\ 1 & \frac{1}{2}\end{bmatrix}$ and $X^TY=\begin{bmatrix}12\\ 23\end{bmatrix}$.
The product of the matrix multiplication is:
$\hat{\beta}=\left ( X^TX\right)^{-1}X^TY = \begin{bmatrix} \frac{7}{3} & 1\\ 1 & \frac{1}{2}\end{bmatrix} \cdot \begin{bmatrix}12\\ 23\end{bmatrix}  = \begin{bmatrix}40\\ 18.5\end{bmatrix}$
Thus $\beta_0 = b = 40$ and $\beta_1 = a = 18.5$, meaning that the final linear model would be:
$y = 18.5x + 40 + \varepsilon$.
Hover, this seems unlikely, because graph of such line would be way above the given points. Am I making a mistake in my calculations? If so, where my understanding is incorrect?
Comment: $(X^T X)^{-1}$ should have two negative ones instead of two positive ones.
Answer: Mistakes:
$$X^{\color{red}{T}}=\begin{bmatrix} 1 & 1 & 1 \\  1 & 2 & 3\end{bmatrix}.$$
$$X^TX=\begin{bmatrix} 1 & 1 & 1 \\  1 & 2 & 3\end{bmatrix}\begin{bmatrix} 1 & 1 \\ 1 &  2 \\ 1 & 3\end{bmatrix}=\begin{bmatrix} 3 & 6 \\ 6 &  14 \end{bmatrix}.$$
To compute inverse:
$$\begin{bmatrix} a & b \\ c & d\end{bmatrix}^{-1}=\frac{1}{ad-bc}\begin{bmatrix} d & -b \\ -c & a\end{bmatrix}$$


Asymptotic expansion for $\frac{1}{2\zeta(3)}\int_x^\infty \frac{u^2}{e^u - 1} du$?

Question: Is there an asymptotic expansion for the function:
\begin{equation}
g(x)=\frac{1}{2\zeta(3)}\int_x^\infty \frac{u^2}{e^u - 1} du,
\end{equation}
over the domain $x\in [0,\infty)$ in terms of elementary functions? Here $\zeta$ is the Riemann zeta function and $1/2\zeta(3)$ is a normalization factor included to ensure $g(0)=1$.
Comment: This is sometimes referred to as the [incomplete Bose-Einstein integral](http://en.wikipedia.org/wiki/Incomplete_polylogarithm).
Answer: We have $$g(x) = \dfrac1{2 \zeta(3)}\underbrace{\int_x^{\infty} \dfrac{u^2}{e^u-1} du}_{I(x)}$$
We will now obtain a series expansion for $I(x)$. We have $$I(x) = \int_x^{\infty} \dfrac{u^2}{e^u-1} du = \int_x^{\infty} \dfrac{u^2 e^{-u}}{1-e^{-u}} du = \int_x^{\infty} \sum_{k=0}^{\infty} u^2 e^{-(k+1)u} du = \sum_{k=1}^{\infty} \int_x^{\infty} u^2 e^{-ku} du$$
We now have that
$$\int_x^{\infty} u^2 e^{-ku} du = \dfrac{e^{-kx} \left(k^2 x^2 + 2kx + 2\right)}{k^3}$$
We have have
$$I(x) = \sum_{k=1}^{\infty} \dfrac{e^{-kx} \left(k^2 x^2 + 2kx + 2\right)}{k^3}\tag{$\star$}$$
For a given $x$, truncating $(\star)$ will give you an exponentially converging approximation. Note that $$I(0) = \displaystyle \sum_{k=1}^{\infty} \dfrac2{k^3} = 2 \zeta(3)$$
Comment: Great! But surely you should substitute $k+1\rightarrow k$ to simplify $(\star)$? Also, the sum is missing in $l(0)$.
Comment: @DouglasB.Staple Oh yes:)!. Thanks. Done.
Comment: Beautiful. Also, $(\star)$ gives $ l(x)=2\operatorname{polylog}(3,e^{-x}) + 2x\operatorname{polylog}(2,e^{-x}) - x^2\ln(1-e^{-x})$ using the definition of the $\operatorname{polylog}$ function.
Comment: @DouglasB.Staple Yes. I always forget the polyLog expansions, though I am encountering it frequently in recent times.
Answer: yes is equal to the incomplete gamma function http://mathworld.wolfram.com/IncompleteGammaFunction.html
$$ \Gamma (3,x) $$
Comment: No, it's not.$\phantom{}$


Nenhuma forma de manter os dados do input text após submit?

Question: Queria manter os dados do formulário, após dar um submit na página. Não existe nenhuma forma mesmo?
Comment: existe e já tem resposta aqui no site. Vou procurar o link...
Comment: Normalmente, se for PHP e submit normal, dá pra fazer isso `$nome = isset( $_POST['nome'] )?$_POST['nome']:'';` e no form ``, desde que você mande o `$_POST` pra mesma página que gere o formulário
Comment: Opa, se encontrar me passa, não encontrei ainda.
Comment: Mas tenho que inicializar a variavel com null, certo?
Comment: Não precisa, veja que o ternário do `isset` já está retornando vazio se não tiver o post. Aproveite que não tem nenhuma resposta, clique em [edit] e ponha o seu código da parte PHP e do HTML, que fica mais fácil postar um exemplo.
Comment: porém vou passar mais dados, além do nome e vou jogar para uma função que irá trazer um resultado do banco de dados.
Comment: De qq forma, vc tem que [edit] explicar direitinho na pergunta o fluxo dos dados e de preferencia por um exemplo mínimo de código do jeito que vc está fazendo agora, pra facilitar quem for dar respostas. A essência é o que eu pus no comentário, que é preencher o `value` com a informação, independente de onde vem os dados
Answer: <code><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <form action="" method="POST" >
            <?php
              $user = (!empty($_POST['user'])) ? $_POST['user'] : '';
             ?>
            <input type="text" name="user" id="user" value="<?php echo htmlentities( $user ) ; ?>" />
            <input type="submit" value="Enviar" />
        </form>

    </body>
</html>
</code>


bivariate function

Question: I have two variables and a single output for example:
$$x_1=\{0.2,0.4,0.6\} , x_2=\{0.2,0.6,1.9\}  , y=\{10, 18, 30\}$$
I want to find an equation to obtain y from both $x_1$ and $x_2$: $y=f(x_1,x_2)$
What kind of equation is suitable for this problem and how to find the coefficients? I am not sure but some equations by googling is:
$$y=x_1^{\alpha}\cdot x_2^{\beta}$$
Find best alpha beta using dataset or maybe bivariate normal distribution
Thanks for your help in advance
Comment: you may want to consider simple linear regression.
Comment: Thanks for comment. it  can work but I need a more sophisticated solution. Is optimization can work in this case? or any other mathematical methods.
Comment: How many data points are given ?
Comment: around 200 data points
Comment: around 200 data points. The x, y range is between 0 to 20. The range of output (y) is from 0 to 100
Answer: The function $y=e^{\gamma}\cdot x_1^{\alpha}\cdot x_2^{\beta}$ fits the data quite well. $e^{\gamma}$ is a constant
To apply linear regression, you have to linearize the equation.
$ln(y)=ln(e^{\gamma}\cdot x_1^{\alpha}\cdot x_2^{\beta})$
$ln(y)=\gamma+\alpha \cdot ln(x_1)+\beta \cdot ln(x_2)$
First you have to transform the values of $y, x_1$ and $x_2$ in ln-values. I inserted the values in a table:

After applying linear regression the equation is:
$y = 0.3290563948\cdot x_1 + 0.327415062\cdot x_2 + 3.359135209$
And the regression line is $y_i=e^{3.359135209}\cdot x_{1i}^{0.3290563948}\cdot x_{2i}^{0.327415062}$
Inserting the values for i=1
$e^{3.359135209}\cdot 0.2^{0.3290563948}\cdot 0.2^{0.327415062}=10$
Inserting the values for i=2
$e^{3.359135209}\cdot 0.4^{0.3290563948}\cdot 0.6^{0.327415062}=18$
Thus there is more or less no difference between $y_i$ and the estimated $y_i$.
Comment: Don't you think that this is normal with $3$ parameters and $3$ data points ?
Comment: @ClaudeLeibovici Yes, it is not surprisingly.
Comment: Thanks for your answer. The function seems very useful. could you please explain the reason for using this function with exponential constant? what is the advantage compared to simple linear regression. Is there any reference for this function or Does this fitting function has a special name in mathematics that I can study more?
Comment: @saeed Linear regression deals with linear functions. Linear functions have, in general, a constant. $y=a_0+a_1x_1+a_2x_2+a_3x_3+...+a_nx_n$. The móre parameters a function has, the better is the fitting. Thus it is useful to calculate with a constant. It is a exponential regression. By transforming the values you can apply the linear regression.

bivariate function


Connect mosquitto as a publisher

Question: I have running mosquitto and I want to do that only one client can connect to topic as publisher (maybe with password or something) others can only conncet as subscriber.
Defining topic and user access rights at conf file is the way that. But in my application topics are created dynamically at run time.
How can I achieve this?
Thanks
Comment: What have you already tried? The docs about how to set up a ACL are easy to find
Comment: Doc is clear. But I forgot to say topics are dynamically created. Therefore defining them on acl file is not practical I think
Comment: Edit the question to include some examples and what you've tried
Comment: I added the dynamically part. I will add some codes and conf file soon
Answer: See mosquitto-auth-plug

... plugin can perform authentication (check username / password) and
  authorization (ACL).

You may need to modify one of the backends suited for you if you want to have a dynamic behavior on topic authorization. See be_jwt_aclcheck functions.

Connect mosquitto as a publisher


Prove that a planar and triangulated graph is $k$ connected if and only if it has no separating cycle of length at most $k−1$

Question: Let G be a  planar graph with a fixed  planar drawing $Γ$. A separating cycle of G is a cycle $C$ such that the curve traced by $C$ in $Γ$  has at least  one vertex strictly inside and strictly outside.

Note: $uwv$ is a separating cycle .
I'd like to prove that a planar and triangulated graph is k connected  if and only if it has no separating cycle of length at most k−1.
The necessary condition is obvious.
I was stuck in a proof of sufficient condition.  I 'd like to know the reason why we will get $G$ is $k$ connected when the triangulated planar graph $G$ has no separating cycle of length at most $k−1$.
Some definitions and  theorems  that may be used:

A connected graph G is said to be
k-vertex-connected (or k-connected) if it has more than k vertices
and remains connected whenever fewer than k vertices are removed.
[Menger's theorem] An equivalent definition is that a graph with at least two
vertices is $k$-connected
if, for every pair of its vertices, it is possible to find k vertex-independent
paths connecting these vertices.
A planar graph $G$ is called triangulated if every face is bounded by a triangle.
Answer: Suppose not, i.e. for some plane triangulation there is a separating set $S$ of size $k-1$ which does not contain a cycle.
Since $S$ is separating, we can divide the remaining vertices into two non-empty sets $T,U$ such that no edge connects $T$ to $U$. But since $S$ does not contain a cycle, the region of the plane remaining after removing $S$ and all edges spanned by $S$ is path-connected. In particular, there is a curve in the plane between a vertex in $T$ and a vertex in $U$.
Look at sequence of faces of the triangulation this curve passes through. Note that we can't move directly from a face with all vertices in $S\cup T$ to one with all vertices in $S\cup U$, since the common vertices to these faces would both be in $S$, but we never cross an edge between vertices of $S$. So the first face we encounter with a vertex in $U$ also contains some vertex in $T$. Since this face is a triangle, there is an edge between these vertices, contradiction.


How to change datagrid cell fore colors as dynamically using c#

Question: I know this is a stupid question but i can't get my desired out put.Actually i want change the datagridview cell fore colors as dynamically for this i have logic like this
 this.dataGridView1.Rows[0].Cells[1].Style.ForeColor = System.Drawing.Color.Red;

but this is  not apply to the cell(even cell background also not applied),
But i  get the fore color name what i assigned to the cell
   string colorname = this.dataGridView1.Rows[0].Cells[1].Style.ForeColor.Name;

.Is there any mistake in my query please help me.
Comment: Why `this.dataGridView1` in first line and `objPreview.dataGridView1` in second line? Is it a problem?
Comment: just i am creating object to the gridview that why i am using objPreview.dataGridView1.Now,i change that one.
Answer: To customize the styles of cells with particular values, implement a handler for the DataGridView.CellFormatting event. Handlers for this event receive an argument of the DataGridViewCellFormattingEventArgs type. This object contains properties that let you determine the value of the cell being formatted along with its location in the DataGridView control. This object also contains a CellStyle property that is initialized to the value of the InheritedStyle property of the cell being formatted. You can modify the cell style properties to specify style information appropriate to the cell value and location.
From MSDN
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 0 && e.RowIndex == 0)
        e.CellStyle.ForeColor = Color.Red;
}

The result is provided below:

Insert preferred indices instead of zeros in if statement to change ForeColor of only those cells that you need.
Comment: Hi thank you for giving response, i have check a link that is given by and i try the code, it is working but it apply all cells not a single cell.
Comment: yah i get one color if i set indices as 0,0 but when i need to set color at Row[0].cell[1] in this time it assign all the cells of second column not one cell.
Answer: Check this
dataGridView1[col, row].Style.ForeColor = Color.Blue;

I hope This help!


Cardinality of maps from {0,1} to R as binary numbers?

Question: I understand why the cardinality of maps from R(the real) to {0,1} would be 2^R. I heard about how the maps from {0,1} to R can be thought of as binary numbers(which are uncountable), but I can not visualize it. Can someone please help me?
Comment: I do not recommend visualizing maps from $\{0,1\}\to\Bbb R$ as binary numbers.  This is very simply going to be the set $\{\{(0,a),(1,b)\}~:~a,b\in\Bbb R\}=\{f(x)=\begin{cases}a&\text{if }x=0\\b&\text{if }x=1\end{cases}~:~a,b\in\Bbb R\}$.  In particular it has the function $f(x)=1$ and the function $f(x)=2$ and the function $f(x)=\sqrt{2}$ and the function $f(x)=3133742$ and the function $f(x)=y$ for any desired $y\in \Bbb R$
Comment: Maps $\mathbb N \to \{0,1\}$ can be thought of as binary real numbers in $[0,1]$ though there is a slight issue over dyadic fractions
Answer: Basically because the maps from $\{0,1\}$ to $\Bbb R$ can be thought of as pairs in $\Bbb R^2$ and the plane has the same size as $\Bbb R$.


aidl file is not working after moving one file to another package

Question: I am using aidl in my project . It was working fine, but after moving one java file to another package I can't build my project .
I am getting the following error .
Process 'command '/home/user/Android/Sdk/build-tools/28.0.3/aidl'' finished with non-zero exit value 1
Here is the content of my aidl file
import com.example.app.models.Conversation;
interface IAppService {
     List<Conversation> fetchConversation();
}

After I move my Conversation file to some other package, I no longer able to build , although the codebase  refactored to following .
import com.example.app.db.Conversation;
interface IAppService {
     List<Conversation> fetchConversation();
}

Answer: This is because you have changed the package of your file by moving your Conversation in another package.
If you are using AIDL between two application then the AIDL file of both the app should be in the same package Example:
If you have App_A and App_B communicating using AIDL then aidl file should be in the same package in both of the app or else you will get an error as java.lang.SecurityException
Comment: This is helpful : https://www.youtube.com/watch?v=QTxX5X3XxHE


$v\in\mathcal{L}(F,E)$ such that $u\circ v\circ u=u$

Question: Let $E,F$ two $\mathbb{K}$ vector spaces, $u\in\mathcal{L}(E,F)$.
a) Show that there exists $v\in\mathcal{L}(F,E)$ such that $u\circ v\circ u=u$
b) Can we additionally have $v\circ u\circ v=v$ ?

I have asked in the past Existence of $v\in\mathcal{L}(E)$ such as $u=u\circ v\circ u$, however here we are not talking about endomorphisms anymore. I have not managed to find an answer so far to any of the two questions.
Answer: I can do it for the infinite-dimensional case using the Axiom of Choice.  I suspect it requires some form of this axiom.
Let $W$ be the null space of $u$, and extend a basis  $\{e_\alpha\}_{\alpha \in A}$  of $W$ to a basis $\{e_\beta\}_{\beta \in B}$ of $E$.  Then the range of $u$ is the linear span of $\{u e_\beta\}_{\beta \in B \backslash A}$, which are linearly independent.  Extend this to a basis $\{w_\gamma\}_{\gamma \in \Gamma}$.
Then we define $v$ to map $u e_\beta$ to $e_\beta$ for $\beta \in B \backslash A$
and all other $w_\gamma$ to $0$.  This satisfies both $u v u = u$ and $v u v = v$.
Comment: Cool stuff! And a much more concise treatment of what I had in mind.
Answer: As with the last question you asked, the Moore-Penrose pseudoinverse will work here as long as $E$ and $F$ are finite dimensional inner product spaces.
Without using this, we could still make do, at least in the finite dimensional case:

Suppose $E$ and $F$ have dimensions $n$ and $m$.  Let $e_1,\dots,e_n$ be a basis for $E$ such that $u(e_1),\dots,u(e_r)$ gives a basis for the image of $u$ and $e_{r+1},\dots,e_n$ are in the kernel of $u$.
We can extend this into a basis $\{f_1 = u(e_1),\dots,f_r = u(e_r),f_{r+1},\dots,f_{m}\}$.  We define the map $v$ by $v(f_i) = e_i$ if $i \leq r$ and $0$ otherwise.
We now verify that $uvu = u$.  For $i \leq r$, we have
$$
uvu(e_i) = uv(f_i) = u(e_i)
$$
For $i > r$, we have $uvu(e_i) = u(e_i) = 0$.  So, $uvu(x) = u(x)$ for all $x \in E$.
Now, for $i \leq r$, we have
$$
vuv(f_i) = vu(e_i) = v(f_i)
$$
and for $i > r$, we have
$$
vuv(f_i) = v(f_i) = 0
$$
So, both conditions are satisfied.

I'm not sure if the same can be said for infinite dimensional vector-spaces.  Note my use of the rank-nullity theorem to ensure the numbers worked out correctly.


DateTime locale settings

Question: We are haveing issue with DateTime on one of our application servers.
The issue is the datetime is picking the locale settings as en-US and we want to use en-GB.
I tried to Change the server Regional and Language options to UK still having the same issue.
I could force DateTime to use en-GB but this will require code changes at various location.
I tried to add globalization settings in web.config file still date time is picked as US.
Is there a way I can fix this issue on that server since the code works fine on all other servers?
Answer: It should be sufficient to set the <globalization> section in web.config. Set both the culture and uiculture parameter. If that won't work you can set the locale per thread via global.asax.
void Application_BeginRequest(object source, EventArgs e)
{
   string Lang = "en-GB";
   System.Threading.Thread.CurrentThread.CurrentCulture =
      new System.Globalization.CultureInfo(Lang);
}

Comment: This will require code changes and we are currently in a code freeze state. The server we are having issue is a test server and we need to fix this on just one machine. Is there a change on the server side which can fix the issue? also I would like to know why the web.config does not work.
Comment: My guess is that the server was originally installed as en-us, and the locale settings for the user which your AppPool runs under still has this as the setting (http://www.justskins.com/forums/asp-net-application-wrong-culture-picked-up-59113.html). You could try to set globalization in machine.config as well.

DateTime locale settings


released the software to Google Market, but release supports zero device

Question: I released the software to Google Market, but release supports zero device.I configured the manifest file: android: targetSdkVersion = "15" />
I use Android version 4.1 compiler. Tried many ways or zero device. I hope someone can help solve the problem. Really thank you!
Comment: Have you activated your apk file?
Comment: I have packaged the signature app. can you help me ?
Comment: You also need to active the app in the Google Play console
Answer: You need minSdkVersion:
<code><uses-sdk android:targetSdkVersion="17"
         android:minSdkVersion="4" />
</code>
Comment: Hi , the manifest file I have declared this : ,but don't have userful,It's really Really weird.Can you continue help me ?
Comment: why you write android:targetSdkVersion="17" ,what is the difference when I write targetSdkVersion="15", I try write android:targetSdkVersion="15" ,someone's android device can download it and install it .why why? I almost collapsed .
Comment: see the accepted answer here: http://stackoverflow.com/questions/4568267/android-min-sdk-version-vs-target-sdk-version
Comment: However, as vmironov pointed out above your APK in Google Play should indicate that it is "in Prod".


proposal distribution for metropolis algorithm

Question: All,
I'm wondering whether it is possible to use an asymmetric distribution, eg the exponential distribution as the proposal dist'n for a metropolis algorithm (wiki) (not the metropolis-hastings). The reason I ask is because it is asymetric. For example, if I have the support of my desired probabilty distribution is (.2,4) could I use $$f(t,\lambda)=\lambda^{-\lambda t}$$
with $$\lambda=.5$$ could I us this to simulate eg the line y=x from 0http://www.mas.ncl.ac.uk/~ndjw1/teaching/sim/metrop/metrop.html I'm not sure you can just replace the line
<code>innov <- runif(1, -alpha, alpha)
</code>
with the exponential distribution...
Answer: As I understand it, the main difference between Metropolis and Metropolis-Hastings is the the former requires a symmetric proposal
distribution and the latter does not. The acceptance criterion
used by M-H 'corrects' for the 'bias' inherent in using an asymmetric distribution for moves to the next proposal.
In particular, I doubt that exponential moves you propose would work well even for M-H. You need to be able to move relatively freely
among possible proposals, Even if the exponential is offset so
that movement in both directions is possible, I think the M-H
acceptance criterion would essentially have to reject for a very
high proportion of jumps resulting from the long exponential tail.
Addendum (7/19): For archival purposes, I should note that
the main applications of both Metropolis and M-H methods is to
simulate from multivariate distributions, where choices of methods are often quite limited. Based on what I saw
in the reference you provide, this is a drill problem to sample
from a univariate distribution. There are much simpler acceptance-rejection methods for univariate cases that produce iid sequences (for example, see my answer to question 1358708 on this site).
Also, of course, sampling from the distribution of your reference
is most efficiently done by a direct method that does not use
acceptance-rejection at all. (I am not at all objecting to this
kind of drill exercise as a way towards understanding Metropolis and M-H;
I have assigned similar problems myself. But no one should mistake
Metropolis or M-H as an optimal sampling method in the current context.)


If I play G Sharp, then play the G that's one octave up, does the accidental carry over?

Question: For example, this ASCII sheet music:
<code>             G
trebel--------
|4------------
|-------------
|4--------#G--
clef----------
</code>
I know it's terrible, but would the second G be sharp too?
And for clarification, we're talking accidentals, not key signatures. I figured that key signatures apply to all octaves, otherwise we'd have a mountain of them...
Comment: "...on my clef, for example C..." that could be misunderstood to mean you are working with a _C clef_.
Comment: I don't know how to grammar very well, but I meant that the note on the whatever clef is C.
Comment: @MichaelCurtis - don't think it'll matter what clef is involved, the question would still remain the same, wouldn't it?
Comment: @Tim, given the recent edit I would say "no, the question doesn't remain the same." It went from seemingly about key signature changes to just how to read accidentals.
Comment: @MichaelCurtis - o.k., the question is now as I suspected. However, whatever clef is involved was never particularly relevant. Regardless if it involved key sigs. *or* accidentals.
Comment: @DaveRainbowin, I answered to provide some notation examples, but gave you the wrong information about octaves. I corrected my answer. Sorry to mislead you!
Answer: As it stands, the question isn't clear. Two ideas.
If you mean at the beginning, in the key signature, then no, it's not going to be correct. Unless there is already an F♯ and C♯ in that key sig., in which case, it will turn key D/Bm into key A/F♯m, and yes, every G will automatically become G♯.
If you mean in a particular bar, then no, any accidental will affect only the notes on that line/space, and also only for that particular bar. The next barline effectively cancels that accidental.
That's one reason they're called accidentals - they're there temporarily. The ♯ and ♭ in the key sig. are not accidentals - they're there on purpose!
So, any accidental will affect only the note/s it applies to until the end of that bar, unless cancelled earlier, usually with a natural (♮) sign. A sharp on middle C line will not automatically change any other C notes anywhere else in that bar. If they need sharpening, they will need a sharp sign in front of them too.
Answer: Accidentals apply to a single bar and a single octave.

Accidentals do not carry over to new bars. A "courtesy" accidental can be used to aid reading and show the tone changed back to the key signature value.
Answer: The sharps and flats in a key signature apply to all pitches of the same pitch class.

If an accidental (a note outside of the key signature) sharp, flat, or natural occurs in a bar, only the notes on that particular line or space in that bar are affected.  i.e. an accidental on a G, will not affect the G's an octave above or below.
This is the modern engraving technique.

An older tradition for engraving has a different rule:  That the entire pitch class is affected by an accidental.  i.e. the G's an octave above and below it in the bar are affected too.

If you really want to be unambiguous, you can write courtesy accidentals:  Accidentals (that are already implied) written in parentheses.
Comment: And a still older tradition required key signatures to be repeated in every octave.  When did accidentals apply to multiple octaves?  I've never seen it.
Answer: There are different answers here about accidentals, because there's no one correct answer.  As someone noted in one answer, the modern convention is to assume that accidentals on one pitch only apply to that specific line/space, not to notes an octave above or below in the same bar.
However, this was not always the convention.  And different people at different times in history and in different places may have assumed various things.  Historically, it was therefore most common to be explicit about what happened to notes in other registers with the same name.  If you wanted a G# and marked it sharp, but another note G occurred an octave above later in the bar, it would typically be marked explicitly with either a natural or a sharp (depending on the intent).  The natural would not be merely thought of as a "courtesy" accidental, but would generally be required for the sake of clarity.
I still think this latter convention is the least confusing, and I'd recommend using it.  Otherwise, unless it's a piece of modern atonal music that has odd accidentals to begin with, there's usually going to be a debate among performers -- "Is this supposed to be natural?  I don't know.  Maybe it's an editorial mistake and they forgot a sharp.  We'll have to look at other parts...."
So, generally speaking, in a modern score with a lot of chromaticism, I'd assume that sharps and flats only correspond to their particular line/space, but honestly that convention cannot be assumed to be universally true (as seen in some other answers here).  It's pretty rare to see situations where an accidental is assumed to apply in all octaves, and I think the only place I've seen it is in some really abbreviated types of notation, like lead sheet charts or some loosely edited jazz parts.  (And I'm pretty sure even that is rare.)
Answer: Yes, the key signature applies to all notes on the staff, regardless of the octave.
In fact, the key signatures are fixed, as in, there is only one "proper" way to notate any key signature. The first accidental should be as high as possible within the staff (so not including the spaces "resting" just outside the lines). If the key signature has sharps, the position alternates going down a fourth then up a fifth. If the key signature has flats, the position alternates going up a fourth then down a fifth. After the first accidental, however, the accidentals can be put on the spaces just outside the staff -- if alternating the "up/down a fourth then down/up a fifth" rule puts the accidental on/above a ledger line, then you break the pattern for that one note.
Comment: Strictly speaking, those #/b in a *key signature* are not *accidentals* - anything but. They're there on purpose! There must be a better, more apposite word for those at the beginning of each line. And, while I'm moaning, why put them at the beginning of each line - we only put the *time sig.* at the beginning of the piece!?
Comment: @jjmusicnotes - let's say a piece is in 4#, but the key sig. is missing in the subsequent lines, there are only a few clues that it hasn't gone into C or Em, for instance. There are those who purely read - read what's in front of them, with not much regard to where the music's going. It wouldn't help them. Reading accidentals as they come! Sound like me, highlighting all the F# and C# as I went! But for film music, et al, which continually changes, it actually might be easier to write it in an agnostic key, and add as it goes along. Reading that is a different skill !
Comment: some old scores don't order the sharps and flats this way.
Comment: @Tim - for many types of music the time signature does not change nearly as often as the pitch relationships do. Also, for  keyboard / wind / string instruments, key signatures take up proportionally more mental real estate. (I know you are a guitar player and thus every key is equally easy!)
Comment: @jjmusicnotes - and just maybe, the answer is that if there was no key sig. on each line, players would consider it to be in C!!
Comment: @Tim - some might on first glance, but a look at the music itself would give them plenty of information. Tangentially, most "new music" people nowadays prefer to read music without key signatures, reading accidental as they come.
Answer:
I have a treble clef and put a sharp on the G part of the G Clef ...

The question implies to me that you are asking about accidentals and not key signs, as it is logical that key signs are affecting all notes (and it would also imply that not only a G would have a sharp following the clef but also the F# and C#):
So I assume the question is referring to accidentals which affect all  notes of the same pitch in the same bar. If needed the accidental has to be repeated and added to a G in another octave:
If a note has an accidental and the note is repeated in a different octave within the same measure the accidental is usually repeated, although this convention is far from universal.
https://en.wikipedia.org/wiki/Accidental_(music)


What is the inverse of $f(x) = a⋅e^{bx} + cx + d$

Question: Does an inverse function for
$f(x) = a⋅e^{bx} + cx + d$
exist where a, b, c, d are constants?  If so, what is it?
I've tried lots of methods, but they've all failed.
What I ended up doing to approximate an inverse:
For very small (very negative) values of y, I ended up using the following function:
$x = \frac{ln(\frac{y-cx-d}{a})}{b}$
to assist in a recursive approximation by which, after seeding x with a guess, I feed the function back on itself a few times.  For greater values of y, I used a similar method/function inspired by binary search algorithms. My implementations converged quickly for my purposes.
Thanks everyone who commented.
Comment: @CameronWilliams But distinguish between the two cases (1) There is no inverse because the function is not $1-1$ and (2) There is an inverse, but not one with a closed form.
Comment: There isn't a solution in general. Some might reference the W Lambert function but I am not a fan of that argument. It's almost like saying "the solution is the solution!" The W Lambert function is constructed to be a solution to a related problem so it's circular to me.
Comment: @CameronWilliams The one nice thing about special functions like the Lambert W function is that they reduce a large family of problems to a smaller family of problems. This makes robust numerical implementation a lot easier. Solving an equation like that in the OP with Newton's method, the convergence properties may depend very strongly on the parameters.
Comment: @CameronWilliams: the benefit of "standardizing" the problem to the Lambert function is that the latter is a well-studied function. As soon as you reduce a problem to it, you immediately "inherit" all the knowledge about it. For instance, we know that it has no closed form.
Comment: @ThomasAndrews Oh doh. I meant to say "no solution in elementary functions." Slipped my mind. You're completely right.
Comment: I agree with Ian and Yves Daoust. So, it's not surprising that I dislike the comment of Cameron Williams : << It's almost like saying "the solution is the solution!" The W Lambert function is constructed to be a solution to a related problem so it's circular to me. >>  Saying this is the same as saying  << The $\arcsin(x)$  function is constructed to be a solution to the problem of solving for $\alpha$ the equation $\sin(\alpha)=x$  so it's circular to me : It's almost like saying "the solution is the solution!".
Comment: In fact, there is no difference of concept between $\arcsin(x)$ and W($x$), except that  one is more common that the other. They are several examples of this kind in the paper : https://fr.scribd.com/doc/14623310/Safari-on-the-country-of-the-Special-Functions-Safari-au-pays-des-fonctions-speciales
Answer: Consider $$y = a⋅e^{bx} + cx + d$$ and make a change of variable $e^{bx}=z$. This then leads to $$y=a.z+\frac cb .\log(z)+d$$Any equation which can write $A+B x+C\log(Dx+E)=0$ has solution(s) in terms of Lambert function. For the particular case in the post, we should then obtain $$z=\frac{c }{a b}W(t)$$ where $$t=\frac{a b }{c}e^{\frac{b (y-d)}{c}}$$ and, back to $x$ (taking into account the fact that $t=W(t).e^{W(t)}$), $$x= \frac{y-d}{c}-\frac{1}{b}W(t)$$ The advantage of this is that there are very good approximations of Lambert function.
For illustration purposes, let us use $a=1,b=2,c=3,d=10^6$ and let us try to solve the equation for $y=2.10^6$. So, replacing, we have $$x=\frac{1000000}{3}-\frac{1}{2} W\left(\frac{2 e^{2000000/3}}{3}\right)$$ Now, let us use for the approximation $$W(t)\approx L_1-L_2+\frac{L_2}{L_1}+\cdots$$ where $L_1=\log(t)$,$L_2=\log(L_1)$. This then leads to $x=6.907744917$ which is the exact solution for ten significant figures.
Answer: It is quite possible for a function to have an inverse but with no closed formula for the inverse.
In this case, $f(x)$ is $1-1$ if and only if $f'(x)\neq 0$ for all $x$ in the (interior of the) domain, which means if $abe^{bx}\neq -b$ has no solution, so if $\frac{-d}{ab}$ is negative.
However, combinations of $x$ and $e^x$ generally make it impossible to find a formula for the inverse function.
We can easily find a way to compute the inverse when $f$ is increasing or decreasing - just apply a binary-search algorithm to get a sequence of approximations to the inverse.


C# Getting proxy settings from Internet Explorer

Question: i have a problem in certain company in germany. They use proxy in their network and my program cant communicate with server.
IE works with this settings:

It means:
Automatically detect settings
This is the code:
public static bool CompleteValidation(string regKey)
{
    string uri = "***";

    int c = 1;
    if (Counter < 5) c = 6 - Counter;
    string response = "";
    try
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
        request.AllowWriteStreamBuffering = true;
        request.Method = "POST";
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0";
        request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        request.Headers.Add(HttpRequestHeader.AcceptLanguage, "pl,en-us;q=0.7,en;q=0.3");
        request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
        request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-2,utf-8;q=0.7,*;q=0.7");
        request.KeepAlive = true;

        //proxy settings
        string exepath = Path.GetDirectoryName(Application.ExecutablePath);
        string proxySettings = exepath + @"\proxy.ini";
        WebProxy wp = new WebProxy();
        if (File.Exists(proxySettings)) {
            request.Proxy = WebRequest.DefaultWebProxy;
            IniFile ini = new IniFile(proxySettings);
            string user = ini.IniReadValue("Proxy", "User");
            string pass = ini.IniReadValue("Proxy", "Password");
            string domain = ini.IniReadValue("Proxy", "Domain");
            string ip = ini.IniReadValue("Proxy", "IP");
            string port_s = ini.IniReadValue("Proxy", "Port");
            int port = 0;
            if (!string.IsNullOrEmpty(ip))
            {
                if (!string.IsNullOrEmpty(port_s))
                {
                    try
                    {
                        port = Convert.ToInt32(port_s);
                    }
                    catch (Exception e)
                    {
                        ErrorLog.AddToLog("Problem with conversion of port:");
                        ErrorLog.AddToLog(e.Message);
                        ErrorLog.ShowLogWindow();
                    }
                    wp = new WebProxy(ip, port);
                } else {
                    wp = new WebProxy(ip);
                }

            }
            if (string.IsNullOrEmpty(domain))
                wp.Credentials = new NetworkCredential(user, pass);
            else
                wp.Credentials = new NetworkCredential(user, pass, domain);
            request.Proxy = wp;
        }

        string post = "***";
        request.ContentLength = post.Length;
        request.ContentType = "application/x-www-form-urlencoded";
        StreamWriter writer = null;
        try
        {
            writer = new StreamWriter(request.GetRequestStream()); // Here is the WebException thrown
            writer.Write(post);
            writer.Close();
        }
        catch (Exception e)
        {
            ErrorLog.AddToLog("Problem with request sending:");
            ErrorLog.AddToLog(e.Message);
            ErrorLog.ShowLogWindow();
        }
        HttpWebResponse Response = null;
        try
        {
           Response  = (HttpWebResponse)request.GetResponse();
        }
        catch (Exception e)
        {
            ErrorLog.AddToLog("Problem with response:");
            ErrorLog.AddToLog(e.Message);
            ErrorLog.ShowLogWindow();
        }

        //Request.Proxy = WebProxy.GetDefaultProxy();
        //Request.Proxy.Credentials = CredentialCache.DefaultCredentials;
        string sResponseHeader = Response.ContentEncoding; // get response header

        if (!string.IsNullOrEmpty(sResponseHeader))
        {
            if (sResponseHeader.ToLower().Contains("gzip"))
            {
                byte[] b = DecompressGzip(Response.GetResponseStream());
                response = System.Text.Encoding.GetEncoding(Response.ContentEncoding).GetString(b);
            }
            else if (sResponseHeader.ToLower().Contains("deflate"))
            {
                byte[] b = DecompressDeflate(Response.GetResponseStream());
                response = System.Text.Encoding.GetEncoding(Response.ContentEncoding).GetString(b);
            }
        }
        // uncompressed, standard response
        else
        {
            StreamReader ResponseReader = new StreamReader(Response.GetResponseStream());
            response = ResponseReader.ReadToEnd();
            ResponseReader.Close();
        }
    }
    catch (Exception e)
    {
        ErrorLog.AddToLog("Problem with comunication:");
        ErrorLog.AddToLog(e.Message);
        ErrorLog.ShowLogWindow();
    }

    if (response == "***")
    {
        SaveKeyFiles();
        WriteRegKey(regKey);
        RenewCounter();
        return true;
    }
    else
    {
        return false;
    }

}

My program logs it as:
[09:13:18] Searching for hardware ID
[09:13:56] Problem with response:
[09:13:56] The remote server returned an error: (407) Proxy Authentication Required.
[09:15:04] problem with comunication:
[09:15:04] Object reference not set to an object instance.

If they write user and pass into proxy.ini file, program works. But the problem is they cant do that. And somehow IE works without it. Is there any way to get those settings from IE or system?
Comment: First of all, in the catch (Exception e) get rid of e.message and just log e. This way you get a stack trace and you can figure out what object is null.
Comment: ttymatty: its still not complete code but the problem is earlier than `Object reference not set to an object instance.` Look at `The remote server returned an error: (407)` when trying to `Response  = (HttpWebResponse)request.GetResponse();`. Response is null because it wasnt authorized.
Answer: Use GetSystemWebProxy to return what the system default proxy is.
    WebRequest.DefaultProxy = WebRequest.GetSystemWebProxy();

But every HttpWebRequest should automatically be filled out with this information by default. For example, the following snippet in a standalone console application should print the correct information on a system with a PAC file configured.
    HttpWebRequest myWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");

    // Obtain the 'Proxy' of the  Default browser.
    IWebProxy proxy = myWebRequest.Proxy;
    // Print the Proxy Url to the console.
    if (proxy != null)
    {
        Console.WriteLine("Proxy: {0}", proxy.GetProxy(myWebRequest.RequestUri));
    }
    else
    {
        Console.WriteLine("Proxy is null; no proxy will be used");
    }

Comment: Isn't it the same thing as: `request.Proxy = WebRequest.DefaultWebProxy;` ?
Comment: Yes you are right. If you execute the code I posted, does the system have a proxy or not? It's hard to tell with "automatic configuration" selected in Internet Options.
Comment: It's not working. Where else can be a problem? In request headers?
Comment: If you execute the console code I posted, does the system have a proxy or not?
Comment: Yes of course. I wrote earlier: "If they write user and pass into proxy.ini file, program works."
Comment: You are missing my point. I posted code that will tell you if the system is even aware of a proxy. According to the IE screenshot you posted, it is not aware of a proxy, it is set to "autoconfiguration". If my suspicion is true, using `WebRequest.DefaultWebProxy` will buy you nothing because there isn't a proxy configured on the end user's system. However I'm not sure and I asked you to try executing those 6 lines of code so that we can verify whether it is even possible to use this API to determine the proxy settings. My suspicion is that it's a network proxy and therefore the API is useless.
Comment: If DefaultWebProxy doesn't work (please verify), then you could investigate using WPAD: http://stackoverflow.com/questions/191023/how-does-windows-actually-detect-lan-proxy-settings-when-using-automatic-confi
Answer: Use DefaultNetworkCredentials to return system proxy credentials.
request.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;


How can I add a header and footer field to all drupal generated blocks?

Question: I have a number of blocks that are created by drupal core, modules and views. In views blocks I can add a header or footer using the views UI, but I would also like to do this for other blocks not created by views. e.g. core search block. I would like to add a user configurable header and footer field to every block generated by drupal. This way a user can add arbitrary content above or below block content using the block UI. Doing this for all views blocks would be great as well as I would not have to give the client permissions and train them how to use the views UI to make changes.
EDIT:
Each block needs to have their fields configurable in the UI. I can't have laypersons digging into the tpl files.
Switching to an entity based block replacement such as the BEAN module is not an option. I need to keep the core block architecture and it also must be able to add headers and footers to core and module generated blocks (which are not beans, boxes etc)
Answer: You can use block.tpl.php

Default theme implementation to display a block

And add html in the same template file.
Comment: I need this to be configurable by a layperson. I cannot have them dig into the tpl files and play around. They need to be able to do this on the fly.


Bayesian SEM: LOO-CV / Fit Measures

Question: I am running various bayesian path models in r ('blavaan' package). I understand that LOO is a more robust fit index when working with a smaller samples size (and weakly informative priors). I am using LOO-CV (PSIS) method to compare path models; however, I have additional questions.

How do I interpret LOO-CV values to determine which model has the better fit?
Should multiple fit indices be present in bayesian SEM results?
Is there an alternative r package that runs 'loo-cv' analyses? The "loo" package will not load.

Thank you.
Answer:
LOO-CV works like an information criterion (lowest value wins): for comparison, not an index for evaluating fit in an absolute sense.
"present"?  Multiple are available.
blavaan provides the DIC, WAIC, and LOO-IC (approximation to LOO-CV) via the loo package.  If you have trouble with installing it, that is a separate issue to post about (e.g., on StackOverflow, or the Stan forum).  You can read through all their introductory information on the blavaan web site.
Comment: Thank you very much! This was very helpful. (also - apologies *presented,* "present" was a typo)

Bayesian SEM: LOO-CV / Fit Measures


Spring Initialisation Order with Configuration

Question: I have a Spring project, and I need to configure Flyway.
Using the default FlywayAutoConfiguration, Flyway migration is immediatly executed before everything else (caching, PostConstruct annotations, services). This is the behavior I expected (in term or startup workflow)
Unfortunatly, I need to override the default FlywayAutoConfiguration because I use a custom Flyway implementation, but that's not the my main problem here, my issue is really related to Spring Priority for configuration and initialization sequence.
So do use my own flyway, I first copied FlywayAutoConfiguration to my maven module, name it CustomFlywayAutoConfiguration and just adapt imports. I also change the property "spring.flyway.enabled" to false and create another one "spring.flywaycustom.enabled" to be able to activate mine and not the default one.
Doing that fully change the sequence of startup. Now, flyway is executed at the end of the startup sequence (after caching and other @PostConstruct that are in my project)
The following bean defined in CustomFlywayAutoConfiguration is now created onyl at the end of the startup sequence. With the default FlywayAutoConfiguration , was well created on the beginning.
@Bean
    @ConditionalOnMissingBean
    public FlywayMigrationInitializer flywayInitializer(Flyway flyway,
            ObjectProvider<FlywayMigrationStrategy> migrationStrategy) {
        return new FlywayMigrationInitializer(flyway, migrationStrategy.getIfAvailable());
    }

I tryied to play a lot with ordering (HIGHEST_PRECEDENCE, and LOWEST_PRECEDENCE)

@AutoConfigureOrder on configuration class
@Order on components
Try to Autowire FlywayMigrationInitializer to force the bean initialisation earlier

It's doesn't change anything, looks like Spring ignore @Order and @AutoConfigureOrder
Any idea why when Configuration is inside spring-boot-autoconfigure dependencies, it started as first priority, and when the same Configuration code is inside my project, I don't have the same ordering?
Thank you so much for your help.
Answer: Thanks to your answer, Focusin my attention FlywayMigrationInitializerEntityManagerFactoryDependsOnPostProcessor help me to solve the issue.
@Configuration(proxyBeanMethods = false)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@EnableConfigurationProperties({ DataSourceProperties.class, FlywayProperties.class })
@Import({ FlywayMigrationInitializerEntityManagerFactoryDependsOnPostProcessor.class }) // Very important to force flyway before
public class CustomFlywayConfiguration {

    @Bean
    public Flyway flyway(FlywayProperties properties, DataSourceProperties dataSourceProperties,
            ResourceLoader resourceLoader, ObjectProvider<DataSource> dataSource,
            @FlywayDataSource ObjectProvider<DataSource> flywayDataSource,
            ObjectProvider<FlywayConfigurationCustomizer> fluentConfigurationCustomizers,
            ObjectProvider<JavaMigration> javaMigrations, ObjectProvider<Callback> callbacks) {
        FluentConfiguration configuration = new FluentConfiguration(resourceLoader.getClassLoader());
        DataSource dataSourceToMigrate = configureDataSource(configuration, properties, dataSourceProperties, flywayDataSource.getIfAvailable(), dataSource.getIfUnique());
        checkLocationExists(dataSourceToMigrate, properties, resourceLoader);
        configureProperties(configuration, properties);
        List<Callback> orderedCallbacks = callbacks.orderedStream().collect(Collectors.toList());
        configureCallbacks(configuration, orderedCallbacks);
        fluentConfigurationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(configuration));
        configureFlywayCallbacks(configuration, orderedCallbacks);
        List<JavaMigration> migrations = javaMigrations.stream().collect(Collectors.toList());
        configureJavaMigrations(configuration, migrations);
        return new CustomFlyway(configuration);
    }

    /**
     * FlywayAutoConfiguration.FlywayConfiguration is conditioned to the missing flyway bean. @Import annotation are not executed in this case.
     *
     * So if we declare our own Flyway bean, we also need to create this bean to trigger the flyway migration.
     *
     * The main issue is now that bean is create after the @PostConstruct init method in MyInitComponent.
     *
     */
    @Bean
    public FlywayMigrationInitializer flywayInitializer(Flyway flyway,
            ObjectProvider<FlywayMigrationStrategy> migrationStrategy) {
        return new FlywayMigrationInitializer(flyway, migrationStrategy.getIfAvailable());
    }

    /**
     * Thanks to that, it's now working, because make sure it's required before to create EntityManager
     */
    // @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class)
    // @ConditionalOnBean(AbstractEntityManagerFactoryBean.class)
    static class FlywayMigrationInitializerEntityManagerFactoryDependsOnPostProcessor
            extends EntityManagerFactoryDependsOnPostProcessor {

        FlywayMigrationInitializerEntityManagerFactoryDependsOnPostProcessor() {
            super(FlywayMigrationInitializer.class);
        }

    }

...

So that confirm we can't easily override the Flyway bean without copy some logic from FlywayAutoConfiguration.
I created a small project to reproduce the bug, with the solution I found.
https://github.com/w3blogfr/flyway-issue-demo
I don't know if it's necessary to fix it or not in spring auto-configuration project?
I checked the history to find back the commit
https://github.com/spring-projects/spring-boot/commit/795303d6676c163af899e87364846d9763055cf8
And the ticket was this one.
https://github.com/spring-projects/spring-boot/issues/18382
The change looks technical and probably he missed that was an @ConditionalOnClass
Answer: None of the annotations that you've described have an impact on runtime semantics:

@AutoConfigureOrder works only on auto-configurations (so if you've copied the auto-configuration as a user config, it won't even be considered). This is used to order how auto-configurations are parsed (typical use case: make sure an auto-config contribute a bean definition of type X before another one check if a bean X is available).
@Order orders components of the same type. Doesn't have any effect as to "when" something occurs

Forcing initialisation using an injection point is a good idea but it'll only work if the component you're injecting it into is initialised itself at the right time.
The auto-configuration has a bunch of post-processors that create links between various components that use the DataSource and the FlywayMigrationInitializer. For instance, FlywayMigrationInitializerEntityManagerFactoryDependsOnPostProcessor makes sure that FlywayMigrationIntializer is a dependency of the entity manager so that the database is migrated before the EntityManager is made available to other components. That link is what's making sure Flyway is executed at the right time. I don't know why that's not working with your copy, a sample we can run ourselves shared on GitHub could help us figure out.
With all that said, please don't copy an auto-configuration in your own project. I'd advise to describe your use case in more details and open an issue so that we consider improving the auto-configuration.


how to programmatically alter the rendering of a field in Views

Question: I have a content type called 'Ping'. It has several fields and one of them is a url by the name 'filename'. I want the View of all such pings, names 'user-pings' to display not the url itself, but a link to it. How do I do that?
I've tried the following, but it doesn't work:
function feedback_views_pre_render(&$view)
{

    if( $view->name === 'user_pings' )
    {

        foreach( $view->result as $key => $val )
        {
           $lang = $view->result[$key]->_field_data['nid']['entity']->language;
           $field = $view->result[$key]->_field_data['nid']['entity']->field_filename[$lang][0];
           $filename = $field['value'];
           $link = "(download)";
           $view->result[$key]->_field_data['nid']['entity']->field_filename[$lang][0]['value'] = $link;
           $view->result[$key]->_field_data['nid']['entity']->field_filename[$lang][0]['safe_value'] = $link;

        }

    }

}

Additionally, if this code is a try in the right direction, I would very much like to learn how to do the same thing in less code.
Cheers and thanks in advance,
Alan
Comment: Can't you use the https://drupal.org/project/link module for this?
Answer: You can do that in the views interface, no need for pre- or post- processing on the theme level (as your script snippet suggests).
I assume that you are using Drupal 7.x and Views 7.x-3.x.
Go to the UI for the view you want to change:
http://example.com/admin/structure/views/view/yourviewname/edit
or Home » Administration » Structure » Views » Yourview

Make sure you are on the Display that you want to change (towards the top: Display has tabs "Page", "Add" and maybe others like "Block" or similar)
Under "Format", it shows "Format" and "Show". "Show" needs to be set to "Fields".
The click on the field with your url, like:
 Content: URL (URL)

A popup window will open with:
 Configure field: Content: URL

Click on "Rewrite Results" - a number of options open, check:
 Rewrite the output of this field

A couple of additional fields now open up.
Click on "Replacement patterns" and identify your url field, for example:
[field_url]

Now, enter the text you want to display into the "TEXT" field (can be html tags like an image tag):
An image tag
Some text

Check "Output this field as a link", and enter the replacement pattern into the "Link path " field [field_url].
If you want to use another field from your content type to show instead of something generic, that field needs to be on the "Fields" list BEFORE the field_url field, but can be marked as "invisible" if you don't want to display it otherwise.
Comment: Thanks, by following your answer step-by-step I was able to achieve exactly what I wanted to achieve. However, I am still wondering how someone would accomplish this programmatically ...
Comment: I also want to know how to achieve the same output programmatically.


ShareThis in header rather than content type?

Question: I am adding Drupal ShareThis to a header mini-panels, but the buttons are not displayed. Firebug tells me that the corresponding code is not there at all. How can I display ShareThis buttons outside of content types?
Answer: Please try the following:

Go to menu Structure>Blocks.
find the ShareThis block.
set the block region settings for the theme you are using
go to block configuration and make sure the block is visible for all required pages, content types, roles, users
go to menu Configuration>Web Services>ShareThis
go to 'Advanced' section
find 'Location' settings
select 'Block' to select the ShareThis widget should appear as a block and not in a node content.
Comment: I tried all of this, but it did not solve the issue. The save configuration does not work in 2.3 (http://drupal.org/node/1507684). I think it has to do with a regression between ShareThis 2.2 and 2.3. I reinstalled 2.2 and it worked.


Very basic derivative question

Question: Why is the derivative of
$e^x + e^{-x}$
equal to
$e^x - e^{-x}$
?
Answer: By the chain rule, the derivative of $e^{f(x)}$ is $f'(x)e^{f(x)}$. Hence, $$\frac{d}{dx}[e^{x} + e^{-x}] = \left[\frac{d}{dx}(x)\right]\cdot e^{x} + \left[\frac{d}{dx}(-x)\right]\cdot e^{-x} = e^{x} - e^{-x}$$

Very basic derivative question


weakly convergence imply strong convergence when $ \|f_n\| \rightarrow \|f\| $ in $l^2([0,1])$?

Question: I know in general weakly convergence do not imply strong convergence in $L^p$,but in  $L^2[0,1]$ space which if we have additional condition do this condition plus the weak convergence will give us strong convergence?
The additional condition is $f \in L^2[0,1]$ and $ \|f_n\| \rightarrow  \|f\| $
Comment: You are right.I will delete my post when I will be more sure about it.thanks
Answer: This is true in an arbitrary Hilbert space:
$$\|f_n - f\|^2 = \langle f_n-f,f_n-f\rangle = \langle f_n, f_n\rangle -\langle f_n,f\rangle - \langle f,f_n\rangle +\langle f,f\rangle\to 0.$$


Can a wald test be computed for Binomial data with 0 successes?

Question: Suppose I observe 0 successes out of $n$ binomial trials.
A Wald test would have me compute
$$ \dfrac{(\hat{\pi}  - \pi_0)^2}{\widehat{V}(\hat{\pi}_j)} \sim X^2_1$$
But the estimated variance is 0.  Is a Wald test not appropriate for cases where no successes (or failures) are observed?
Comment: See also https://stats.stackexchange.com/questions/319643/is-this-a-valid-way-to-construct-a-confidence-interval
Answer: I cannot think of a single reason, other than perhaps ignorance, to use the Wald test or Wald interval for this problem. The fact that, as you noted, it can lead to a zero estimated variance is one of the problems with it.
The default test is the score test; the Wald method is sometimes used to build intervals. One way to repair the Wald interval in this case is to add two successes and two failures. This approximates, but is slightly wider than, the score interval, and generally has good coverage properties.
Comment: @kjetilbhalvorsen See [this paper](http://users.stat.ufl.edu/~aa/articles/agresti_coull_1998.pdf).
Comment: Do you have  reference for "to add two successes and two failures"?


Como ver se foi selecionado um arquivo em input do tipo "file"?

Question: Existe alguma forma de saber se o input do tipo file tem algum arquivo ja carregado, pronto para ser enviado?
Quero fazer uma condição onde se tiver algum arquivo para fazer upload no primeiro input, então mostre um botão de add mais um input do tipo file e assim sucessivamente.
É possivel?
Answer: Você só precisa, no evento change() do seu <input type=file> verificar o valor dele, se for diferente de vazio, mostre o botão de adicionar outro, que estaria até então escondido(suposição) e adicione um evento de click() a ele que adicione outro <input type=file> ao seu documento, que seria isto:
function verificaMostraBotao(){
    $('input[type=file]').each(function(index){
        if ($('input[type=file]').eq(index).val() != ""){
            $('.hide').show();
        }
    });
}

$('input[type=file]').on("change", function(){
  verificaMostraBotao();
});

$('.hide').on("click", function(){
    $(document.body).append($('<input />', {type: "file" }).change(verificaMostraBotao));
    $('.hide').hide();
});

E o HTML seria esse:
<input type=file>
<input type=button class=hide value="Adicionar outro">

Com o devido css para esconder o botão:
.hide {
    display: none;
}

Exemplo no JSFiddle
Comment: Isso ai garoto, hehe... mais uma vez Obrigado!
Comment: É bem isso Paulo, só que assim.. se o cara clicou para add no primeiro queria que o botao de add + desaparecia  e aparecesse só quando o próximo input tbm estiver carregado. É possivel?
Comment: pronto @JeffersonAlison
Comment: Estou aqui pra isso :) Disponha
Answer: Você pode usar o evento change do input para saber quando algum arquivo for selecionado:

Referência no SO em inglês... então vale a pena checar.
Answer: você pode usar um onchange no input, assim quando você adicionar o arquivo será possível executar uma função, se você já tiver a função que mostra o botão pronta é só adicionar isso.
function addinput(){
            var input = document.createElement("input");
            input.type = "file";
            input.name = "upload";
            document.getElementById("imgform").appendChild(input);
        }

pequemos essa função que gera uma tag input como exemplo
<input name="upload" id="img" type="file" accept="image/png, image/jpg, image/gif" onchange="addinput()">

Quando o arquivo for adicionado o onchange detectara a mudança e irá executar a função addinput fazendo com que um novo input apareça logo abaixo
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Why size of a string compressed by LZMA-JS is approx. 10x bigger then before the compression

Question: I'm trying to find a way to reduce size of BASE64 encoded images that I'm sending to the server. I found that question where LZMA is suggested solution. However when I check request size on the server I see that size of the uncompressed version is ~10 times smaller. Do I missing a step? I see that result of compression is a Byte Array I tried to use .toString('utf8') method but it seems it just join the array.
/* LZMA COMPRESS / DECOMPRESS */
.factory('ooLZMA', ['CONFIG', function (CONFIG) {
  return {
    compress: function (string) {
       return LZMA.compress(string, CONFIG.stringCompression);
    },
    decompress: function () {
      return LZMA.decompress(string);
    }
  }
}])

And on the server:
console.log('size', req.headers['content-length'] / 1048576, 'comp', req.body.compressed);

//"compressed"
size 0.1276998519897461 comp true
//raw BASE64
size 0.01657390594482422 comp false

Comment: There are two issues that might be causing the issue.

1. If you read the accepted answer to the question you mentioned you can see that the LZMA JS library is creating a signed byte array and the server is using an unsigned one.

2. What format are the images in before you base64 encode them, a lot of image formats are already compressed so base64 encoding them and then compressing the resultant string will almost certainly increase the size of the data.
Answer: This is due to format convertion.
If you send the BASE64 encoding it is already a string and it is sent as it is to the server.
An array instead is converted to a string before the actual request.
If your data cannot be compressed too much the compressed one is going to have a similar size, but the string convertion operation will increase it because each number on average in 10/12 chars long.
If you are using jquery I think this is the correct way to post the data.
Sending binary data in javascript over HTTP
By setting the actual content type 'application/octet-stream' and avoiding the preprocessing/convertion.