How to get a recurrence relation from an expression with maximum

Question: There is a certain function $F(r,s)$ (where $r\geq -1$ and $s\geq 0$ are integers) that satisfies the following relation:
$$
\max\big[2 F(r,s) - F(r-1,s) - F(r-1,s-1)~~~,~~~F(r+1,s+1) - F(r-1,s)\big] =  0
\\
F(r,0)=1 ~~~~~ \forall r\geq 0
\\
F(0,s)=0 ~~~~~ \forall s\geq 1
\\
F(-1,s)=0 ~~~~~ \forall s\geq 0
$$
Is there a way to get from this relation, an explicit recurrence relation on $F(r,s)$, so that I can numerically compute e.g. $F(1000,1000)$?
NOTE: I had a similar function $G(r,s)$ that satisfies the following similar relation:
$$
\max\big[2 G(r,s) - G(r-1,s) - G(r-1,s-1)~~~,~~~G(r,s) - G(r-2,s-1)\big] =  0
\\
G(r,0)=1 ~~~~~ \forall r\geq 0
\\
G(0,s)=0 ~~~~~ \forall s\geq 1
\\
G(-1,s)=0 ~~~~~ \forall s\geq 0
$$
Here I managed to find the solution myself. There are two cases: either the leftmost term is larger, and then $G(r,s)=[G(r-1,s) - G(r-1,s-1)]/2$, or the rightmost term is larger, and then $G(r,s)=G(r-2,s-1)$. Therefore, the recurrence relation is:
$$
G(r,s) = \min\big[
[G(r-1,s) - G(r-1,s-1)]/2
~~~,~~~
G(r-2,s-1)
\big]
$$
From this relation and the boundary conditions, it is easy to compute $G(1000,1000)$.
But, this does not work with $F$. How can I get a recurrence relation on $F$?
Comment: The previous case you solved has a unique solution. However, with the new recursion formula there are multiple solutions (assuming the condition of my previous comments). For example, the function G is a solution (it satisfies the recursion formula), but also $F(r,s)=G(r-1,s)$ is a solution. I'm pretty sure that you can vary the parameter t=F(2,1) freely between 1/2 (first solution F=G) and 0 (the second solution), but I haven't done the full computations. Moreover, you can also vary other entries of F. What can be proven is that F(r,s)=0 for $r\le s-1$ if $r\ge 1$ and $(r,s)$ is not $(2,1)$.
Comment: Do you mean $r,s$ integers, or $r,s$ non negative integers?
Comment: It is not clear to me how the case you mention for $G$ is handled. In order the recurrence to work, you need the values of $G(1,s)$ for all $s$, and there are restrictions on these values.
Comment: @san I see what you mean - another row of $r$ is needed because of the $r-2$. I added the row where $r=-1$.
Comment: It is also not clear if for example $(r,s)=(0,0)$ satisfies the relation. The relation implies that $F(r+1,s+1)−F(r−1,s)\le 0$, which makes sense for $(r,s)=(0,0)$, but $2F(r,s)−F(r−1,s)−F(r−1,s−1)$ is not defined, so the maximum is not defined.
Comment: You should define $F(r,s)$ for $r,s\ge -1$ but require the recursion formula only for $r,s\ge 0$.
Comment: In that case you must define $F(r,-1)=1$ for $r\ge 0$ and you can define $F(-1,-1)=2$.
Comment: @san the last comment is very interesting. I did not think there might be multiple solutions.
Comment: The solution given by Linalg is yet another solution
Answer: You can bootstrap the recursion and see if you find a pattern. The easiest way to read this post is by drawing a 2x2 grid and taking notes in it.
Your expression is:
$$\max\left\{ 2 F(r,s) - F(r-1,s) - F(r-1,s-1), \quad F(r+1,s+1) - F(r-1,s)\right\} =  0$$
Due to the argument $s-1$, you cannot fill in $s=0$. Since $F(r-1,s)$ occurs in both terms, you can take it out of the max expression:
$$\max\left\{ 2 F(r,s) - F(r-1,s-1), \quad F(r+1,s+1)\right\} =  F(r-1,s) \qquad (1)$$
For $r=0$ and $s \geq 1$, (1) means:
$$\max\left\{ 0, F(1,s+1)\right\} =  0$$
so $F(1,s+1) \leq 0$.
For $r=1$ and $s \geq 1$, (1) means:
$$\max\left\{ 2 F(1,s) - F(0,s-1), \quad F(2,s+1)\right\} =  0,$$
so $F(2,s) \leq 0$ and $2 F(1,s) \leq F(0,s-1)$, with equality for at least one of them.
For $s=1$ and $r \geq 1$, (1) means:
$$\max\left\{ 2 F(r,1) - 1, \quad F(r+1,2)\right\} =  F(r-1,1),$$
so $F(r,1)\leq0.5+0.5F(r-1,1)$ and $F(r+1,2)\leq F(r-1,1)$, with equality for at least one of them
There is no pattern that arises, but
$$F(r,s)=\begin{cases}1 & \text{if } r\geq 0 \text{ and } s=0\\ 0 & \text{otherwise}\end{cases}$$
satisifies the recursion.
Comment: Indeed there is a trivial solution that I did not notice. Thanks!


Number of connections per client in L4 vs. L7 Load balancing

Question: I am reading the faq for HAProxy.
It mentions that the layer 4 connection is established between the client and the server.
And in the next section, the layer 7 load-balancer acts as a proxy, which means it maintains two TCP connections: one with the client and one with the server.
I thought even the L4 LB will maintain 2 connections - one with the client and one with the server.
Why is that not the case?
Answer: More load balancer techniques exist than just proxies; that is a FAQ for load balancing in general. Read HAProxy's intro.txt particularly the survey on the topic "Quick introduction to load balancing and load balancers".
HAProxy is, well, a proxy. In TCP mode it links an incoming and outgoing socket like you were expecting. Again from intro.txt:
<code>  - a TCP proxy : it can accept a TCP connection from a listening socket,
    connect to a server and attach these sockets together allowing traffic to
    flow in both directions
</code>
At layer 4, it is also possible to forward the original flow to several different next hops based on just IP + TCP. You could call these packet-based load balancers fancy routers. Which isn't what TCP proxies like HAProxy do.
L7, at the application layer, enables many more features. Near-universally implemented as a proxy.

Some designs have both L4 and L7 load balancers, for redundancy and scalability. Combines extremely fast (usually) stateless L4 with the fancy features of a L7 proxy.
For an example of this, have a look at Vincent Bernat's lab Multi-tier load-balancing with Linux. ECMP routers, L4 to get the desired connection routing, L7 with the fancy features in front of the backends.
Comment: Is the gist of the your answer that it is possible to have 2 different TCP connection for L4 load balancer as well? If so, is the vice-versa also true wherein 1 single TCP connection between client and server when there's a L7 load balancer in between?
Comment: My answer is essentially, do not conflate layer 4 load balancing with proxying. There are L4 load balancers that are not proxies, the lab I linked to built one with keepalived on top of IPVS.  And, there are L4 load balancers that are proxies, such as HAProxy in TCP mode. HAProxy in specific you can assume to terminate a frontend connection and start a backend connection because, well, proxy is in the name.


KNN and K-means, very different but possible equivalency?

Question: Why does the k-nearest neighbor algorithm and k-means clustering algorithm with $k=1$ act the same?
Comment: because k=1 is a degenerate situation. Both methods should be used with k>1 only.
Comment: I don't think KNN with K=1 is degenerate
Answer: as @ttnphns stated in his comment, $k = 1$ is meaningless because there is only one cluster per datapoint.
To answer the question in a little more detail, there is a huge theoretical difference in K-means clustering and KNN. KNN requires an implicit construction of an $N \times N$ matrix which can be viewed as a graph with each node being connected to its 5 nearest neighbors.
K-means clustering actually separates the data into clusters which are not connected by edges, but are just classified as belonging to cluster $k$


Pegando o dado do campo value dinamicamente em Jquery

Question: Estou com dificuldade em implementar um botão deslogar em jquery...
gero uma lista de usuário que estão logados em tela de admin o admin pode deslogar o usuario
O Problema e que o botão só mostra o primeiro usuário da lista
 $('.comment-phara').on('click','#deslogar', function () {
    var select = $('#deslogar').val();
    alert(select);
    Lobibox.notify('info', {
        msg: 'Usuario deslogado já pode logar na estação.'
    });
});
                             <?php
                                foreach ($logados as $usuarios){
                                    echo '
'
                                    . '
'
                                            . '
'
                                            . '
' . $usuarios['nome_completo'] . '
'
                                            . '
'
                                            . '
'
                                            . '
 Logou as 16:55
'
                                            . '
'
                                            . '<button class="btn btn-custon-four btn-primary btn-xs" id="deslogar" value="'. $usuarios['nome_completo'] .'">Deslogar</button>'
                                            . '
'
                                            . '
'
                                            . '
';

                                }
                                ?>

Answer: Ha dois principais problemas na lógica, o primeiro está em criar um elemento com um id que será repetido em tela, idealmente ids devem ser únicos no DOM. Se você criar elementos em uma estrutura de repetição como foreach e precisar adicionar um id a algum deles, tente incluir uma chave que pertença ao objeto percorrido, em outros casos de preferência a utilização de classes.
O segundo problema esta na forma como você pega o valor do item que foi clicado, ao usar o comando $('#deslogar').val() ainda que ele procurasse por uma classe, você está pegando qualquer elemento da tela que corresponda ao valor de busca, ao invés de usar um termo para buscar pelo elemento, você pode usar o objeto this desta forma:
$(this).val();

this é o objeto que corresponde ao elemento que teve o evento disparado.
Comment: Perfeito bombou com o  $(this).val(); Como uso o mesmo botão me salvou cara!! Vou usar a classe também.


Shapiro-Wilk says data is not normal, but histogram looks like that

Question: I am using R. I have two data sets. The first one is generated with rnorm(), the second one is created manually.
Histogram of the first set is here

and Shapiro-Wilk (shapiro.test()) returns p-value 0.189, which is expected.
> shapiro.test(d)

    Shapiro-Wilk normality test

data:  d
W = 0.96785, p-value = 0.189

The second data set are residuals from linear regression fitting function (got by lm()) and its histogram is here:

I'd expect it to be detected as a normal distribution or, at least, pretty close to it. But Shapiro-Wilk gives p-value 4.725e-05, which strictly denies the possibility of it being a normal distribution.
> shapiro.test(fit$residuals)

    Shapiro-Wilk normality test

data:  fit$residuals
W = 0.70681, p-value = 4.725e-05

Do you know, why does it behave like this?

Data 1 (d)
-0.07205526
-0.645539
-2.025838
0.2518213
1.293012
-1.236223
-0.4183682
1.208981
-0.1084781
-0.7542519
-0.902902
0.1428906
-0.5124051
-1.959943
-1.272916
-1.706359
1.288966
0.7631183
-2.163717
-0.2049349
-0.7565308
1.12756
0.5250697
1.002177
0.6505888
0.7055426
1.143954
-0.02660517
-1.539839
-1.02968
-0.1616118
0.3548749
0.1531889
0.1214934
0.6672141
0.8862341
-0.2431952
-0.7877379
0.3775137
-0.8941234
1.003717
-0.07051517
-0.009962349
-1.501927
-0.1547865
-1.209728
0.3160188
-0.694145
0.3009792
0.07562172

Data 2 (fit$residuals)
-0.01270401
-0.01266431
-0.01109333
-0.009522339
-0.007951352
-0.006380364
0.09519062
-0.003238389
-0.001667402
-9.641439e-05
0.001474573
0.003045561
0.004616548
0.006187535
0.007758523
-0.09067049
0.0109005
0.01247149
-0.001270401
0.01561346

EDIT
I've added additional case with just 10 observations generated by rnorm() function too.
Data doesn't look very normally distributed at first sight, but Shapiro-Wilk tells otherwise.

> shapiro.test(dd)

    Shapiro-Wilk normality test

data:  dd
W = 0.93428, p-value = 0.4912

Data 3 (dd)
-0.5272838
-0.03053323
0.009022335
0.8179343
0.8927589
0.3694592
-0.7372785
0.8209204
0.1088729

Comment: A normal Q-Q plot clearly reveals why the Shapiro Wilk test would reject. for "Data 2".
Comment: R has it right. Should be Wilk (Martin B. Wilk) not Wilks (Samuel S. Wilks) here throughout. Edited accordingly.
Comment: @NickCox Thank you. So, is my interpretation of histogram wrong? And could you, please, write a full answer, so I could accept it?
Comment: @Glen_b Ok, could you, please, submit your answer with a little explanation? I'm really not experienced in this area.
Comment: I have answered. I am in full agreement with @Glen_b.
Comment: @Eenoku I don't think I would say anything Nick didn't say well already.
Comment: @Glen_b I wrote it shortly before his answer :-)  Anyway, thank you.
Answer: The second dataset has two clear outliers, one high and one low. So the test result appears perfectly plausible.
Here a normal quantile plot makes the point.

In this question, and usually,

Worrying about the Shapiro-Wilk test result is much less important than worrying about whether the regression makes sense. If possible, you should show us the data and the regression results. Perhaps the regression is about the best you can do and one outlier either side is just the way your data are. Normally distributed residuals are just an ideal condition, while life is imperfect. Or perhaps a different regression is needed. We can't tell without more information.
A histogram can be a fairly poor means for judging normality or non-normality. It's better than not looking at the data at all, but the normal quantile plot (a.k.a. normal probability plot) is tailored to that purpose. The outliers aren't hidden in your histogram (they are shown in the extreme bins), but it's much harder to see them as outliers on the histogram.

What you can also do is

Go back to the data and check which points are outliers. Do those points make sense given other variables and what else you know?
Consider some other kind of regression (e.g. quantile regression) as a check on results.
Answer: Looking at a non-significant p-value for any test doesn't lend support to the null hypothesis. In this case, a non-significant SW doesn't show normality-- it just means the sample doesn't have enough information to suggest stronger incompatibility with normality which may be due to sample size or just due to the actual distribution (or some kind of bias).
Relying too much on formal tests of normality can lead you astray, as they are often very powerful to detect even the slightest variation from normality which may have zero practical importance.
I would also disagree that a significant test "flies in the face" of normality; under a standard framework you could conclude the data are not from an underlying normal distribution, but looking at the data on a q-q and histogram is more revealing as to the shape of the empirical distribution: that is what you're using as a proxy for the underlying distribution, which is unknown.
Using subject matter expertise is often useful in statistics, and this is one where blindly following a p-value is likely to lead you astray.
Answer: I think this behavior can arise because your residuals series has only 20 observations while the first dataset generated with rnorm() has 50 observations. If you generate your random dataset with only 10 observations it will be easier that the test result is significant.
Comment: Clearly you need to worry when you have small sample sizes, but sample size seems a side-issue in this case. The second dataset is clearly not normal. How far that is a big problem is then the question,
Comment: I've added the random dataset with 10 observations generated by `rnorm()` too and it's still confusing...
Comment: Totally agree @NickCox


DataView.Rowfilter filtering parent-form's dataset

Question: I am trying to filter my dataview.  So I've got the following event-handler:
private void Break_ValueChanged(object sender, EventArgs e)
  {
     DataView dvBreaks = ParentForm.CurrentUser.Cache.GetERPLuTableFromCache( Db.CustomDbMetaData.CachedTables.Breaks ).DefaultView;
     if( Convert.ToString( Break.Value ) != string.Empty ) {
        dvBreaks.RowFilter = "BREAK = '" + Convert.ToString( Break.Value ) + "'";
     }
  }

When I look at this code, my understanding is that it should ONLY be filtering the data in dvBreaks, however the data in the parent form is actually being filtered.  I could work around this issue with a loop but I thought it would be nice to use less code - and maybe make this process more efficient.
Can anyone shed some light on this for me?
Comment: PS - I used your first solution.
Answer: It's filtering the parent form because you're grabbing the reference from the parent form. If you want it to only filter the child then you'll need a copy of that for the child and use that copy to data bind.
You could change the code like this:
private void Break_ValueChanged(object sender, EventArgs e)
{
    DataView dvBreaks = ParentForm.CurrentUser
        .Cache
        .GetERPLuTableFromCache( Db.CustomDbMetaData.CachedTables.Breaks )
        .DefaultView
        .ToTable()
        .DefaultView;

    if( Convert.ToString( Break.Value ) != string.Empty ) {
        dvBreaks.RowFilter = "BREAK = '" + Convert.ToString( Break.Value ) + "'";
    }
}

or, if GetERPLuTableFromCache is a DataTable:
DataView dvBreaks = ParentForm.CurrentUser
    .Cache
    .GetERPLuTableFromCache( Db.CustomDbMetaData.CachedTables.Breaks )
    .Copy()
    .DefaultView;


Are you allowed to set the ball over the net sideways instead of forwards/backwards in indoor volleyball?

Question: I looked through the indoor volleyball rulebook, and can't find anything on this in there, through Google, nor in any previously asked questions here.
I was told many times before that you cannot purposely set a ball over the net unless your back or front are parallel to the net, as in you can only set it forward or backwards, not to the side. However, I was watching some indoor volleyball highlights and a girl did a purposeful low side set over the net for a point.
What is the official rule? I'm referring to indoor volleyball (recreational/intermediate leagues, not like college or anything) and I would like to know the official ruling.
Edit: to be clear, in case it matters, I'm referring specifically to the 2nd hit.
Answer: Yes, you are allowed to set the ball over the net anyway you want.

I was told many times before that you cannot purposely set a ball over the net unless your back or front are parallel to the net

I think the person who told you so, was referring to Beach-volleyball.
It matches the FIVB-Beach rule 13.2.5
N.B. : As a back row setter, you cannot block, attack, set or hit the ball at all above the net.


How to Create Compound Dataset on HDF5 C#

Question: i need to write some data to a HDF5 file, i have a list of objects of the class "OPC_UA" inside a "BV" class, i want to create a dataset with the name of the BV and inside the dataset i want to have the list of the "OPC_UA" objects, tha OPC_UA Class have 3 attributes, a Long int ,one float value and a Datetime that i will convert to a timestamp, i can't seem to make it work, the Marshal.SizeOf() doesn't work with classes but i cant do it as a struct... Here is my code:
 public void CriaHDF5Customizado(PackingConfigFile pf)
    {
        H5FileId fileId = H5F.create("pmdfq.h5", H5F.CreateMode.ACC_TRUNC);

        H5GroupId infoGroupId = H5G.create(fileId, "informations");
        H5G.close(infoGroupId);
        H5GroupId datasetGroupId = H5G.create(fileId, "datasets");

        long[] dims = new long[1];

        foreach(BasicVariable bv in pf.basicVariableList.bvList)
        {
            OPC_UA aux = new OPC_UA();
            var xx = bv.bvData;
            int tamanho = Marshal.SizeOf(typeof(OPC_UA));
            dims[0] = (long)bv.bvData.Count;
            // dims[1] = (long)4;
            H5DataSpaceId spaceId = H5S.create(H5S.H5SClass.SCALAR);
            H5DataTypeId dataTypeId = H5T.create(H5T.CreateClass.COMPOUND, Marshal.SizeOf(typeof(OPC_UA)));

            H5T.insert(dataTypeId, "TimeStamp", 0, new H5DataTypeId(H5T.H5Type.NATIVE_UINT));
            H5T.insert(dataTypeId, "Quality", Marshal.SizeOf(H5T.H5Type.NATIVE_UINT), new H5DataTypeId(H5T.H5Type.NATIVE_UINT));
            H5T.insert(dataTypeId, "Value", 2* Marshal.SizeOf(H5T.H5Type.NATIVE_UINT), new H5DataTypeId(H5T.H5Type.NATIVE_INT));

            H5DataSetId dataSetId = H5D.create(datasetGroupId, bv.bvTag, dataTypeId, spaceId);

            //H5D.write(dataSetId, new H5DataTypeId(H5T.H5Type.STD_REF_OBJ), new H5Array<OPC_UA>(bv.bvData.ToArray()));
            H5D.writeScalar(dataSetId, dataTypeId, ref xx);
            H5D.close(dataSetId);
        }
        H5G.close(datasetGroupId);

        H5F.close(fileId);
    }

And this is the OPC UA Class
   public class OPC_UA
{
    public DateTime timeStamp { get; set;  }
    public string data { get; set; }
    public Int64 quality { get; set; }

    public OPC_UA(DateTime? ts = null ,string dt = "",Int64 qlt = -99)
    {
        if (!ts.HasValue)
        {
            timeStamp = DateTime.Now;
        }
        data = dt;
        quality = qlt;
    }

Answer: public DateTime timeStamp { get; set;  }

DateTime is not an atomic datatype. Convert it into long/Int64 ticks. Then you might be able to write it.
public DateTime timeStamp
    {
        get { return new DateTime(StartTimeTicks); }
        set
        {
            StartTimeTicks = value.Ticks;
        }
    }
public long StartTimeTicks;

The constructor may also be hindering it.
The workaround would be making a structure. Note: Make the structure of fields or properties, depending upon (GetFields)fields or (GetProperties)properties you will to use in the reflection to read it.
 public structure OPC_UA
 {

    public string data;
    public Int64 quality ;
    public DateTime timeStamp
    {
        get { return new DateTime(StartTimeTicks); }
        set
        {
            StartTimeTicks = value.Ticks;
        }
    }
    public long StartTimeTicks;
 }

Hdf5DotnetTools is a working C# wrapper on Hdf.PInvoke. You can write a compound dataset by using a C# structure list.
If you have any difficulty in using the functions of either Hdf.PInvoke or Hdf5DotnetTools, you can use its UnitTest project.


Oracle SQL substitution variable, the scope of substitution

Question: I have been pondering about what and how much I can actually put into the substitution variable. can we only have it to replace a single 'entity' but not a string of command? I found if I want to substitute a block of actual SQL, it did not work (in SqlDeveloper).
I wonder how I can get around this...
/*------test--------------*/
CREATE TABLE Test_Persons (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255)
);

INSERT INTO Test_Persons
    (PersonID,LastName,FirstName)
    values(1,'LN_1','FN_1');

INSERT INTO Test_Persons
    (PersonID,LastName,FirstName)
    values(2,'LN_2','FN_2');

INSERT INTO Test_Persons
    (PersonID,LastName,FirstName)
    values(3,'LN_21','FN_2');

commit;

--------------sub-table, worked!---
set define #;

define first_name_input = 'FN_2';
define last_name_input = 'LN_2';
define tbl_Test_Persons = 'Test_Persons';
define temp_tbl_Test_Persons_FN = 'Test_Persons_FN';

with
#temp_tbl_Test_Persons_FN as
(
    select * from #tbl_Test_Persons tp
    where tp.FIRSTNAME = '#first_name_input'
)
select * from #temp_tbl_Test_Persons_FN tp
    where tp.LASTNAME = '#last_name_input';

set define off;

--------------sub-table, replace the entire with clause, does NOT work - 'Invalid value for DEFINE command.'!---
set define #;

define first_name_input = 'FN_2';
define last_name_input = 'LN_2';
define tbl_Test_Persons = 'Test_Persons';
define temp_tbl_Test_Persons_FN = 'Test_Persons_FN2';
define with_clause = '
with
#temp_tbl_Test_Persons_FN as
(
    select * from #tbl_Test_Persons tp
    where tp.FIRSTNAME = ''#first_name_input''
)
';

#with_clause
select * from #temp_tbl_Test_Persons_FN tp
    where tp.LASTNAME = '#last_name_input';

set define off;

Answer: From the documentation (for SQL*Plus but applies to SQL Developer too):

If the value of a defined variable extends over multiple lines (using the SQL*Plus command continuation character), SQL*Plus replaces each continuation character and carriage return with a space.

SQL Developer actually behaves slightly differently, and leaves the continuation character inside the string, which isn't helpful. But is also leaves the line breaks, so you can double-up the continuation character from - to --to stop it causing a problem, as that is then treated a comment; so you can do:
define with_clause = '--
with--
#temp_tbl_Test_Persons_FN as--
(--
    select * from #tbl_Test_Persons tp--
    where tp.FIRSTNAME = ''#first_name_input''--
)--
';

But there is a further complication, because #with_clause isn't recognised as a command - as you aren't yet in a command substitution doesn't happen. You can get around that, messily, with a subquery:
select * from (
#with_clause
select * from #temp_tbl_Test_Persons_FN tp
    where tp.LASTNAME = '#last_name_input'
);

which isn't ideal. But if you do that, the script output window shows the substitution happening and you get a row back:
old:select * from (
#with_clause
select * from #temp_tbl_Test_Persons_FN tp
    where tp.LASTNAME = '#last_name_input'
)
new:select * from (
--
with--
Test_Persons_FN2 as--
(--
    select * from Test_Persons tp--
    where tp.FIRSTNAME = 'FN_2'--
)--

select * from Test_Persons_FN2 tp
    where tp.LASTNAME = 'LN_2'
)

  PERSONID LASTNAME                                                                                FIRSTNAME
---------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
         2 LN_2                                                                                FN_2

(Also, interestingly, this still doesn't work in SQL*Plus if you use # as the substitution character - you get "ORA-24333: zero iteration count". It doesn't get that error with & though; I haven't tried any others. And you have to go back to a single concatenation character. But even with those changes it still doesn't substitute the with clause properly. Not sure why yet.)


How to figure out which NodeJS core modules a package is using?

Question: Let's say we have a package on NPM like got.
I want to figure out which core NodeJS modules this package is using as I want to polyfill it on environments (like React native, or the browser).
Is there any way where I can just get a list of which core NodeJS modules this package is using without manually searching through the source code?
I know there are ways to figure out the dependency tree -- that is not what I am asking. I specificially want to know which core NodeJS modules are being used.
Answer: There is no way to do this that is not manual unfortunately.
However, it is pretty simple to do.
Simply search all the files in your project via your IDE. CMD+F for things like crypto, buffer, stream, etc.
https://flaviocopes.com/node-core-modules/ is a list of all the core node modules


Element type invalid, when using Flatlist

Question: Please have a look at the following class. As soon as I use a FlatList (or List), I get the error: "Element type is invalid: expected a string (for built-in components) or a class/function for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of 'Userlist'"
When I search for this error, it usually has to do with missing wrong imports. I think, my imports are correct?
import React, { Component } from 'react';
import { ScrollView, View, Text, Navigator, Alert, StyleSheet} from 'react-native';
import { List, FlatList, ListItem } from 'react-native-elements';
import FBUsers from '../../firebase/FBUser'

export default class Userlist extends React.Component {
    fbUser = new FBUsers();

    constructor(props) {
       super(props);

       this.state = {
         lastRefresh: '',
       }
    }

    refresh() {
        this.setState({lastRefresh: Date(Date.now()).toString()});
    }

    // buildUserList() {
    //     var users = this.fbUser.getUserList();
    //     return users;
    // }

    renderRow ({ item }) {
    return (
      <ListItem
        roundAvatar
        title={item.name}
        subtitle={item.subtitle}
        avatar={{uri:item.avatar_url}}
      />
    )
  }

  render () {
    var list = [
      {
        name: 'Amy Farha',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
        subtitle: 'Vice President'
      },
      {
        name: 'Chris Jackson',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
        subtitle: 'Vice Chairman'
      }
    ]

    return (
      <List>
        <FlatList
          data={this.list}
          renderItem={this.renderRow}
          keyExtractor={item => item.name}
        />
      </List>
    )
  }
}

Comment: > Element type is invalid: expected a string... isn't this just the first part of the error? doesn't it say what it got ? ie: expected string, got undefined
Comment: I am sorry - now I completed the error message
Answer: Import FlatList from react-native. That's why you're getting this error. Use this code.
import React, { Component } from 'react';
import { ScrollView, View, Text, Navigator, Alert, StyleSheet, FlatList } from 'react-native';
import { ListItem } from 'react-native-elements';

export default class Userlist extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      lastRefresh: '',
    }
  }

  refresh() {
    this.setState({ lastRefresh: Date(Date.now()).toString() });
  }

  // buildUserList() {
  //     var users = this.fbUser.getUserList();
  //     return users;
  // }

  renderRow({ item }) {
    return (
      <ListItem
        roundAvatar
        title={item.name}
        subtitle={item.subtitle}
        leftAvatar={{
          source: {
            uri: item.avatar_url
          }
        }}
      />
    )
  }

  render() {
    var list = [
      {
        name: 'Amy Farha',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
        subtitle: 'Vice President'
      },
      {
        name: 'Chris Jackson',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
        subtitle: 'Vice Chairman'
      }
    ]

    return (

      <FlatList
        data={list}
        renderItem={this.renderRow}
        keyExtractor={item => item.name}
      />
    )
  }
}

Comment: My pleasure. :)


Verificando se um elemento está visível ou não na página

Question: Eu tenho os seguintes botões:
Primeiro botão:
<button id="modal-btn" class="button btn-cart btn-verde-claro"> Comprar </button>

Segundo botão:

    <button class="button btn-cart btn-verde-claro">Comprar</button>

Eu queria que quando o primeiro botão aparecesse, o segundo não aparecesse e vice versa. Quando o segundo aparecer na tela, o primeiro ficasse escondido.
Fiz a função em jQuery usando o .is(':visible'), porém não deu certo, pois eu queria ver se o elemento estava sendo exibido na tela, não se está com display: none ou display: block.
Código da função:
$j(window).scroll(function() {
   console.log('fazendo');
   if($j('#modal-btn').is(':visible')){
       console.log('if');
       $j('#btn-comprar-fixed-mobile').css('display','none');
   } else{
       console.log('else');
       $j('#btn-comprar-fixed-mobile').css('display','block');
   }
});

Answer: Você pode verificar se ele esta na tela verificando o scroll.
Como os botões irão sumir e aparecer, vou utilizar a div para definir quando ele deve aparecer, você vai fazer da mesma forma na sua pagina, colocando as divs onde os botões estão.

  <button id="btn1">Comprar</button>

    <button id="btn2">Comprar</button>

Criei este código css para que a pagina possa ter um scroll:
body{
  background-color:#000;
}
.area1{
  background-color:#a00;
  height: 1000px;
}
.area2{
  background-color:#005;
  height: 1000px;
}

E o seguinte código:
$(function(){
  var area1 = $('.area1').offset().top - $(window).height();
  var area2 = $('.area2').offset().top - $(window).height();

  $(window).scroll(function() {
    if ($(window).scrollTop() > area1) {
      $('#btn1').css('display','block');
      $('#btn2').css('display','none');
    }
    if ($(window).scrollTop() > area2) {
        $('#btn2').css('display','block');
      $('#btn1').css('display','none');
    }
  });
});

Assim ele consegue pegar se ele esta ou não na tela através do scroll.
Resultado: https://jsfiddle.net/pjqxrgwu/
Creditos: Como saber qual div é mostrada na tela com javascript?
Comment: Acho que ele quis dizer que o primeiro botão é fixo, e quando aparecesse ou segundo, o primeiro sumisse e vive-versa... aliás, o segundo que é fixo rs
Comment: @dvd isso mesmo. Mas consegui fazer funcionar a partir desse código, somente alterei algumas coisas na função.


About the definition of **independent points of infinite order** in a group

Question: Let $(G,+)$ be a group.
I am asking about the definition of independent points of infinite order in $G$. A search in google does not give helpful information.
Comment: No wonder you didn't find anything googling: this seems to be a non-standard definition. Where did you get it from? Perhaps you meant "$\,\Bbb Z-$linearly independent *elements* in an abelian group", or something of the like? Or free-torsion generators or stuff?
Comment: Oh, dear: this is a very different thing! You should make sure you include all relevant information in your questions. People can't usually guess.
Comment: No, this is comes from **Rational points of infinite order on elliptic curves** where $G$ is the set of rational solutions. See this page: http://en.wikipedia.org/wiki/Elliptic_curve
Comment: Actually, googling *independent points of infinite order* leads you immediately to the Wikipedia article on elliptic curves.
Comment: Interesting though the OP said there was no helpful information after googling...
Comment: @ DonAntonio: Yes, since I am looking on the wrong side, i.e., the definition for groups!. Thank you for your kind help.
Answer: You're probably reading about elliptic curves.
An abelian group $G$ is the same thing as a $\mathbf{Z}$-module. So the definition is a partial analogue to that in vector spaces. Elements $g_{1}, \dots, g_{n} \in G$ are said to be (linearly) independent if
$$
a_{1} g_{1} + \dots + a_{n} g_{n} = 0,
$$
for $a_{i} \in \mathbf{Z}$ implies $a_{i} = 0$ for all $i$.
If $g_{1}, \dots, g_{n}$ are independent, then each of them has infinite order. (If, by way of contradiction, $g_{1}$, say has order $a > 0$, then $a g_{1} + 0 g_{2} + \dots + 0 g_{n} = 0$.)
The cardinality of a maximal independent set in $G$ is its rank.
Comment: @ Andreas Caranti: Thank you very much for clarification.
Comment: @Chaos, you're welcome.


solve internal error: STRING operator applied to undefined or non-STRING variable

Question: Newb here with Gnuplot. I tried just testing it with a simple plt script as per below but get the error when using it interactively (there is no output or error message when using it non-interactively). I have tested with plot sin(x) interactively and that worked.
The script is as follows:
set xdata time
set timefmt "%Y-%m-%d"
set format x "%Y-%m-%d"
set xlabel "Date"
set ylabel "Value"
set title "Decimal Values Over Time"
plot 'data.txt' using 1:2 with linespoints

The input data is a simple 2 columns, space-delimited and the first column is a date and the second column a decimal value.
2023-02-01 60
2023-03-01 30
2023-04-01 55

I have actually been trying to plot a much more complex file (where it had multiple inputs and decimal values as percentages etc) without success and always having this same error. So I tried this simpler input just to see and still no luck. It's weird that the plot sin(x) worked.
I'm now just trying to create a simple line chart with these values over the dates (i.e. dates on x and values on y and then a line joining each).
I have also done a full upgrade on my system etc.  my Debian is using version Version 5.4 patchlevel 1.
Edited : to add more detail based on the qwuestions below.

my plot script is in a file created via vim called testplot.gnuplot
my data is in a file also created via vim called data.txt
I first executed from the CLI like this $gnuplot -c testplot.gnuplotand I saw no output. Then I tried interactive via $gnuplot and once in interactive mode, used load testplot.gnuplot where I saw the error as per the subject line.

Any ideas on how I can make this work or where I am doing something wrong?
Comment: Do your input files contain DOS carriage returns? https://stackoverflow.com/questions/39527571/are-shell-scripts-sensitive-to-encoding-and-line-endings
Comment: I cannot or at least don't know how to reproduce your error. How exactly do you start your gnuplot script? From gnuplot console or from operating console? What is the full command you're typing?
Answer: In the gnuplot console simply put your filename into quotes:
load "testplot.gnuplot"

Check help load:

Syntax:

      load "<input-file>"

The name of the input file must be enclosed in quotes.

Furthermore:
In the operating system CLI, use the option -p for persistent, in the  gnuplot-console check help command line options. So, something like:
gnuplot -p -c Testplot.gnuplot

Here, the filename can be with or without quotes.
Comment: @KingJulian glad to hear. On StackOverflow: "Thank you" or "answer was helpful" = upvote answer, and "answer solved problem" = accept answer (check the check mark at the top left).
Comment: Thanks, done, I could not upvote it due to low post count, but managed to check it.
Comment: Thank you so much, both these tips worked.


Somar valores em vetor e retornar o valor na condição verdadeira

Question: Estou com uma duvida em um script onde estou fazendo um Quiz, em meu último Quiz meu eu coloquei 3 opções de resposta: A, B e C. Onde se a resposta for A soma 3 pontos para opção X, 2 pontos para opção Y e 1 ponto para Opção Z. Se a resposta for B soma 2 pontos para opção X, 3 pontos para opção Y e 1 ponto para Opção Z. Se a resposta for C soma 1 ponto para opção X, 2 pontos para opção Y e 3 pontos para Opção Z.
Então a função verifica qual Opção tem mais pontos e retorna ela.
Porém eu quero modificar para a seguinte função:
Se resposta for A soma 4 pontos. Se resposta for B soma 2 pontos. Se resposta for C soma 0 pontos.
Se a quantidade de pontos for até 10 retorna Opção X. Se a quantidade de pontos for de 11 até 24 retorna opção Y. Se a quantidade de pontos for maior que 24 retorna a Opção Z.
Segue parte do código:
self.jobs = [
    {
        title: 'Opção X',
        description: 'Descrição Opção X'
    },
    {
        title: 'Opção Y',
        description: 'Descrição Opção Y'
    },
    {
        title: 'Opção Z',
        description: 'Descrição Opção Z'
    }
    ];

self.job = 9999;

self.questions = [
    {
        text: 'Pergunta 1',
        answered: false,
        skipped: false,
        answers: [
            {
                text: 'A',
                selected: false,
                values: [3, 2, 1]
            },
            {
                text: 'B',
                selected: false,
                values: [2, 3, 1]
            },
            {
                text: 'C',
                selected: false,
                values: [1, 2, 3]
            }
        ]
    },
    {
        text: 'Pergunta 2',
        answered: false,
        skipped: false,
        answers: [
            {
                text: 'A',
                selected: false,
                values: [3, 2, 1]
            },
            {
                text: 'B',
                selected: false,
                values: [2, 3, 1]
            },
            {
                text: 'C',
                selected: false,
                values: [1, 2, 3]
            }
        ]
    },
    {
        text: 'Pergunta 3',
        answered: false,
        skipped: false,
        answers: [
            {
                text: 'A',
                selected: false,
                values: [3, 2, 1]
            },
            {
                text: 'B',
                selected: false,
                values: [2, 3, 1]
            },
            {
                text: 'C',
                selected: false,
                values: [1, 2, 3]
            }
        ]
    }
];

self.index = 0;

self.userAnswers = [];

self.error = false;

self.answerQuestion = function(elem) {
    self.userAnswers[self.index] = elem.answer;
    self.index = elem.$parent.$index + 1;

    var question = elem.$parent.question;
    question.answered = true;

    angular.forEach(question.answers, function(answer) {
        answer.selected = false;
    });

    elem.answer.selected = true;
};

self.changeQuestion = function(elem) {
    var question = self.questions[self.index];
    if(question && !question.answered)
        question.skipped = true;

    self.index = elem.$index;
};

self.goToResult = function() {
    var question = self.questions[self.index];
    if(question && !question.answered)
        question.skipped = true;

    self.index = self.questions.length;
}

self.viewResult = function() {
    var hasError = false;

    angular.forEach(self.questions, function(question) {
        if(!question.answered) {
            hasError = true;
            question.skipped = true;
        }
    });

    if(hasError) {
        self.error = true;

        $timeout(function() {
            self.error = false;
        }, 2000);

        return false;
    }

    self.showQuiz = false;

    var result = getResult();
    self.job = result;
};

getResult = function() {
    var results = [0, 0, 0];
    var maior = -9999;
    var iMaior = 0;

    angular.forEach(self.userAnswers, function(answer) {
        for(var i=0; i < self.jobs.length; i++) {
            results[i] += answer.values[i];
        }
    });

    for(var i=0; i < results.length; i++) {
        var result = results[i];
        if(result > maior) {
            maior = result;
            iMaior = i;
        }
    }

    return iMaior;
};
}]);

Comment: Alguém pode ajudar?
Comment: Você conseguiu resolver?
Answer: Para resolver o problema do valor de cada letra, deve-se alterar os arrays [3, 2, 1], [2, 3, 1] e [1, 2, 3] para [4, 2, 0], [2, 4, 0] e [0, 2, 4] (respectivamente e nas 3 perguntas).
A pontuação você testa na função "getResult", modificando o final dela:
getResult = function() {
    var results = [0, 0, 0];
    var soma = 0;

    angular.forEach(self.userAnswers, function(answer) {
        for(var i=0; i < self.jobs.length; i++) {
            results[i] += answer.values[i];
        }
    });

    for(var i=0; i < results.length; i++) {
        soma += results[i];
    }

    if (soma > 24)
        return 2; // Z
    else if (soma >= 11 && soma <= 24)
        return 1; // Y
    else
        return 0; // X
};

Imagino que seja isso!


Altera cor de elemento ao ser clicado

Question: Possuo esse codigo, ele mostra 1 video ao clicar em uma tabela.
É possivel altera a cor do elemento que foi clicado da mesma forma como se faz com links? mas com CSS?
Exemplo: video 1 cor vermelha, após ser clicado essa opção ficar cinza.

01

Opção 1

Opção 2

Fechar

 02

Opção 1

Opção 2

Fechar

 03

Opção 1

Opção 2

Fechar

Answer: A maneira mais simples é juntar isto nos dois auscultadores de evento, que vai forçar a côr de fundo para preto, juntando um estilo diretamente no elemento:
$(this).closest('li').css('background-color', 'black');

assim: https://jsfiddle.net/x2uoxbLy/
outra opção é juntar uma classe, por exemplo:
.visitado {background-color: black !important;}

e no código ter
$(this).closest('li').addClass('visitado');

assim: https://jsfiddle.net/x2uoxbLy/
Edit, para ser persistente ao carregar da página:
Para o browser memorizar tens de gravar algo no servidor ou no computador do utilizador, como uma entrada no localStorage por exemplo.
Usando o localStorage podias fazer assim:
var linksVisitados = Visitados();
linksVisitados.forEach(function(link) {
    var li = document.querySelector(`[data-videoid="${link}"]`).parentElement;
    li.classList.add('visitado');
});

function Visitados(link) {
    var linksVisitados = JSON.parse(localStorage.linksVisitados || '[]');
    if (!link) return linksVisitados;
    linksVisitados.push(link);
    localStorage.linksVisitados = JSON.stringify(linksVisitados);
}

e depois em cada callback:
$(this).closest('li').addClass('visitado');
var videoID = $(this).attr('data-videoID');
Visitados(videoID);

assim: https://jsfiddle.net/r4L6f3p2/
Comment: Valeu Sergio, vou fazer uns testes aqui, agora ficou otimo
Comment: Valeu Sergio, mas essa opção que vc mostrou, ela fica gravada no navegador ? tipo igual quando a gente já clicou em algum link e nos já sabemos que visitamos eles pq ele está de outra cor?
Comment: @Endou fica gravado até navegar para outra página, aí ele esquece. Se queres que ele lembre o utilizador tens de deixar um cookie, localstorage ou falar com o servidor se o utilizador estiver logado.
Comment: Não teria como usar o Css :visited  ou :target ?
Comment: @Endou queres que o browser saiba que o clique aconteceu mesmo depois de voltar à página?
Comment: Sim, é disso que necessito.
Comment: @Endou como geras esse HTML? é no servidor com algum loop a partir de dados organizados?
Comment: É uma pagina HTML, simples feito em 1 site Wordpress.
Comment: A Opção mais adequada, seria o navegador salvar os dados, como faz em uma pagina html com links.
Comment: @Endou editei com uma solução que "tem memória"
Comment: Sergio, vc poderia da uma olhada aqui https://jsfiddle.net/r4L6f3p2/1/  eu não to conseguindo fazer funcionar. não sei onde está o erro, mas o codigo está igual o seu mas não está funcionando
Comment: @Endou no meu cache/localStorage tinha ainda links que não existem. Juntei uma verificação extra: https://jsfiddle.net/r4L6f3p2/2/

Altera cor de elemento ao ser clicado


Module build failed using css-loader while trying to import main.css file

Question: I am trying to use node and vue js in the wordpress plugin.I am struck in the css file import.I am trying add css file into the package.json file. importing css file using css-loader. But i am getting the following error. Also can anyone explain how to post-css in this case.
package.json
    {
  "name": "plugin_toolkit",
  "version": "1.0.0",
  "description": "Simple WordPress plugin that uses Webpack.",
  "main": "index.js",
  "babel": {
    "presets": [
      "@babel/preset-env"
    ]
  },
  "scripts": {
    "dev": "webpack --mode=development --watch --config webpack-config.js",
    "build": "webpack --mode=production --config webpack-config.js"
  },
  "keywords": [
    "wordpress",
    "webpack",
    "javascript"
  ],
  "author": "Srinitamil",
  "license": "GPL-2.0+",
  "devDependencies": {
    "@babel/cli": "^7.1.5",
    "@babel/core": "^7.1.6",
    "@babel/preset-env": "^7.1.6",
    "axios": "^0.21.1",
    "babel-loader": "^8.0.4",
    "lodash": "^4.17.11",
    "vue-loader": "15.9.8",
    "vuex": "^3.6.2",
    "css-loader": "^6.2.0",
    "webpack": "^4.26.1",
    "webpack-cli": "^3.1.2",
    "vue-template-compiler": "^2.6.12"
  },
  "dependencies": {
    "vue": "^2.6.14"
  }
}

web-pack-config-file
// Require path.
const path = require( 'path' );
const { VueLoaderPlugin } = require('vue-loader')

// Configuration object.
const config = {
    // Create the entry points.
    // One for frontend and one for the admin area.
    entry: {
        // frontend and admin will replace the [name] portion of the output config below.
        frontend: './src/front/main.js',
        admin: './src/admin/admin-index.js',

    },

    plugins: [
        // make sure to include the plugin!
        new VueLoaderPlugin()
    ],

    // Create the output files.
    // One for each of our entry points.
    output: {
        // [name] allows for the entry object keys to be used as file names.
        filename: 'js/[name].js',
        // Specify the path to the JS files.
        path: path.resolve( __dirname, 'assets' )
    },

    // Setup a loader to transpile down the latest and great JavaScript so older browsers
    // can understand it.
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            // this will apply to both plain `.js` files
            // AND `<script>` blocks in `.vue` files
            {
                test: /\.js$/,
                loader: 'babel-loader'
            },
            // this will apply to both plain `.css` files
            // AND `<style>` blocks in `.vue` files
            {
                test: /\.css$/,
                use: [
                    'vue-style-loader',
                    'css-loader'
                ]
            }
        ]
    }
}

// Export the config object.
module.exports = config;

Vue file
<template>

    <app></app>

 {{ content }}

</template>

i am getting issue like
ERROR in ./src/front/main.css (./node_modules/css-loader/dist/cjs.js!./src/front/main.css)
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
TypeError: this.getOptions is not a function
    at Object.loader (/opt/lampp/htdocs/vblog/wp-content/plugins/plugin-toolkit/node_modules/css-loader/dist/index.js:31:27)
 @ ./src/front/main.css 4:14-79
 @ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib??vue-loader-options!./src/front/templates/Home.vue?vue&type=script&lang=js&
 @ ./src/front/templates/Home.vue?vue&type=script&lang=js&
 @ ./src/front/templates/Home.vue
 @ ./src/front/main.js

I am using normal css file, but in webpack config file i have mentioned as vue-loader-css that is the issue.
{
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
}

Answer: I think this is version incompatibility issue. You can try the following css-loader version
"css-loader": "4.3.0"


If $|x|^2u=0$ for $u\in\mathcal D'(\mathbb R^d)$, then $\psi\in\mathcal D(\mathbb R^d)$ and $\operatorname{supp}(\psi)\cap B(0,10)$ imply $u(\psi)=0$

Question: Problem: Show that if $\vert x\vert^2u=0$ for $u\in\mathcal D'(\mathbb R^d)$, then for all $\psi\in\mathcal C_c^\infty(\mathbb R^d)$ such that $\operatorname{supp}(\psi)\cap B(0,10)=\varnothing$ we have $u(\psi)=0.$
My Thoughts: I think that the problem statement is not clear, as there seems to be nothing special about $B(0,10)$. For example, fix $\varepsilon>0$ and consider $B(0,\varepsilon)$. Note that $x\mapsto \vert x\vert^2$ is smooth on $\mathbb R^d\setminus B(0,\varepsilon)$. Therefore, if $\psi\in\mathcal D(\mathbb R^d)$ has $\operatorname{supp}(\psi)\cap B(0,\varepsilon)=\varnothing$, then
$$u(\psi)=\vert x\vert^2u\left(\frac{\psi}{\vert x\vert^2}\right)=0.$$
I justify the above calculation by noticing that $\psi/\vert x\vert^2\in\mathcal D(\mathbb R^d\setminus B(0,\varepsilon))$ and $\operatorname{supp}(\psi/\vert x\vert^2)=\operatorname{supp}(\psi)$. Also if $u\in\mathcal D'(\mathbb R^d)$, then $u\vert_{\mathbb R^d\setminus B(0,\varepsilon)}\in\mathcal D'(\mathbb R^d\setminus B(0,\varepsilon)).$
Therefore, it seems that the result holds for any ball centered at the origin.

Could anyone tell me if I am on the right track or if I have made a horrible mistake at the beginning in my understanding of the definitions?
Thank you for your time and appreciate the valuable feedback.
Answer: You are correct that there is nothing special about radius $10$. You can as well take radius $R>0$ or $\epsilon>0.$ That doesn't make the problem statement non-clear, though. But I understand that it might be confusing.
I was about to write that I do not understand how you justify $u(\psi)=|x|^2u(\psi/|x|^2)$ as $|x|$ is not a constant. But then I realized that you do not mean $|x|^2$ multiplied with $u(\psi/|x|^2)$ but the distribution $|x|^2 u$ applied to $\psi/|x|^2$. In the "bracket" notation that I'm used to it would be $\langle u, \psi \rangle = \langle |x|^2 u, |x|^{-2}\psi \rangle.$ So, yes, you are on the right track; $|x|^{-2}$ is smooth outside of the ball.


Best way to create list of parameters from string

Question: I have a variable with space separated list of paths. I need to send these paths to a program as a parameter like this script.sh -i /dir1 -i /dir2. What is the best way  to create such parameter list? Something like $(echo "$paths" | sed 's|\([^[:space:]]\+\)|-i \1|g) will work but it's unreadable given the fact that it's part of the makefile.
Comment: this question should be moved to [stackoverflow](http://www.stackoverflow.com)
Answer: list="one two three"
for i in $list; do params="$params -i $i"; done
script.sh $params

You will have troubles with paths with spaces, using : as paths separator is better
Answer: use bash arrays
paths="/dir1 /dir2"
params=()
for path in $paths; do params+=( -i $path ); done
script.sh "${params[@]}"

Comment: You're correctly quoting the last expansion but none of the others; that will cause problems with spaces in filenames.
`for path in "$paths"; do params+=( -i "$path" ); done`
Comment: No. "I have a variable with space separated list of paths." Therefore, you must not quote `$paths` in the for statement, and you're guaranteed that `$path` will not have a space in it.
Comment: Ugh, you're right.
Brainfart on the silliness of the original question.


3 Level dependent dropdown. The 3rd list won't update while first one changes

Question: I am trying to create a 3 level dependent dropdown select.
Lv1 Options > Lv2 Options > Lv3 Options.
e.g:
AUDI > Coupé > A5
BMW  > SUV   > X5
I followed Examples module and this answer to create a custom module. (I know there is Hierarchical Select module does the job, I prefer do it with custom module)
My problem is that when level 1 option selected, level 2 options DID update, however, level 3 options DID NOT update to reflect level 2's change. I have to manually pick an option in level2 to make level 3 update.
Ideally, if level 1 dropdown select updated, level 2 options will update and level 3 options should also update.
Here is my code, dependent.module :
<?php

/**
 * Implementation of hook_menu().
 */
function dependent_menu(){
  return array(
    'dependentselect' => array(
      'title' => 'A page to multi level dependent select',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('dependent_page'),
      'access callback' => TRUE,
    )
  );
}

/**
 * A form with a dropdown whose options are dependent on a
 * choice made in a previous dropdown.
 */
function dependent_page($form, &$form_state) {
  // Get the list of options to populate the first dropdown.
  $options_first  = dependent_first_dropdown_options();
  $options_second = dependent_second_dropdown_options();

  $value_dropdown_first  = isset($form_state['values']['dropdown_first'])  ? $form_state['values']['dropdown_first']  : key($options_first);
  $value_dropdown_second = isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : key($options_second);

  $form['dropdown_first'] = array(
    '#type' => 'select',
    '#title' => 'First Dropdown',
    '#options' => $options_first,
    '#default_value' => $value_dropdown_first,
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'dependent_first_ajax_callback',
      'wrapper' => 'dropdown_second_replace',
    ),
  );

  $form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => 'Second Dropdown',
    // The entire enclosing div created here gets replaced when dropdown_first
    // is changed.
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => dependent_second_dropdown_options($value_dropdown_first),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'dependent_second_ajax_callback',
      'wrapper' => 'dropdown_third_replace',
    ),
  );

  $form['dropdown_third'] = array(
    '#type' => 'select',
    '#title' => 'Third Dropdown',
    // The entire enclosing div created here gets replaced when dropdown_first
    // is changed.
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => dependent_third_dropdown_options($value_dropdown_second),
    '#default_value' => isset($form_state['values']['dropdown_third']) ? $form_state['values']['dropdown_third'] : '',
  );

  return $form;
}

/**
 * Selects just the second dropdown to be returned for re-rendering
 *
 * @return renderable array (the second dropdown)
 */
function dependent_first_ajax_callback($form, $form_state) {
    return $form['dropdown_second'];
}

/**
 * Selects just the second dropdown to be returned for re-rendering
 */
function dependent_second_ajax_callback($form, $form_state) {
    return $form['dropdown_third'];
}

/**
 * Helper function to populate the first dropdown. This would normally be
 * pulling data from the database.
 *
 * @return array of options
 */
function dependent_first_dropdown_options() {
  return array(
    'colors' => 'Colors',
    'animals' => 'Animals',
  );
}

/**
 * Helper function to populate the second dropdown.
 *
 * @param key. This will determine which set of options is returned.
 *
 * @return array of options
 */
function dependent_second_dropdown_options($key = '') {
  $options = array(
    'colors' => array(
       'red' => 'Red',
       'green' => 'Green',
       'blue' => 'Blue'
    ),

    'animals' => array(
      'dog' => 'Dog',
      'cat' => 'Cat',
    ),
  );

  if (isset($options[$key])) {
    return $options[$key];
  } else {
    return array();
  }
}

/**
 * Helper function to populate the third dropdown.
 *
 * @param key. This will determine which set of options is returned.
 *
 * @return array of options
 */
function dependent_third_dropdown_options($key = '') {
  $options = array(
    'red' => array(
    'darkred' => 'Dark Red',
    'lightred' => 'Light Red',
    ),

    'green' => array(
      'darkgreen' => 'Dark Green',
      'lightgreen' => 'Light Green',
    ),

    'blue' => array(
      'darkblue' => 'Dark Blue',
      'lightblue' => 'Light Blue',
    ),

    'dog' => array(
        'bigdog' => 'Big Dog',
        'smalldog' => 'Small Dog',
    ),

    'cat' => array(
        'bigcat' => 'Big cat',
        'smallcat' => 'Small Cat',
    ),

  );

  if (isset($options[$key])) {
    return $options[$key];
  } else {
    return array();
  }
}

Answer: You've set #ajax callback event as 'changed', but it is not called for the 2 element after it changed, because your ajax callback returns the whole element(changed event is envoked only if you change selected option).
I'm not sure about proper solution, but as for me, I would have either added custom JS to change element after update, or experiment a little with changing #options for select.
One more variant is to return both form selects on first one change.
Answer: Just went through the docs again, realize that since I want to manipulate multiple elements.
I should use a 'bigger' wrapper for ajax replace.

You can easily replace the entire form if that is easiest. Just add a
prefix and #suffix to the entire form array, then set that as the #ajax['wrapper']. (This will allow you to change multiple form elements via a single ajax call.)

--
http://drupal.org/node/752056


Firebase user's context.auth is present still allAuthenticatedUsers secured Google function error with UNAUTHENTICATED

Question: I wrote a simple cloud function:
import * as functions from 'firebase-functions';

export const repeat = functions.https.onCall( function (data, context) {
    // Authentication user information is automatically added to the request.
    if (context.auth) {
        console.log(' context.auth is defined ');
        console.log(' uid is ' + context.auth.uid);
    } else {
        console.log(' context.auth undefine. ');
    }
        if (context.auth) {
            return {
                repeat_message: context.auth.uid + ' ' + data.message,
                repeat_count: data.count + 1,
            };
        } else {
            return {
                repeat_message: ' noUID ' + data.message,
                repeat_count: data.count + 1,
            };
        }    }
);

And a corresponding Flutter Client app:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:cloud_functions/cloud_functions.dart';

final FirebaseAuth _fAuth = FirebaseAuth.instance;

final GoogleSignIn _googleSignIn = GoogleSignIn(scopes: ['email'], signInOption: SignInOption.standard);

FirebaseUser _firebaseUser;
GoogleSignInAccount _googleSignInAccount;

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        textTheme: TextTheme(
          caption: TextStyle(
              fontSize: 20.0
          ),
          body1: TextStyle(
              fontSize: 20.0
          ),
        ),
      ),
      title: 'calling function',
      debugShowCheckedModeBanner: false,
      home: LaunchScreen(),
    );
  }
}

class LaunchScreen extends StatefulWidget {
  @override
  _LaunchScreenState createState() {
   return _LaunchScreenState();
  }
} // LoggingOptions  to _LaunchScreenState

class _LaunchScreenState extends State<LaunchScreen> {
  String _response = 'no response';
  int _responseCount = 1;
  final HttpsCallable callable = CloudFunctions.instance.getHttpsCallable(functionName: 'repeat')
    ..timeout = const Duration(seconds: 90);

  Future<FirebaseUser> _handleSignIn() async {
    try {
      GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
      _googleSignInAccount = googleSignInAccount;

      GoogleSignInAuthentication authentication = await googleSignInAccount.authentication;

      final AuthCredential credential = GoogleAuthProvider.getCredential(
        accessToken: authentication.accessToken, idToken: authentication.idToken,
      );
      AuthResult authResult;
      authResult = await _fAuth.signInWithCredential( credential);

      _firebaseUser = authResult.user;
      setState(() {});
      return _firebaseUser;
    } catch (e) {
      print(e.toString());
    }
    return null;
  }

  Future<void> _handleSignOut() async {
    FirebaseAuth.instance.signOut();
    _googleSignIn.signOut();

    setState(() {
      _firebaseUser =null;
      _googleSignInAccount= null;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar( title: const Text('Sample Code'),),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              MaterialButton(
                  child: const Text( 'Sign in with Google', style: TextStyle(fontSize: 16.0),),
                  onPressed: () {
                    _handleSignIn().then((user) {
                      // logggedIn
                      debugPrint('user ' + user.toString());
                    }
                        );
                  },
                  ),

                 MaterialButton(
                  child: const Text( 'Sign out with Google', style: TextStyle(fontSize: 16.0),),
                  onPressed: () {
                    _handleSignOut();
                  },
                ),

              Text( _firebaseUser != null ? _firebaseUser.uid : 'user logged off'),

              Text('FromServer $_responseCount: $_response'),
              MaterialButton(
                child: const Text('SEND REQUEST', style: TextStyle(fontSize: 18.0),),
                onPressed: () async {
                  try {
                    final HttpsCallableResult result = await callable.call(
                      <String, dynamic>{
                        'message': 'hello',
                        'count': _responseCount,
                      }
                      ,
                    );
                    print(result.data);
                    setState(() {
                      _response = result.data['repeat_message'];
                      _responseCount = result.data['repeat_count'];
                    });
                  } on CloudFunctionsException catch (e) {
                    print('caught Firebase functions exception');
                    print(e.code);
                    print(e.message);
                    print(e.details);
                  } catch (e) {
                    print('caught generic exception');
                    print(e);
                  }
                },
              ),
            ],
          ),
        ));
  }    }

and I can see in both server logs and client side that Auth is passed correctly.
But when I add allAuthenticatedUsers and remove allUsers to 'Cloud Functions Invoker' Role from the function, the App starts getting PlatformException with UNAUTHENTICATED code.
Here is how setting looks before the change:

And after adding allAuthenticatedUsers:

After removing allUsers:

Then when Flutter invokes the function (when the user is logged in), Flutter errors with

PlatformException(functionsError, Cloud function failed with
  exception., {message: UNAUTHENTICATED, details: null, code:
  UNAUTHENTICATED})

It should show an error only when the user is not logged in, but it is showing in either cases.
Answer: The cloud configuration for allAuthenticatedUsers is not in any way related to Firebase, and what it does for authentication for callable type functions.  Firebase callable functions handle their own authentication separately from the configuration you changed.  You should change it back if you want callables to work properly.
The allUsers permission that you removed was responsible for making your function accessible to the public, including your app.  When you removed that, you effectively removed the ability for anyone on the internet to be able to invoke the function (which is very much required for callable functions to operate as designed).
When you added allAuthenticatedUsers, what you did was require only callers that authenticate themselves with a Google service account.  Again, this is not related to Firebase or Firebase Auth.  It's a Google Cloud IAM concept.  It's not applicable for callable functions, so you shouldn't use it.  It's not clear to me why you thought this was a good configuration to make.
If you want Firebase callable functions to be invoked normally from apps, you should leave the permission at the default allUsers, and let the Firebase SDK handle the authentication of the end user.
Read more about Google Cloud access control lists to understand the cloud configurations that you were changing.
Comment: It's working as designed.  If you don't want unauthenticated Firebase Auth users to invoke it, you should return early out of the function if `context.auth` is not defined.  This is your only option.  You cannot stop the function from being invoked from anyone on the internet, but you can stop them from running your code without auth.
Comment: this callable can be called
**curl -X POST -d '{ "data": {"count":2,"message":"any message"}}'   'https://us-central1-xyz.cloudfunctions.net/repeat' -H "Content-Type:application/json"**
and that is what I wanted to avoid
Comment: I know - I understood the last comment that you deleted, and I'm saying that it's not possible to fully cut off access from unauthenticated users.  You have to check in your code if the user is authenticated and return early if they're not. Contact Firebase support directly to file a feature request if you'd like different behavior. https://support.google.com/firebase/contact/support
Comment: Using allUsers is a **BAD** solution. What is the solution for firebase express functions? (can't `context.auth`). I'm using SMS verification via Flutter


How to solve functions error in LibreOffice Calc

Question: I am trying to do a split expenses in libreoffice calc and I have referred to others people template. However, my LibreOffice Calc keeps showing error of "#value!".
<code>=SUM(IF(NOT(ISBLANK(K5:K55)),(1/$H$5:$H$55)*$D$5:$D$55))-SUMIF($F$5:$F$55,K4,$D$5:$D$55)
</code>
Comment: at first glance the if function is missing a third argument, but that should not be an issue so I guess it something in the SUMIF rows - can you add the value for the criteria K4
Comment: i have just uploaded another picture for more understanding. the k4 is the criteria
Comment: that part with e5h1:... doesn't look right probably missing a comma or something. Try pasting each part of the formula separately eg =SUM(...) , then =SUMIF(...) and you will see which part is wrong
Comment: i just corrected it but still failed. please kindly view pic again
Comment: Now the image shows the SUMIF function inside the SUM() - which is the correct form you want? Try writing the criteria in sumif as "=X" instead of H4. From the look of it the cell H4 is actually equal to A
Comment: I want to do a conditional sum by if there a x in A,then 1 divided by "No."  and multiple "Amount" respectively. Also, it minus the sumif as well in one line equation.
Comment: Please explain again what you are trying to achieve with 1 / . In Excel, this "dirty hack" really works. Calc is much stricter about the results of intermediate calculations - if in the depth of the formula there was a "division by zero" error, then Calc does not consider it possible to return any result, it would be a deception of the user. Explain what you are trying to achieve, and perhaps it will be done with a simple `SUMPRODUCT()`
Comment: Not sure how the AMT column is formatted - it should be a number to do the calculations you want. And the criteria should be either H5 or "=X" because you want to check that the value is X, not A (which is the value of the H4 cell)
Answer: It seems that you want an array operation. Finish the edit of the formula with Ctrl-Shift-Enter, see Array Functions.


Contar recorrências em uma lista

Question: Fiz o seguinte código para contar as recorrências em uma lista:
n = int(input())
n <= 100 and n >= 1
lista = []
for c in range(n):
     lista.append(int(input()))
for v in lista:
    repete = lista.count(v)
    print(v,repete)

Porém a saída que recebo é essa (Entrada: 56,70,67,56,90)(EXEMPLO):
56 2
70 1
67 1
56 2
90 1

A saída esperada era essa(é necessario o mantimento da ordem da entrada para a quantia de N valores na lista):
56 2
70 1
67 1
90 1

Comment: Oi, não resolve... Isso porque o reverse só mantem a ordem numa lista com o 3 e 2. Porém, minha lista pode agregar N valores, assim, o reverse não soluciona... Mesmo assim, muito obrigado pela atenção! @lmonferrari
Comment: E se a lista for `[1,2,3,2,2,1,1,3,2,2,3,1]`, deve mostrar em qual ordem?
Comment: Nesse caso, seria 1 2 3, porém falo de casos em que a lista é [35,231,12,543,12,35,12,76] no output eu gostaria de manter a ordem de entrada e retirar os repetidos que vem apos a primeira aparição...
Answer: Vamos usar o que o Python tem de bom... :)
Veja o exemplo abaixo:
>>> from collections import Counter

>>> lista = [1, 1, 2, 3, 4, 4, 2, 2]

>>> c = Counter(lista)

>>> print(c)
Counter({2: 3, 1: 2, 4: 2, 3: 1})

>>> lista_sem_repeticao = list(set(lista))

>>> print(lista_sem_repeticao)
[1, 2, 3, 4]

Veja que o método Counter que existe no pacote collections (padrão do Python, não precisa instalar) retorna um dicionário com a chave igual ao encontrado na lista e o valor a quantidade.
O método set retorna o tipo set que, por definição, é uma "lista" sem repetições. Coloquei lista entre aspas, pois não é o tipo lista.
UPDATE: Caso manter a ordem da lista inicial seja importante, o set não é a solução. No lugar disso, faça um list comprehension com um pulo do gato
>>> lista = [1, 1, 2, 3, 4, 4, 2, 2]
>>> aux = set()
>>> lista_sem_repeticao = [x for x in a if not (x in aux or aux.add(x))]
>>> lista_sem_repeticao
[1, 2, 3]

O Counter também funciona com Strings
>>> lista = ["banana", "goiaba", "laranja", "banana", "banana", "goiaba"]

>>> qtd_frutas = Counter(lista)

>>> qtd_frutas
Counter({'banana': 3, 'goiaba': 2, 'laranja': 1})

Espero que ajude
Comment: Oi, tentei usar esse metodo do set, porém ele inverte o 3 com o 2, o que não pode acontecer. Tem como resolver isso? Desde já, obrigado!
Answer: Primeiro, não use count, porque cada chamada precisa percorrer toda a lista para contar quantas vezes o elemento ocorre. Ou seja, mesmo se a lista não tiver nenhum elemento repetido, como por exemplo, [1, 2, 3], ainda sim ela será percorrida desnecessariamente 3 vezes (uma para obter a contagem do 1, outra para o 2, outra para o 3).

Quando você percorre uma lista várias vezes sem necessidade, está criando uma variação do chamado Shlemiel the painter's algorithm (conhecido anedoticamente por ser um "algoritmo ruim").

Então para contar os elementos, use um Counter, como sugerido em outra resposta, pois ele percorre a lista apenas uma vez e já guarda a quantidade de vezes que todos os elementos ocorrem.
Já para manter a ordem dos elementos, não adianta transformar a lista em um set, pois um set não garante a ordem dos elementos: a própria documentação diz que ele é uma "unordered collection" ("coleção desordenada"), então se quer manter a ordem, tem que fazer de outro jeito.
O que você pode fazer é usar um set para guardar os elementos que já foram impressos, e só imprimir caso seja a primeira ocorrência. Algo assim:
from collections import Counter

lista =  [35, 231, 12, 543, 12, 35, 12, 76]
contagem = Counter(lista)
visitados = set()
for n in lista:
    if n not in visitados: # se o número ainda não foi impresso
        print(f'{n:<4} {contagem[n]}')
        visitados.add(n) # marco que o número já foi impresso

Desta forma, quando o número aparece pela primeira vez, ele ainda não está em visitados. Da próxima vez ele já estará e não será impresso novamente. Assim eu imprimo os elementos na ordem em que a primeira ocorrência deles aparece na lista.
É mais ou menos a mesma ideia que uma das respostas fez, a diferença é que lá foi usada uma lista em vez de set. Mas eu prefiro usar set que é mais otimizado para buscas (tempo constante, versus o tempo linear de uma lista, veja aqui), e como a cada iteração será feita uma busca em visitados, isso pode fazer diferença conforme a lista original aumenta (e também se tiver muitos elementos repetidos) - veja mais abaixo um comparativo entre as duas soluções.
Por fim, também usei f-string (disponível a partir do Python 3.6) para formatar melhor a saída, que no caso do exemplo acima, será:
35   2
231  1
12   3
543  1
76   1

Mas claro que, uma vez tendo o algoritmo, você pode formatar a saída da forma que achar melhor.

Fazendo um teste rápido com o módulo timeit, para comparar as soluções (count() vs Counter):
from collections import Counter

def counter(lista):
    contagem = Counter(lista)
    visitados = set()
    for n in lista:
        if n not in visitados: # se o número ainda não foi impresso
            x = contagem[n] # usando o valor em vez de imprimir
            visitados.add(n)

def list_count(lista):
    filtro = []
    for i in lista:
        if i not in filtro:
            filtro.append(i)

    for v in filtro:
        lista.count(v) # só pegando a contagem em vez de imprimir

from random import choices
# lista com mil números (de 0 a 99 para ter vários repetidos)
lista = choices(range(100), k=1000)

from timeit import timeit

# testando mil vezes, com uma expressão válida e outra inválida
params = { 'number' : 1000, 'globals': globals() }
print(timeit('counter(lista)', **params))
print(timeit('list_count(lista)', **params))

Retirei o print porque I/O pode impactar nos testes e mascarar os resultados, então eu só peguei o valor da contagem e mais nada.
Lembrando que os tempos podem variar de uma máquina para outra, mas de qualquer forma, na minha o resultado foi (em segundos):
0.0981796
2.2945525

Ou seja, usando count() e um list para guardar os visitados foi cerca de 20 vezes mais lento do que usando o Counter e set.
É claro que para listas pequenas a diferença será imperceptível, afinal, para poucos dados, tudo é rápido...
Answer: Utilizando seu código/raciocínio, você pode utilizar um "filtro"(nova lista):
n = int(input())
lista = []

for c in range(n):
     lista.append(int(input()))

filtro = []
for i in lista:
    if i not in filtro:
        filtro.append(i)

for v in filtro:
    print(v, lista.count(v))

Entrada:
3
3
3
2
2

Saída:
3 3
2 2

O filtro vai conter a primeira ocorrência dos números na ordem em que eles aparecem.
Comment: Oi, esse set está invertendo a ordem do 2 com o 3, tem como ele não fazer isso?
Comment: @GabrielSchrader Um `set` não garante a ordem dos elementos, a própria [documentação](https://docs.python.org/3/library/stdtypes.html#types-set) diz que ele é uma "_unordered collection_" ("coleção desordenada"). A única garantia é que não tem elementos repetidos. Por isso a sugestão de usar `reversed` é uma gambiarra, que vai "funcionar" às vezes por coindicência. Por exemplo, se a lista for `[3, 3, 2, 2, 4, 4]`, o resultado de `list(set(lista))` é `[2, 3, 4]`, se usar `reversed` será `[4, 3, 2]` (ou seja, nenhuma das alternativas preserva a ordem original).
Comment: Vale lembrar que essa ordem resultante é detalhe interno de implementação: como um `set` não garante a ordem, ele pode muito bem mudar sua implementação de uma versão pra outra e o resultado ser diferente (ele só precisa garantir que não haverá repetidos, tanto faz a ordem). Fazer qualquer algoritmo que dependa da ordem que o `set` retorna estará sujeito a erro.
Comment: Oi, obrigado pela informação! Sou novo no mundo da programação e as aulas EAD estão dificeis de aprender... Sabe me dizer se há outra maneira de remover os repetidos e manter a ordem sem o set? @hkotsubo Muito obrigado desde já!!
Comment: A pergunta original não continha o requerimento para tal ordenação. O reversed era gambiarra mesmo.
Comment: @GabrielSchrader, veja o update de minha resposta para manter a ordem
Comment: @PauloMarques ficou perfeito! Obrigado!

Contar recorrências em uma lista


zshenv:2: command not found: rbenv

Question: I've just had a nightmare getting rbenv to load Ruby v 2.3.0. I've finally got it to show after adding 'eval "$(rbenv init -)"'to my .zshrc file. However, now I'm getting the note above at the top of my terminal when I relaunch.
Any ideas why this would show and how I can amend?
Comment: It wasn't the .zshrc file that was the issue it was the same line in the .zshenv which I've now deleted and the line has gone. It was showing at the top of my terminal when I launched it.
Comment: What does "the note" say? I have exactly the same line in my `.zshrc` and don't really recall it being a nightmare, rather a mundane documentation-following.
Comment: So is it solved or is there still a problem?
Comment: It's solved as far as I can see.
Answer: Stumbled upon this while debugging an issue, just clarifying for future interweb travelers.
Edit your ~/.zshrc file and add this:
eval "$(rbenv init -)"

Restart your terminal.

Here are some helpful links
https://stackoverflow.com/a/25452411/6114891
https://stackoverflow.com/a/42002830/6114891

zshenv:2: command not found: rbenv


compile error User-defined type not defined at "oShell As WshShell"

Question: I am currently using MS Access 2016 database. I get this compile error below

"compile error User-defined type not defined" at the code where it is
Dim oShell As WshShell

Below is the program. I dont understand where the problem is. Can anyone help me.
Sub SetWebControlAsIE9()
    Dim sKey As String
    Dim oShell As WshShell
    Dim vKey As Variant
    Dim nErr As Long
    Dim bNewStart As Boolean

    Set oShell = New WshShell

    sKey = "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION\msaccess.exe"
    On Error Resume Next
    vKey = oShell.RegRead(sKey)
    nErr = Err.Number
    On Error GoTo 0
    If nErr = -2147024894 Then
        oShell.RegWrite sKey, 9999, "REG_DWORD"
        Debug.Print "IE9 Mode set"
        bNewStart = True
    Else
        If vKey <> 9999 Then
            oShell.RegWrite sKey, 9999, "REG_DWORD"
            Debug.Print "IE9 Mode set"
            bNewStart = True
        Else
            Debug.Print "IE9 Mode is already set"
        End If
    End If
    Set oShell = Nothing

    If bNewStart Then
        RestartAccess
    End If

End Sub

Sub RestartAccess()
    If MsgBox("Die Datenbank und Access müssen neu gestartet werden," & vbCrLf & _
        "weil die Einstellungen für das WebControl geändert wurden." & vbCrLf & _
        "Jetzt neu starten?", vbQuestion Or vbYesNo, "Bestätigen:") = vbYes Then

        Dim sExec As String
        Dim oShell As Object

        sExec = Chr$(34) & SysCmd(acSysCmdAccessDir) & "msaccess.exe" & Chr$(34) & _
                " " & Chr$(34) & CurrentDb.Name & Chr$(34)
        oShell.Exec sExec
        Application.Quit acQuitSaveNone
    End If
End Sub

Answer: If you want to use late binding instead (not adding the reference) then you can change this
Dim oShell As WshShell

to this
Dim oShell As Object

and then change this
Set oShell = New WshShell

to this
Set oShell = CreateObject("WScript.Shell")

Comment: Hi, Thanks a lot. I think it works but I get the error now on a different part of the program. I just added the Sub RestartAccess part of program to the above my question. Do I have to make the same changes to this part of the script? on "oShell.Exec sExec" line the debugger highlights.
Comment: In your second routine, you have the first part that `Dim`s the object, but you dont have the second line that `Set`s the object. You have to have both.
Comment: I didn't get that exactly, sorry I am a beginner to VBA.
Comment: What didnt you get? Your second routine needs this line too - `Set oShell = CreateObject("WScript.Shell")` - Put it after the `Dim` line.


sftp download without keyring prompt - without change of .bashrc

Question: For a bash install script, I need to download files with sftp. When doing so, a gnome keyring prompt will open. This can be avoided by some changes in .bashrc or so.
But as my script should run on any machine without changing settings there, I'd need a solution which avoids that keyring lookup. Can somebody help?
Comment: Have you consider using ssh keys (with ssh agent)?
Answer: This is not an answer but space is limited in the comments section and may put you on the right path.

This can be avoided by some changes in .bashrc

This is worrying.

You assert this is possible but you don't provide any details of what the changes are nor why you think this is the case
If the behaviour can changed in .bashrc then it should be just as easy to change the behaviour inside your script

You didn't tell us what sftp client you are using. This is certainly not the default behaviour of Openssh sftp (you did not say what you are using) but its possible that when you type 'sftp' at the command line something else is happening before handing off to the actual sftp client. You might want to check the output of which sftp and alias sftp.
Again, assuming that this is openssh, then the behaviour maybe implemented via the SSH_ASK_PASS shell variable (start a terminal emulator and echo $SSH_ASK_PASS to check). If that is the case then you simply need to set the variable to blank within your shell script.
It is also possible that the keyring is activate as a helper program by the ssh_config. If that's the case then the config will be somewhere in /etc/ssh/ssh_config or a file included in that depending on which distribution of Linux you are running (you did not say). This config can be overridden on the sftp command line in your script.
Comment: Sorry for being so little precise. Now:
Comment: it's open ssh from ubuntu 22;
'echo $SSH_ASK_PASS' gives a blank;
'alias sftp' results in 'bash: alias: sftp: not found';
'which sftp' produces '/usr/bin/sftp'

"This config can be overridden on the sftp command line in your script." - That's what I'm seeking for. Thank you for your help.


C FILE stream implementation

Question: here it is, the FILE stream implementation in C :
<code>typedef struct
{
 short level ;
 short token ;
 short bsize ;
 char fd ;
 unsigned flags ;
 unsigned char hold ;
 unsigned char *buffer ;
 unsigned char * curp ;
 unsigned istemp;
}FILE ;
</code>
I really don't know what all of these are for, and I wonder if the buffer contains the full file or not. If not, how does mister C know where to find the rest of the file ?
Comment: The definition of FILE is not specified by the C standard. How it works is implementation-specific.
Answer: You are not supposed to know. FILE is an 'opaque' structure and you must not mess with its fields.
Probably, it does not contain the full file, and the associated functions read it as you request data.
To know more, you could read the source code for the f* functions, but don't assume that they will work the same in other versions of the library, or in other libraries.
Comment: I ask because I have a school project about making a filesystem on a fake disk (stored in a file)... In fact it's for DIR exactly.
I can read the whole dir and fill a struct with a buffer and an offset, but this is not optimum, and since directory (or file contents) might not be stored consecutively.
I still could store adress of the next block where to find datas in the struct, but that means the implementation depends of the filesystem... So I was wondering how does the real FILE and DIR does besides its opacity...
Comment: Well, the FILE functions do not deal with that directly. That's done deeper in the OS. But you already got the idea: ordered blocks, with a fixed size. That's the way to go.

C FILE stream implementation


Include intercept/error term in logistic regression model specification

Question: Short question,
When specifying a logistic regression model as below, does one also include B0?
In other words, does the bottom part of the equation look like:
A. 1 + exp(-(B1X1 + B2X2)
B. 1 + exp(-(B0 + B1X1 + B2X2)
And how about and error term?
Answer: It's always option B.  So in the notation of your source:
$$ t = \beta_0 + \beta_1 x_1 + \cdots + \beta_k x_k $$


Defintion for model diversity?

Question: Two models are diverse if they make prediction errors on different instances. I know there are different measures to quantify diversity, however, I'm looking for formal conceptual definition of what we are trying to measure. Any suggestions?
Comment: I'm not familiar with the phrase model diversity. However, it sounds like what you are after is related to the concept of model _sharpness_ in forecasting. A model has _sharpness_ (a.k.a. _resolution, discrimination_) if its predictions are sensitive to differences in the input data. One could construct a measure of distance between two models based on the degree to which they exhibit sharpness on different subregions in the space of input data. One could then derive a measure of diversity as a function of average or aggregate distance between models. Is this sort of what you are looking for?
Comment: I'm referring to the diversity required in an ensemble of classifiers. A requirement of a good ensemble is to have a set of classifiers each of which make prediction errors on different cases in the training set.
Answer: There is a great book on the topic of ensemble classifier. It is online on:
Combining Pattern Classifiers
There is a full chapter (ch10) in this book on diversity and how to measure it.
A set of measures are defined in the chapter including:
1- The Disagreement Measure.
2- The Double-Fault Measure.
3- The Entropy Measure E.
4- ...
I hope that this is what you were looking for.
Comment: The cited book is great and thanks for that. However, Ch 10 deals mainly with classification problems. How about regression? My naive approach is to use the old-fashion correlation coef, but I can think of multiple problems with that. Are you aware of anything specific to regression. I can't believe this thread didn't get more views and comments, as this is a very important problem in ML.
Comment: This question is prompted by the well known requirement in building ensembles that diversity of the component models gives better performance. Yea entropy should work.
Comment: @horaceT One workaround is to discretize the continuous variable and then apply any of those measures by Kucheva. I understand that this is not always meaningful or preserving original level of information. Otherwise, correlation could be a good choice to experiment with or other entropy-based measure for continuous variables.

Defintion for model diversity?


A better definition of Polynomial

Question: Usually, we define a polynomial as
$a_n x^n + \cdots + a_1 x + a_0$
where $x$ is called indeterminate.
Would it be better to define it as
$a_n x^n + \cdots + a_1 x + a_0 x^0$
where $x^0$ means the identity element in the structure which $x$ belongs to.
For the study of the polynomial itself, I think these two definition make no difference. But when you treat a polynomial (expression) as a polynomial function, and if we use the second definition, we can just substitute all the $x$ with some variable (eg. some square matrix), rather than define it in a "adhoc" way, i.e. if we are using the first definition, we have to explicitly define the function to add an identity element to the constant term $a_0$ to make $a_1 x$ and $a_0$ addable.
Is the second definition equivalents to the first one?
If yes, then is it true that the authors of those texts actually means def 2 when the define the polynomial using def 1, they just omit the identity element?
If not, why? Would it be nicer to eliminate the non-addable $a_1x + a_0$ with $a_1x + a_0 x^0$, (even though we really don't need to add these two terms together when we are studying the knowledge of polynomial itself)?
Comment: Please give an example of what you mean by the second requires "adding an identity... to make addable"
Comment: Did you mean $x^0$ instead of $x_0$ in that last line?
Comment: It really doesn't matter. Quite often, when written in sigma notation, we write it as $\sum_{i=0}^n a_ix^i$, even if we otherwise write $a+bx+cx^2$. I often use this notation for one of the reasons we define $0^0=1$ :)
Comment: You can also define a polynomial as a sequence $(a_0,a_1,\dots)$ where only finitely many $a_i$ are non-zero. Then $(1,0,0,\dots)$ is not $x^0$, where $x=(0,1,0,0,\dots)$, but rather $(1,0,0,0,0,\dots)$ is just the identity.
Comment: @BillDubuque Suppose that $x$ is a matrix, then $a_1 x + a_0$ is not a valid expression, but if you "add" the identity matrix $I$ to $a_0$, you get $a_0I$, which makes $a_1 x + a_0 I$ a valid expression.
Comment: Congratulations, you've independently invented modules! http://en.wikipedia.org/wiki/Module_(mathematics)
Comment: @NotanID See [this answer](http://math.stackexchange.com/a/4300/242) on $R$-algebras.
Comment: Why is it harder to add $a_0+b_0$ than it is to add $a_0x^0+b_0x^0$. You still haven't said.
Comment: It doesn't matter since as you said yourself multiplication by $x^0$ doesn't change the element being multiplied. Nevertheless it does make a subtle pattern more obvious, as in people can understand how that constant fits into the general scheme :)
Comment: @frogeyedpeas But the def 2 will allow substitution which will cause a problem. Please see my comment for Thomas Andrews's answer for the detail.
Comment: @NotanID It seems to me that the issue is the formal domain of the function isn't well defined. I'm taking a computer-scientist assumption that every function is assumed to come with a list of things that can be considered arguments for it, and that $x^0$ denotes the identity element of the groups of all possible arguments for which the polynomial can be evaluated. The type mismatch issue you helped answer earlier could've been dodged if the asker realized that the polynomial only acted on Matrices and $x^0$ was implied to be a matrix
Comment: @ThomasAndrews No, not $a_0 + b_0$, but $a_1x + a_0$. You will never want to or need to add $a_1x$ and $a_0$ together (to get a somewhat more simplified expression) when you treat a as an element of the polynomial ring, there is no problem here. But When you treat it as a function, and you plug a specific matrix, say $A$, into it, you get problem, since $a_1A + a_0$ is not a valid expression, but in the second def, you will get $a_1A + a_0I$, which is valid, sometimes whether or not I can perform the substitution is important (for example see the link I mentioned in your answer's comment).
Comment: $a_0+a_1x$ is $a_0+a_1x$. What is the difference? $x$ is an ideterminate.
Answer: It really doesn't matter which way you define polynomial. Another way is to consider all sequences:
$$(a_0,a_1,\dots,a_n,\dots)$$ where only finitely many $a_i$ are non-zero.
Then we add series point-wise, and we find their products by the Cauchy product.
Then $(1,0,0,0,\dots)$ is the multiplicative identity, and $(0,1,0,0,\dots)$ is $x$. So $1$ isn't really $x^0$, and $x^2$ just means $x\cdot x$.
Comment: @NotanID No, there is no problem when treating it as a function, as long as you accept that $0^0=1$.
Comment: For the study of the polynomial itself, it really doesn't matter. It is when you treat it as function that causes a problem, if you think def 2 is equivalent to def 1, then you will run into trouble with this formula $p(\lambda) = det(\lambda I - A)$, where $p$ is the characteristic polynomial of matrix $A$. because substitution is allowed, we can substitute the $\lambda$ in both sides with $A$, then you get "zero (that is the number 0) = ZERO (that is the zero matrix)". (to be continued)
Comment: ... Please see [this question](http://math.stackexchange.com/questions/885179/does-substitute-lambda-with-matrix-a-in-a-polynomial-conflict-with-the-axio) for detail.

A better definition of Polynomial


If $u$ solves Dirichlet problem $-\Delta u =f$, what is known about $fu$?

Question: Let $u \in H^1_0(\Omega)$ be the weak solution of
$$-\Delta u = f$$
$$u|_{\partial\Omega} = 0$$
Is there anything known about the sign of $fu$ a.e?
Comment: I think the sign of $\int_\Omega fu d\sigma$ is positive. But I have no idea about $fu$. I think it is complicated.
Comment: Do you have any particular $f$ in mind? In this generality there is nothing to say about this sign.
Answer: As Lion said: the integral of $fu$ is nonnegative, but not because of any pointwise bound for $fu$. It's integration by parts: $\int_\Omega (-u\,\Delta u ) = \int_{\Omega}|\nabla u|^2\ge 0$.
To give a simple example: let $u (x)=x(x-1)(x-4) $  in one dimension, with $\Omega=(0,4)$. Then $f(x) = -u''(x) = 10-6x$. The product $fu$ changes sign at $1$ and at $5/3$:


Amazon EC2, still cant ping or "http" it

Question: I am new at Amazon Cloud technologies. I ve set up an Amazon Linux instance created my keys and assigned elastic IP. Also, I opened all TCP, UDP, ICMP ports(ok, it's very dangerous, but I am using it for test purposes). I ve also installed Apache server and enabled it. But still cant ping or access my instance via IP. Any ideas?
EDIT:
Please see a screenshot of the security groups settings. All ports are open...
Check this out
Comment: try add a 80 port in security group.
Comment: Can you be a little more clear about what you can and can't do and what you want to achieve ?
Comment: I can make ssh connections, and of course to use the admin interface of aws console. But neither can ping my instance nor "http" to the apache server I just installed. Check my edits please...
Answer: Use the key (the .pem file) to connect to the instance.  You can get the address from looking at the instance in the EC2 console... it's at the bottom when you select one.
just do
<code>$ ssh -i [keyfile.pem] ec2-user@[address from the console]
</code>
that will get you in.  Also, you can try telnet to make sure it is listening
<code>$ telnet [address from the console] 22
</code>
That will connect to the SSH port over telnet which will let you know if it's up.  You won't be able to log in this way however.
EDIT = sorry, I didn't catch the part about apache for some reason.
check iptables
<code>$ iptables -L
</code>
Add a rule for port 80 if you need
<code>$ iptables -I INPUT 1 -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
</code>
Comment: He installed apapche, so he logged in so he has port 22 up.
Comment: Yeap, I already can make ssh connections.
Comment: Whoops, sorry.  2 things then. 1) check the Security Group.  2) check iptables.
Comment: Thank you...as you can see from my edits(screenshot), all ports are open. I added this rule on IP Tables and I executed iptables -L after that. Still cant connect to port 80
Comment: is apache running?
Answer: You need to go to EC2 console and in the security tab configure the firewall to open ports, ICMP (ping) and UDP if needed. This is stateless firewall on incoming packets only. By default it allows only SSH (tcp/22).
Comment: Hello Andrew, Please check my edits