Why we are calling System.gc() method to garbage collection of unused object

Question: Why we are calling System.gc() method to garbage collection of unused object, if garbage collection is automatically done in Java by daemon thread in background process with regular interval?
Comment: Who's 'we'? You might want to read this thread, and the code in question might be following bad practices or makes some assumptions - ask the person who put it in there why he did it: http://stackoverflow.com/questions/2414105/why-is-it-a-bad-practice-to-call-system-gc
Comment: No, *we* don't. The GC runs only when JVM runs out of memory and needs to get rid of, well, garbage. It does not run on regular intervals.
Answer: For testing purposes it can be useful to know when a GC has been performed. However this is rare and calling System.gc() when it isn't needed is such a common mistake that you can turn it off with -XX:+DisableExplicitGC.
Answer: We're not, because we're generally not smarter than the GC. Technically, calling it doesn't guarantee it'll run, although in many implementations it does.
Also, it's not necessarily done at regular imtervals, but based on an as-needed basis. Different implementations will start GC based on different criteria.
Answer: System.gc() just gives the garbage collector a hint that this might be a good time for garbage collection, e.g. because a lot of objects aren't used anymore and processing has finished.
It doesn't force the garbage collector to do anything - it just gives a hint.
Only use this once you need to optimze your application (after profiling).
I don't think I have ever seen it in production code so far.
Answer: While it shouldn't be necessary, I had code that thrashed much, much less when I did an explicit System.gc after a very large Map was emptied, just to be refilled again, in a loop. I think without a hint the collector tried minor gcs until it was clear that wouldn't do. Yes, I put it in production. I also put in a comment, just so my colleagues would test rather than blindly remove.


Sentry ignores --config path, but only for "start" command

Question: I've installed Sentry into a virtualenv located at /www/sentry/ and I have a config file /www/sentry/sentry.conf.py. I am able to run the following commands successfully:

$ sentry --config=/www/sentry/sentry.conf.py celery worker -B
$ sentry --config=/www/sentry/sentry.conf.py upgrade

I can even run sentry --config=/www/sentry/sentry.conf.py shell and then once in the Django shell, check that the settings module imported from django.conf has the custom settings I added in my sentry.conf.py file.
However, when I try to spin up the included Gunicorn server I get the following:
$ sentry --config=/www/sentry/sentry.conf.py start
Performing upgrade before service startup...
Loading help page organizations.md
Loading help page sampling.md
Loading help page tagging.md
Loading help page quotas.md
Loading help page teams_and_projects.md
Running service: 'http'
[2015-02-20 19:47:01 +0000] [19199] [INFO] Starting gunicorn 19.2.1
[2015-02-20 19:47:01 +0000] [19199] [INFO] Listening at: http://0.0.0.0:9000 (19199)
[2015-02-20 19:47:01 +0000] [19199] [INFO] Using worker: sync
[2015-02-20 19:47:01 +0000] [19219] [INFO] Booting worker with pid: 19219
[2015-02-20 19:47:01 +0000] [19219] [ERROR] Exception in worker process:
Traceback (most recent call last):
  File "/www/sentry/lib/python2.7/site-packages/gunicorn/arbiter.py", line 503, in spawn_worker
    worker.init_process()
  File "/www/sentry/lib/python2.7/site-packages/gunicorn/workers/base.py", line 116, in init_process
    self.wsgi = self.app.wsgi()
  File "/www/sentry/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/www/sentry/lib/python2.7/site-packages/sentry/services/http.py", line 34, in load
    import sentry.wsgi
  File "/www/sentry/lib/python2.7/site-packages/sentry/wsgi.py", line 20, in <module>
    configure()
  File "/www/sentry/lib/python2.7/site-packages/sentry/utils/runner.py", line 399, in configure
    initializer=initialize_app,
  File "/www/sentry/lib/python2.7/site-packages/logan/runner.py", line 89, in configure_app
    raise ValueError("Configuration file does not exist at %r" % (config_path,))
ValueError: Configuration file does not exist at '/www/.sentry/sentry.conf.py'
...etc...

I tried creating a /www/.sentry/ directory, and then copying my config file into it and then the server loads without a problem:
$ mkdir /www/.sentry/
$ cp /www/sentry/sentry.conf.py /www/.sentry/sentry.conf.py
$ sentry --config=/www/sentry/sentry.conf.py start
Performing upgrade before service startup...
Loading help page organizations.md
Loading help page sampling.md
Loading help page tagging.md
Loading help page quotas.md
Loading help page teams_and_projects.md
Running service: 'http'
[2015-02-20 19:50:12 +0000] [19653] [INFO] Starting gunicorn 19.2.1
[2015-02-20 19:50:12 +0000] [19653] [INFO] Listening at: http://0.0.0.0:9000 (19653)
[2015-02-20 19:50:12 +0000] [19653] [INFO] Using worker: sync
[2015-02-20 19:50:12 +0000] [19673] [INFO] Booting worker with pid: 19673
[2015-02-20 19:50:12 +0000] [19674] [INFO] Booting worker with pid: 19674
[2015-02-20 19:50:12 +0000] [19675] [INFO] Booting worker with pid: 19675

This seems silly and unnecessary however. Can anyone point me in the correct direction?
Answer: I had the same issue, I found this bug report:
https://github.com/getsentry/sentry/issues/1438
This commit fixed it for me: https://github.com/getsentry/sentry/commit/7629de1102973e4a3930487a3bf126a2f13c6850


What is $E[E[X|Y]|X]$? Could it be further simplified?

Question: I am trying to figure out what $E[E[X|Y]|X]$ equals to. Could it be further simplified?
My initial guess is that it should be equal to X. However, I have no clue if it is correct.
I know $E[X|Y] = \int xf(x|y)\,dx$ and $E[E[X|Y]|X] = \int \int xf(x|y)\,dx f(y|x)\,dy$, but I am stuck here.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: You are on the right track. To simplify [[|]|], you can use the law of iterated expectations, which states that [[|]|]=[|]. This means that the conditional expectation of  given , taken over all possible values of , is equal to the unconditional expectation of , taken over all possible values of .
Using this result, we have:
[[|]|] = [|]
Now, we can simplify [|] using the definition of conditional expectation:
[|] = ∫(|)
where (|) is the conditional probability density function of  given . However, (|) is a Dirac delta function centered at , which means that it is equal to 1 when =, and 0 otherwise. Therefore, we have:
[|] = ∫(|) = ∫δ(−) =
where δ(−) is the Dirac delta function centered at .
Therefore, we have:
[[|]|] = [|] =
which confirms your initial guess. So, [[|]|] is equal to .
Comment: It is easy to construct counterexamples to negate your judgement, e.g., check the case when $X$ and $Y$ are independent.
Comment: The law of iterated expectations says $E[X] = E[E[X|Y]]$ but not $E[X|X] = E[E[X|Y]|X]$!
Comment: Hi Aditya. You could use the MathJax that this site supports to typeset your equations. For a quick start, please check [Instructions on how to use LaTeX on CrossValidated](https://stats.meta.stackexchange.com/questions/1604/instructions-on-how-to-use-latex-on-crossvalidated).


ISA x Desempenho

Question: De que maneira a quantidade de instruções (ISA) pode afetar a análise de desempenho de um sistema? O compilador pode auxiliar na melhoria dos resultados?
Answer: ISA significa "Instruction Set Architecture" - "Arquitetura de Conjunto de Instruções". Há dois tipos de arquiteturas a se considerar: RISC e CISC.
O CISC significa "Complex Instruction Set Computer" - "Computador com Conjunto de Instruções Complexo". Esse tipo de computador apresenta diversos tipos de microinstruções codificados dentro do processador. Por vezes, o número de diferentes tipos de instruções estão nas casas das centenas e frequentemente elas têm formatos e tamanhos bastante variados. Entretanto, devido ao grande número de instruções, o projeto do processador acaba sendo bastante complicado e as instruções podem demorar algum tempo significativo para serem decodificadas e interpretadas, grande parte delas levando diversos ciclos de clock para serem concluídas.
O RISC significa "Reduced Instruction Set Computer" - "Computador com Conjunto de Instruções Reduzido". Esse tipo de computador apresenta apenas alguns poucos tipos de microinstruções codificados dentro do processador. Por causa disso, essas instruções têm formato e tamanho uniforme, o que também simplifica bastante o projeto do processador e simplifica a decodificação e execução das mesmas. Por vezes, todas ou quase todas elas demoram o mesmo tempo para serem executadas.
Há também uma arquitetura híbrida, que consiste em um processador de duas camadas, sendo a externa CISC e a interna RISC. Nesse processador, cada instrução CISC é traduzida em uma sequência de instruções RISC que são então executadas. Codificada nos circuitos do processador, há uma tabela denominada microcódigo que é utilizada para traduzir cada instrução CISC em uma sequência de instruções RISC.
Outras arquiteturas também são possíveis, especialmente no que concerne a processamento paralelo.
Observe que isso nada diz acerca do desempenho. Ter um grande número de possíveis instruções faz com que cada uma delas possa ser extremamente otimizada em nome de um melhor desempenho, permitindo ao compilador quando for gerar o código, uma ampla gama de possíveis instruções a serem escolhidas e combinadas. Mas isso complica bastante o projeto do processador e pode trazer um custo no desempenho por conta da complexidade. Já com o conjunto de instruções reduzido, um número maior de instruções é necessário ser executado para efetuar algum trabalho útil, mas essas instruções são bastante simples.
Um algoritmo qualquer para realizar alguma tarefa, quando escrito em uma sequência de instruções CISC, costuma ser bem menor do que em uma sequência de instruções RISC. O motivo disso é exatamente porque uma instrução CISC tipicamente representa o trabalho feito por diversas instruções RISC. Mas isso não significa que seja mais rápido e nem que não seja.
Enfim, nenhuma abordagem é inerentemente melhor que a outra. Para entender, imagine o seguinte: João e Maria estão em uma competição para ver quem enche mais rápido uma caixa d'água de 1000 litros. A cada 10 minutos, João despeja um balde que tem em média 20 litros de água (às vezes mais, às vezes menos) na sua caixa. A cada 3 segundos, Maria despeja uma xícara com exatamente 100 ml em sua caixa. Nesse ritmo, ambos demoram 8 horas e 20 minutos para terminar, empatando. Nessa abordagem, cada despejo na caixa d'água corresponde a uma instrução executada e a quantidade de água despejada representa a quantidade de trabalho executada por tal instrução, sendo João o que usa uma abordagem análoga ao CISC e Maria uma análoga ao RISC. Não há uma abordagem claramente melhor em termos de desempenho.
Quanto ao compilador, é ele quem produz a sequência de instruções a ser executada, então ele é que tem a responsabilidade por determinar qual sequência de instruções para realizar a tarefa descrita no programa a ser compilado que resultaria no melhor desempenho. Obviamente, isso não é algo simples, mas significa que o papel dele em melhorar a análise dos resultados é fundamental. Um compilador CISC tem um leque bem maior de possíveis instruções a escolher, o que também significa que é muito mais difícil saber qual seria a melhor combinação possível de sequência de instruções a ser emitida. Já o compilador RISC tem mais uniformidade nas instruções a serem emitidas, o que simplifica a análise, mas provavelmente significa produzir sequências de instruções mais longas.

ISA x Desempenho


Calculating the exact inverse of a transaction fee with a linear volume-based fee structure

Question: Let's say we have a volume-based fee structure that takes a 5% fee of a transaction from \$0, and a 2% fee at \$1000, with the intermediate amount being a linear interpolation of these two points - for example, \$500 would equate to a 3.5% fee.
The crux of the question comes when we want to calculate the inverse. I.e. instead of "if I give \$250, what do I receive?", we need to answer "if I need exactly \$250, what do I need to give?".
Given the linear interpolation of the fees, simply taking the inverse of the amount is no longer possible, as we would end up in a slightly more favorable fee rate.
An example of what I've tried so far, which due to the above doesn't quite work:
$$feeRate = 5 - (5 - 2) * \frac{250}{1000} = 4.25\%$$
$$amountOut = 250 * (1 - \frac{4.25}{100}) = \$239.375$$
Calculating the inverse:
$$feeRate = 5 - (5 - 2) * \frac{239.375}{1000} = 4.281875\%$$
$$amountOut = 239.375 * (\frac{1}{1 - 4.281875 / 100}) \approx \$250.083$$
Is there any way, creative or not, to make sure this inverse way of calculating the fee is possible?
I've also tried "chunking" the linear interpolation, i.e. making it into a series of steps instead of completely linear, but that just made it work for the amounts where both fell onto the same steps, but made it even less accurate when they didn't.
As long as any kind of solution is programmable, I'd be satisfied, even if it requires some sort of multi-step process/brute forcing. Herein also if rounding the fee percent to, for example, 2 decimals makes it easier, that wouldn't be a problem either.
Answer: I don't really understand why, in order to do the inverse, you still started from the interpolated rate. If you know that you end up with $239.375$, it seems to me that you just need to invert the second equation you wrote.
Plus, if you plug that number into the interploated rate, you are answering to your first question ("if I give you $239.375$, what do I receive?") with the new amount $239.375$.
Defining $A$ as what you called amountOut, $r$ as the feeRate and $x$ the amount you need we have:
$$
A = x \; (1-r) \Rightarrow r = 1- \frac{A}{x}
$$
In your example $A=239.375, \; x = 250 \;$ which gives the desired $r=4.25\%$


Subgroups in $G$ of the form $gHg^{-1}$

Question: Let $G$ be a group and $H$ be a subgroup of finite index. Prove that there is only a finite number of distinct subgroups in $G$ of the form $gHg^{-1}$ where $g$ belongs to $G$.
Answer: HINT: If $g'\in gH$, what can you say about $g'H(g')^{-1}$?

Subgroups in $G$ of the form $gHg^{-1}$


Group an aggregated view by date without time

Question: I would like to create a view that uses aggregation on an entity to display the count and the sum by date. But it should be grouped by date only without time even the original date value has time values. I.e.
Entity:
processedTime | amount | value | ...
01/01/2017 08:00:00 | 10 | 1 | ...
01/01/2017 08:18:10 | 10 | 1 | ...
01/01/2017 10:00:00 | 10 | 1 | ...
01/02/2017 08:00:00 | 10 | 1 | ...
01/02/2017 09:30:00 | 10 | 1 | ...
...
the view should output
01/01/2017 | 30 | 3 | ...
01/02/2017 | 20 | 2 | ...
If I create a view with aggregation grouped by the date field, the view also evaluates the time and tries to group by the entire value of the date field. How can I group only by year, month and day without time?
Answer: Add a field to the view for the date field you want to group by. In the filter config, set the date format to whatever level of granularity you want for the filter (in the image, it's by month), and tick exclude from display. Then you can group by this field.
Comment: That doesn't solve my problem. I want to use aggregation. In your example you are only grouping the items, but I want to group and to aggregate them (using count and sum).
Comment: I don't know that you can build this view completely within the Views UI. Having said that, it would be pretty easy to update your Twig templates to display the row count instead of the actual nodes.

Note: you may need the patch in https://www.drupal.org/node/2118743 to see what Twig templates Views is using.'
Answer: I was able to aggregate by year with a date field with a Year only format (Y) and AVG as the aggregation method on the field. Grouping was on the NID which was hidden from view.


On decreasing sequences $(a_n)_n$ such that $\sum_{n=1}^{+\infty} a_n$ diverges

Question: As an exercise for my math class, I have to find the widest possible choices of sequences $(a_n)_n$ such that $(a_n)_n$ is a nonnegative decreasing and the series $$\sum_{n=1}^{+\infty} a_n$$ diverges.
I was thinking about $a_n=\frac{1}{n}$, so that
$$\sum_{n=1}^{+\infty} \frac{1}{n}$$
is the harmonic series which diverges.
Could someone please help me with more exmples?
Thank you in advance!
Comment: What exactly do you mean by "widest possible choices of sequences"?
Comment: Typical examples are $\sum \frac{1}{n \ln(n)}$,$\sum \frac{1}{n \ln (n) \ln(\ln(n))}$, ...
Comment: Maybe it's a requirement the terms of the sequence to be non-negative, otherwise it's too easy.
Comment: Note that for every diverging series $\sum a_n$ there is a "more slowly" diverging series $\sum b_n$ with $b_n/a_n \to 0$, see for example https://math.stackexchange.com/q/452053/42969
Comment: @User1010 What does "as many as possible" mean, mathematically?
Comment: Are the examples supposed to satisfy specific constraints?
Comment: @AlannRosas nothing more than the fact that $a_n$ has to be a decreasing sequence (I guess in the next class some we will add some more binding conditions, but that's all so far).
Comment: @5xum I mean "as many examples as possible".
Comment: @MartinR thank you!
Comment: How about $\sum_{n=1}^\infty \sin \frac 1n$?
Comment: @5xum "What does "as many as possible" mean, mathematically?" Maybe it means the  limit as $n$ goes to infinity.
Answer: $(1)$ Take for example
$$\sum_{n=1}^{+\infty} \frac{1}{n^\alpha}$$
where $\alpha$ is a fixed number in the interval $(0,1)$
Give different values for $\alpha$ and you will get different divergent series.
$(2)$ More examples:
$$\sum_{n=1}^{+\infty} \frac{1}{n \cdot \ln(n)}$$
$$\sum_{n=1}^{+\infty} \frac{1}{\ln(n)}$$
$$\sum_{n=1}^{+\infty} \frac{1}{\ln^2(n)}$$
All these are divergent.
$(3)$ In general if $f(n)$ is a strictly increasing function which grows more
slowly than $g(n) = n$ then
$$\sum_{n=1}^{+\infty} \frac{1}{f(n)}$$  is also divergent.
$(4)$ Other interesting examples would be:
$$\sum_{n=1}^{+\infty} {\sin(n)}$$
$$\sum_{n=1}^{+\infty} {\cos(n)}$$
They are also divergent. But their terms are not all non-negative.
Comment: $\sin(n)$ is neither non-negative nor decreasing.
Comment: But that is what the question asks for.
Comment: Something different from $sum\frac{1}{n}$ and $\sum\frac{1}{n^{\alpha}}$?
Comment: I added a few more examples.
Comment: @MartinR I know. I didn't say it was.
Comment: @MartinR It asks for that after I mentioned it, and the OP changed the question.
Comment: @MartinR I don't claim that. Maybe you misread something.
Comment: Indeed, I misread.
Comment: @MartinR I put a "But"  there and some highlighting to avoid others misreading.


Definition of the preimage orientation

Question: Guillemin and Pollack give quite confusing (at least for me) definition of the preimage orientation (see below).
I don't understand the part starting from the last display. Namely:

How exactly does the last display follow?
Why does $T_xS$ contain $\ker df_x$ and how does it follow from this that $df_x$ restricted to $N_x(S;X)$ is injective (I believe that's what is claimed)?
At which point does this prove use the fact that every vector from $N_x(S; X)$ is orthogonal to every vector from $T_x S$?
Answer: It's not important that $N_x(S;X)$ is orthogonal to $T_xS$. It's only important that they are in direct sum. But you may find it useful for the sake of visualization/concreteness.
The reason that the kernel of $df_x$ contains $S$ is just that the kernel is spanned by the tangent vectors of curves mapped identically to $z$.
Since the kernel of $df_x$ is contained in $T_xS$ and $T_xS$ is in direct sum with $N_x$, the restriction of $df_x$ to $N_x$ is injective.
The last display consists of two assertions. One is that every element of $T_zY$ is the sum of an element of $df_xN_x$ and an element of $T_zZ$. The second is that the intersection of $T_zZ$ and $df_xN_x$ is just the zero vector. These two assertions follow from the previous equation, the fact that $T_xS$ is mapped into $T_zZ$ by $df_x$, and the fact that $T_xS$ is in direct sum with $N_x$.

Definition of the preimage orientation


Insertion Of dynamic dropdownlist values(of each row) from a gridview to tables

Question: //code in aspx.
   </asp:TemplateField>
        :
        :
        :
   <ItemTemplate>
   <asp:DropDownList ID="didDdl" runat="server"
    DataSourceID="departmentsDataSource"
    DataTextField="Department"
    DataValueField="DepartmentID"
    SelectedValue='<%# Bind("DepartmentID") %>'
    Enabled="False" />
   </ItemTemplate>
   </asp:TemplateField>

Q:I have to insert the selected dropdownlist items to a table all at a once i.e when i click a submit button(which i have not shown here) then all the selected values should go at a time to a table.
Answer: My assumption is you are using Gridview. So this will work.
protected void btnSubmit_Click(object sender, EventArgs e)
{
    List<string> lst = new List<string>();

    foreach(GridViewRow gvr in GridView1.Rows)
    {
        if (gvr.RowType == DataControlRowType.DataRow)
        {
            lst.Add(((DropDownList)gvr.FindControl("didDdl")).SelectedValue);
        }
    }
}

Improvised solution
protected void btnSubmit_Click(object sender, EventArgs e)
{

    SqlCommand comm = new SqlCommand();

    StringBuilder sb = new StringBuilder("INSET INTO [Table] ");

    string template = " SELECT @{0} UNION ALL ";

    foreach(GridViewRow gvr in GridView1.Rows)
    {
        if (gvr.RowType == DataControlRowType.DataRow)
        {
            string value = ((DropDownList)gvr.FindControl("didDdl")).SelectedValue;

            sb.AppendFormat(template, value);
            comm.Parameters.Add(new SqlParameter("@" + value, value));

        }
    }
    comm.CommandText = sb.ToString()

}

Answer: You can read values from your template columns then build an once Insert statement to SQL server.
the following example shows how to insert Multiple Records using One Insert Statement:
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

Answer: The best way i can think of is get the values inside an arrayList and through for loop insert the values into SQL.


ActiveAdmin: sort by child association's property

Question: I am having these objects:
class District < ActiveRecord::Base
  belongs_to :city
end
class City < ActiveRecord::Base
  has_many :districts
end

What I would like to do (and been unable to do so thus far), is: have a City column in District's index and that column should be sortable on City.name.
Closest thing I was able to do without crashing ActiveAdmin is:
index do
  column City.human_name(:count => :other), :city, :sortable => :city_id
end

Which of course is not good enough; I don't want to sort on foreign key's integer value.
Tried stuff like :sortable => 'city.name', gives an error. Even tried to do it like you do it on "pure" Rails - :joins => :cities, :sortable => 'city.name' - no luck. Tried a bunch of other stupid stuff, got annoyed and decided to humbly ask for help.
Can anyone point me in the right direction?
Thanks for your time.
Comment: what did your solution end up being..
Answer: That should also do the work:
index do
  column City.model_name.human, :city, :sortable => 'cities.name'
end

controller do
  def scoped_collection
    end_of_association_chain.includes(:city)
  end
end

Comment: shorter version, just add line "includes :city" instead of all "controller do" stuff
Comment: any ideas on how to sort by the count of the association? See http://stackoverflow.com/questions/15924458/activeadmin-sort-by-association-count
Comment: @alexBrand, I'd also use the counter cache approach, as suggested in the replies to your question. Cheers.
Answer: Try this.. It will help....
index do
  column :city, :sortable => :"cities.name" do |district|
    district.city.human_name(:count => :other) if district.city.present?
  end
end

controller do
  def scoped_collection
    District.includes(:city)
  end
end

Answer: Very simple and readable solution:
index do
  column :city, sortable: "cities.name"
end

controller do
  def scoped_collection
    # join cities
    super.includes :city
  end
end

Answer: Use the name of the table, probably cities. It might look like this:
District.joins(:city).order("cities.name")

Comment: I know this. I meant ActiveAdmin's DSL, though. Happily, it got fixed like 14 hours ago -- https://github.com/gregbell/active_admin/pull/623


Is there any way to read data by bytes length in R

Question: Is there any way to read data by bytes length in R like SAS input command?
When some multi-bytes characters are in a table as fixed column length,
aaa대전11b1
bb 서울21b2
ccc부산갑b3
SAS can read it by bytes length as below.
data test;
infile "filepath";
input
V1      $3.
V2      $6.
V3      $2. ;
run;
→
aaa, 대전11, b1
bb , 서울21, b2
ccc, 부산갑, b3

But in R, read.fwf only can seperate data by widths not by bytes lengths.
So, command like below
test <- read.fwf("file path", widths=c(3,6,2))
outputs error, or at best shape like this
aaa, 대전11b1, NULL
bb , 서울21b2, NULL
ccc, 부산갑b3
So, this is my question: Is there any way to seperate data columns by bytes lengths in R?
Comment: checkout this [link](https://stats.idre.ucla.edu/r/faq/how-can-i-read-binary-data-into-r/) and see if `readBin()` helps here with little bit of tweaking.
Comment: It sounds like you don't want to read the bytes, but the characters. The first two lines have 13 bytes but the third one has 14 bytes.
Answer: With below code you should get the desired output (note: you can have this solution as a workaround till the time you find a better way to do it!)
<code>file <- readLines("your_data_file.txt",encoding="UTF-8")
newTxt <- unlist(strsplit(file, split = "\u2028"))
newTxt <- lapply(newTxt, function(x) gsub("^([a-zA-Z]*)(.*)([a-zA-Z0-9]{2})$", "\\1,\\2,\\3", x))
df = do.call(rbind.data.frame, newTxt)
names(df) <- "combined_column"

library(tidyr)
df %>% separate(combined_column, c("col1", "col2", "col3"), ",")
</code>
Output:
<code>  col1    col2 col3
1  aaa  대전11   b1
2   bb  서울21   b2
3  ccc  부산갑   b3
</code>
Comment: @resol if you liked the solution then you should accept it as the right answer. It'll surely help others in case they encounter similar problem in future. Thanks!


Ember.js - ENV.host setting being ignored - how can I diagnose this?

Question: I've got two very similar, and simple, apps.
I start both of them as 'ember s' with no other arguments.
They both rely on a backend found at http://localhost:8000 .
One of them works perfectly the other is convinced it should be making API calls to http://localhost:4200 .
So for instance rendering a list screen on the working one involves a GET to http://localhost:8000/api/todos . Rendering a list screen on the non-working one results in a GET request being made to http://localhost:4200/api/projects .
The location of the backend is defined in config/application.js via the ENV.host property.
How can I further diagnose this problem to see why the non-working app ignores ENV.host ?
Any ideas welcome.
Both the working and and non working apps are running on Ember 2.4.2
I'll put the relevant configs below in case that helps.

The problem config/application.js looks like this :
module.exports = function(environment) {
  var ENV = {
    host: 'https://example.com',
    modulePrefix: 'spuv-ember',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
       ENV.host = 'http://localhost:8000';
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};

The working config\application.js looks like this :
module.exports = function(environment) {
  var ENV = {
    host: 'https://example.com',
    modulePrefix: 'todo-ember',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  ENV['ember-simple-auth'] = {
    authenticationRoute: 'login',
    routeAfterAuthentication: 'todos',
    routeIfAlreadyAuthenticated: 'todos'
  };

  if (environment === 'development') {
    ENV.host = 'http://localhost:8000';
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};

The non-working version of app/adapters/application.js showing the ENV.host value being used :
import DS from 'ember-data';
import ENV from 'spuv-ember/config/environment';

export default DS.JSONAPIAdapter.extend({
  host: ENV.host,
  namespace: 'api'
});

The working version of app/adapters/application.js showing the ENV.host value being used (slightly different due to this app also using a form of authentication) :
import DS from 'ember-data';
import ENV from 'todo-ember/config/environment';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {
  host: ENV.host,
  namespace: 'api',
  authorizer: 'authorizer:drf-token-authorizer'
});

Comment: Are both projects using the same version of Ember? Are you setting the host in your application adapter?
Comment: @NicholasJohn16 : Thanks for your comment. Yes both are using the same version of Ember and yes I'm setting the host in the application adapter. I'll update the question showing the adapter setting in a few minutes. Will also dig out the actual ember version, which I can't recall off top of my head . Thanks again for your response.
Comment: Are you using authentication with just one or both?
Comment: @NicholasJohn16 Only one of the two apps has authentication and that's the one that works. It's my intention to add authentication to the working one but when I came across this problem I put off doing that.
Comment: @NicholasJohn16 : I've done an edit to the question to show the host being set in the respective application adapters.
Comment: Just editted the question to include details of the Ember version under which the two apps are running.
Comment: There's a type in one of the comments above and for some reason I can't edit it so I'm just going to change it here : The original text was "Only one of the two apps has authentication and that's the one that works. It's my intention to add authentication to the working one but when I came across this problem I put off doing that." and it should have read "Only one of the two apps has authentication and that's the one that works. It's my intention to add authentication to the non-working one but when I came across this problem I put off doing that."
Comment: Do you have a separate adapter for `projects`?
Answer: You're code looks correct to me and I've struggled with this myself. My only suggestion to you is to use the proxy option:
ember s --proxy http://localhost:8000

This will proxy all the requests through that domain and should hopefully allow you to continue development.
Comment: Thanks that did the trick although I find it a bit flaky that this is th only way of making it work ! Regardless, thanks for your help, I appreciate it.


Como mesclar duas arrays multidimencionais, desprezando valores repetidos?

Question: Eu tenho dois arrays multidimensionais. Um array eu estou trazendo de um arquivo .json, o outro está vindo de um POST via Ajax.
A minha ideia é gerar um novo array com a fusão desses outros dois outros arrays multidimensionais, sem repetir os dados.
Os arrays vindos por POST via Ajax trazem informações de elementos de uma página. O campo 'tempo' é único, já o campo 'vis' pode variar entre os valores 0 e 1 (não visualizado e visualizado).
Esse abaixo é o array vindo do arquivo .json:
{"AdministradorGabrielOliveira":
    [
        {
            "tempo":"2017-08-24T04:57:13-03:00",
            "vis":1
        },
        {
            "tempo":"2017-08-24T04:57:13-03:04",
            "vis":0
        },
        {
            "tempo":"2017-08-24T04:57:13-03:05",
            "vis":0
        }
    ]
}

E esse abaixo é o array vindo do POST via Ajax:
{"AdministradorGabrielOliveira":
    [
        {
            "tempo":"2017-08-24T04:57:13-03:00",
            "vis":0
        },
        {
            "tempo":"2017-08-24T04:57:13-03:01",
            "vis":0
        }
    ]
}

Ao final, eu deveria ter como resultado da fusão dos dois arrays, um outro com o conteúdo:
{"AdministradorGabrielOliveira":
    [
        {
            "tempo":"2017-08-24T04:57:13-03:00",
            "vis":1
        },
        {
            "tempo":"2017-08-24T04:57:13-03:04",
            "vis":0
        },
        {
            "tempo":"2017-08-24T04:57:13-03:05",
            "vis":0
        },
        {
            "tempo":"2017-08-24T04:57:13-03:01",
            "vis":0
        }
    ]
}

Tentei percorrer os arrays dentro de dois foreach, mas não tive sucesso. Alguém pode me dar uma dica?
[EDITADO] : Segui a dica de vocês e mudei a estrutura para o user comportar os valores 'tempo' e 'vis', com 'tempo' como sendo o id.
Comment: Existe alguma razão para você não usar o valor de `user` como chave do elemento? Uma chave por user e dentro do elemento user, uma chave por `tempo` que teria o valor de `vis`. Isso facilitaria bastante seu trabalho.
Comment: Seguindo a sugestão do @ClaydersonFerreira facilitaria até nas coisas que iria fazer a seguir como por exemplo, pegar em todos os tempos de um user e fazer qualquer coisa. No que tem neste momento você teria que iterar a coleção inteira.
Comment: Qual o parâmetro para definir se é igual? Os três valores devem ser idênticos?
Comment: De acordo com a estrutura e descrição do AP presumo que sejam iguais se `user` e `tempo` forem iguais já que o `vis` indica só se foi ou não visualizado
Comment: Na realidade eu tinha pensado nisso só não pus em prática porque o código que desenvolvi estava funcionando no modelo inicial, aí não quis mudar pra não perder o foco. Mas não tinha pensado que isso poderia facilitar tanto as coisas... :/ rsrs boa!

Se entendi bem o que vocês estão propondo, a estrutura de array deveria ficar assim, não é?

 {"user":
  [
   {
    "tempo":"2017-08-24T04:57:13-03:00",
    "vis":0
   },
   {
    "tempo":"2017-08-24T04:57:13-03:01",
    "vis":0
   }
  ]
 }
Comment: Até sei como mesclar esses Json, porem eu não sei como fazer isso sem repetir os dados.
Comment: O seu problema é semelhante a este outro: https://pt.stackoverflow.com/q/231110/64969; vou tentar subir assim que possível uma adaptação da solução apresentada para a questão que linkei
Comment: Opa! Vou olhar direitinho as dicas quando chegar em ksa. Mas desde já, muito obrigado!
Comment: E sim. vou passar a usar o  'user' como array principal, e 'tempo' como id, para eu pesquisar só na coleção que realmente preciso. Valeu pela dica pessoal.
Answer: A solução do @WictorChaves é suficiente para a questão, dado o tamanho dos dados. A solução que proponho abaixo é overkill, com uma entrada algumas ordens de grandeza acima do que está sendo utilizado para o caso da questão atual.

Teve uma pergunta que respondi recentemente que precisava de performance para julgar a interseção entre dois conjuntos em C#. Ele usava um algoritmo quadrático o(n * m) para determinar a interseção. Na minha resposta, fiz um preâmbulo teórico mostrando que é possível resolver o problema em tempo linearítmico (aproximadamente o(n log n)).
Bem, a questão lá tratava de calcular a interseção, mas essa aqui trata de calcular a união. Aqui, está sendo feito uma união matemática de conjuntos propriamente dita, por isso o comportamento de eliminar as duplicações.
Na união de conjuntos, acontece o seguinte:

Para fazer a operação de união desse jeito, também é necessário remover os valores idênticos.
Se os conjuntos estão desordenados, precisamos comparar todos os valores de um conjunto com os do outro conjunto. Portanto, tempo quadrático o(n * m).
Porém, se os conjuntos estiverem ordenados, a identificação dos termos idênticos precisa de tempo linear o(n + m). Na minha resposta, sugeri um algoritmo para identificar os elementos da interseção. Vou apresentar uma versão ligeiramente modificada dele.

A, um conjunto ordenado de elementos do tipo E
B, um conjunto ordenado de elementos do tipo E
cmp : E,E -> S, uma função que, dados dois elementos de E, define qual a relação entre eles; retorna - caso o primeiro elemento seja menor do que o segundo; + se o primeiro elemento for maior do que o segundo ou 0 caso os elementos sejam idênticos (S é o conjunto sinal: {-, 0, +})
entrada:
  A, conjunto ordenado de elementos do tipo E
  B, conjunto ordenado de elementos do tipo E
  cmp, função sinal que compara dois elementos de E
retorno:
  C, conjunto de elementos do tipo E oriundo da união de A e B

começo
  i <- 0 # índice para iterar em A
  j <- 0 # índice para iterar em B
  C <- []
  ultimo_elemento_adicionado <- null

  enquanto i < A.tamanho && j < B.tamanho:
    s = cmp(A[i], B[j])
    se s == '0':
      # elementos são iguais, um deles como elemento candidato
      candidato <- A[i]
      i <- i + 1
      j <- j + 1
    senão, se s == '-':
      # A[i] < B[j], então próxima comparação será com A[i + 1] e B[j]; A[i] agora é candidato
      candidato <- A[i]
      i <- i + 1
    senão # caso trivial onde s == '+':
      # A[i] > B[j], então próxima comparação será com A[i] e B[j + 1]; B[j] agora é candidato
      candidato <- B[j]
      j <- j + 1
    # agora vamos ver se o candidato deve ser inserido em C: precisa ser distinto do último elemento adicionado, ou ser o primeiro elemento adicionado
    se ultimo_elemento_adicionado != null && cmp(candidato, ultimo_elemento_adicionado) != '0':
        ultimo_elemento_adicionado = candidato
        C.push(candidato)
  # caso i ou j extrapolem o tamanho de A ou B, respectivamente, não há mais comparações a se fazer
  retorna C
fim

Ao todo, há a garantia que a busca demore o(n + m) operações. Tempo linear, fazendo com que seu problema torne-se tangível agora.
Em compensação, para poder fazer esse algoritmo de tempo linear, precisamos pré processar os conjuntos de dados A e B, conforme reparado pelo @Isac. Conforme expliquei na resposta em C#, é possível fazer uma ordenação total em qualquer conjunto de elementos compostos, contanto que cada uma das chaves desses elementos seja passível de ordenação total.
Então, desenvolvendo a função cmp que estabelece relação de ordenação total entre os elementos desejados no seu conjunto de elementos, você consegue fazerordenar os elemento em o(n log n) e então aplicar o algoritmo acima e obter a união.
Para transformar o JSON em objetos PHP, você pode usar a função json_decode. No caso, depois de decodificar o JSON, basta ordenar usando a função cmp de ordenação total do campo o array dentro do objeto decodificado $json_decodificado->AdministradorGabrielOliveira.
Comment: Nossa! Muito obrigado mesmo pelo esclarecimento @JeffersonQuesado .  Confesso que estava desenvolvendo sem pensar tanto na questão do peso desse processamento. Vou me atentar mais pra esse "detalhe".
Comment: Respondendo a [uma pergunta sobre complexidade](https://pt.stackoverflow.com/a/237026/64969), percebi que cometi um pequeno erro na operação de união. Falta terminar de percorrer os elementos restantes dos conjuntos `A` e `B` quando o `while` termina para os conjuntos `B` e `A` respectivamente
Comment: @GabrielOliveira , pro seu caso, com quantidade controlada, não precisa se preocupar demais
Answer: Este código remove todos os valores repetidos.
<?php
$entrada1 = '{"forum":[{"user":"AdministradorGabrielOliveira","tempo":"2017-08-24T04:57:13-03:00","vis":1},{"user":"AdministradorGabrielOliveira","tempo":"2017-08-24T04:57:13-03:22","vis":1},{"user":"AdministradorGabrielOliveira","tempo":"2017-08-24T04:57:13-03:04","vis":0},{"user":"AdministradorGabrielOliveira","tempo":"2017-08-24T04:57:13-03:05","vis":0}]}';
$entrada2 = '{"forum":[{"user":"AdministradorGabrielOliveira","tempo":"2017-08-24T04:57:13-03:00","vis":1},{"user":"AdministradorGabrielOliveira","tempo":"2017-08-24T04:57:13-03:04","vis":0},{"user":"AdministradorGabrielOliveira","tempo":"2017-08-24T04:57:13-03:05","vis":0},{"user":"AdministradorGabrielOliveira","tempo":"2017-08-24T04:57:13-03:01","vis":0}]}';

$json1 = json_decode($entrada1);
$json2 = json_decode($entrada2);

foreach($json1->forum as $indice => $f1){
    foreach($json2->forum as $f2){
        if(!isset($f1) || !isset($f2)){
            continue;
        }
        $f1_string = json_encode($f1);
        $f2_string = json_encode($f2);
        if ($f1->user == $f2->user && $f1->tempo == $f2->tempo){
            unset($json1->forum[$indice]);
        }
    }
}

Comment: Vou testar nesse exato momento, meu caro!
Comment: @JeffersonQuesado Só vejo uma solução não quadrática para o algoritmo, que é utilizar chaves especificas em ambos os arrays, o que torna O(n). Mas implica pré processamento de ambas as estruturas de entrada.
Comment: Verdade... Feito!
Comment: Seu código está ótimo, brother! Só tem aquele detalhe que até agora não consegui resolver. Seguinte, os valores de $entrada1 são recebidos dum site como sendo o feedback de uma postagem clicada, então, se eu tiver na $entrada1 o 'tempo'='x1' e 'vis'=1 , e na $entrada2 o 'tempo'='x1' e 'vis'=0 , eu devo mesclar as duas considerando que a posição que contém 'tempo'='x1', tanto em $entrada1 quanto em $entrada2, isso devem resultar em $entrada1 = '{"forum":[{"user":"AdministradorGabrielOliveira","tempo":"x1","vis":1}]}';
Comment: Fiz uma alteração, agora ele compara o "user" e o "tempo", então se o "user" e o "tempo" for igual ele remove o item da "entrada1". Assim fica mais fácil para você decidir o que você quer comparar.
Comment: Essa solução é quadrática. Se o tamanho da entrada poder explodir (por exemplo, alguns milhões de dados), então o tempo de execução dela se torna inviável. Se você tem a garantia de que ela é de tamanho controlado (talvez até alguns milhares de dados?), essa preocupação que falei anteriormente é purismo
Comment: @Isac sim, com pré processamento mesmo. Imaginei aqui uma solução usando ordenação, o que reduziria para `o(b log n + n)`. A parte linearítma para o pré processamento, mais `o(n)` da busca
Comment: Opa! **Muito obrigado @WictorChaves e todos que ajudaram!** Esse script está ótimo pra o que preciso. Realmente Jefferson e Isac, existe a questão do excesso de processamento desses dados, mas não será problema para o que tenho. Os dados que irei analisar, tanto os que virão da página quanto os que virão do arquivo, são relativamente pequenos pq a página mesmo exclui as notificações de postagens com um certo tempo, então nem precisarei guardar dados antigos por muito tempo. Vou ainda, colocar um limite no tamanho do array. Mas de novo, obrigadão pela colaboração, pessoal. Ajudou pra caramba!!!
Comment: @GabrielOliveira marque esta resposta como resposta da sua pergunta, por favor.


Dimension selection based on test accuracy

Question: consider that I have a dataset with train, validation and test set and I want to train the pipeline PCA+logistic regression classifier. So far, for a specific k (that is the reduced data dimension from PCA), a logistic regression classifier is trained on the training set, using the validation set for tuning the parameters of the classifier. The fine-tuned classifier is subsequently used to get an accuracy for the test data. Then, for another value of k, the same procedure is followed to get another accuracy for the test data.
Is it fair to follow this procedure to choose the best value for k?
Comment: This method is OK for selecting the best model, but the test error you get will be biased low because you did optimization over the test set. You will need yet another holdout set to get a proper test error with this method.
Answer: No, this procedure isn't fair because you're essentially fitting your $k$ (number of principal components) to the test set. This results in information leakage from the test set and therefore means you'll get a biased estimate of how well your model will generalise to unseen data.
You should think of $k$ as another hyperparameter that you're tuning, so you should use the validation set for this purpose. I guess the key is to realise that you're basically tuning a pipeline ($k$ + logistic regression hyperparameters), so use the validation set to tune it and then use the test set to get an idea of how well your best model will generalise.


How can i find my WPF Autocompletebox in my DataGrid?

Question: Hello I've been trying to integrate an Autocompletebox into my project for days, unfortunately without success. I'm getting a little desperate. I have at least found a very simple solution for a text box outside of my Datagrid (DotNetProjects.WpfToolkit.Input 6.0.90 https://www.nuget.org/packages/DotNetProjects.WpfToolkit.Input/) but I can't put it in my . I followed the instructions in this video: https://www.youtube.com/watch?v=SK8TXvcPWqI. I will post my Code here:
<Grid>
<controls:AutoCompleteBox x:Name="ACB2" Text="TT" ></controls:AutoCompleteBox>
</Grid>

This Box is working. I Can find the Box "ACB2" in my Code:
public Databasewindow()
        {
            InitializeComponent();
            ACB2.FilterMode = AutoCompleteFilterMode.Contains;
            ACB2.ItemsSource = new string[] { "TEST1", "TEST2 TEST2", "TEST3 TEST3" };

        }

But when i try to fill a Column and use this box i fail and cant find my Textbox anymore
<Grid>
<DataGrid x:Name="DataGrid1"
    <DataGridTemplateColumn  Width="200" Header=" Command ">
                    <DataGridTemplateColumn.CellTemplate >
                        <DataTemplate>
                            <controls:AutoCompleteBox
                                Text="{Binding Command, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                                x:Name="ACB2"
                                ></controls:AutoCompleteBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
           </DataGrid>
         </Grid>

The Binding Text="{Binding Command, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" is working good. But i cant find the x:Name="ACB2" in my Code anymore. Can anyone help me with this? I tried many different AutoCompleteFunctions (Nuget) but i always had problems with the suggestions-Bindings. Maybe someone has some experience with this and can can help me out? That would be very, very nice. Kind regards
Answer: There are many ways to do this but I would tell you the simplest. Put x:Name to your DataGrid and get its first child so it would be your textbox. If you have smth more difficult to implement then look at MVVM and DataBinding... Its a long way of information to get but it is a right thing to know while working with WPF.
    public List<string> AutoCompleteBoxItems { get; set; } = new List<string>();

    public Databasewindow()
    {
        InitializeComponent();

        AutoCompleteBoxItems.Add("Test1");
        AutoCompleteBoxItems.Add("Test2");
    }

And XAML
        <controls:AutoCompleteBox Text="{Binding Command, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
    ItemsSource="{Binding AutoCompleteBoxItems}"
FilterMode="Contains"></controls:AutoCompleteBox>

Also you can use this method for find your UIElement but do that in DatGrid.Loaded event. You can always extend that method and find all same UIElements, but again thats not how you should do it. Use DataBinding insted. Strongly recommend.
Comment: Hello Melkor V, thank you for your reply. Can you give me an example? Kind regards
Comment: For this approach you need an ItemsSource property in your DataGrid. Another way to solve the problem is to bind ItemsSource for your AutoCompleteBox like:  Where CollectionOfItems is a collection with { "TEST1", "TEST2 TEST2", "TEST3 TEST3" } inside your DataBaseWindow as public property with get/set
Comment: Wow thank you so much! Tomorrow i will test it, when i am back at work again. You saved my day. When i have a problem at programming i cant stop thinking about it xD
Comment: @MarioAllw You'r welcome. Remember to mark an answer as accepted x)
Answer: So i found a solution for my Binding problem. Thank you Melkor V for your support. Here is my Code:
In my Xaml i had to add these lines for my Binding:
XAML:
xmlns:controls='clr-namespace:System.Windows.Controls;assembly=DotNetProjects.Input.Toolkit' xmlns:local="clr-namespace:Databases"

In my Datagrid => Commandselection is the Class where i wrote a List and AutoCompleteBoxItems is the Name of the List
<DataGrid
   <DataGrid.DataContext>
         <local:Commandselection/>
   </DataGrid.DataContext>
</DataGrid>

<DataGridTemplateColumn  Width="200" Header=" Command ">
                    <DataGridTemplateColumn.CellTemplate >
                        <DataTemplate>
                            <controls:AutoCompleteBox
                                Text="{Binding Command, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                                ItemsSource="{Binding Path = DataContext.AutoCompleteBoxItems, RelativeSource={RelativeSource AncestorType=DataGrid}}"
                                FilterMode="Contains"
                                ></controls:AutoCompleteBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

Here is the Code of my Class:
class Commandselection
    {

        public static ObservableCollection<string> AutoCompleteBoxItems { get; set; }
        public Commandselection()
        {
            AutoCompleteBoxItems = new ObservableCollection<string>()
            {
                "Apple",
                "Banana",
                "Carrot",
                "Dog",
                "Elderberry",
                "Fruit",
                "Grapes",
                "Honey",
                "Iron"
            };
        }

    }


Using Vim, what is the best way to implement PHP code folding that only folds functions blocks?

Question: I'm currently using Vim to edit PHP files and would like to implement code folding for functions only. I've tried setting the foldmethod=expr and using a regex with foldexpr in my .vimrc file. The problem is i don't fully understand how foldexpr is using the regex to apply folding to the source code and i can't seem to get it right.
Basically i want all PHP functions (inside classes too) to be folded and that's it. The nearest i've got is:
set foldexpr=getline(v:lnum-1)=~'function'?'>1':'='

but it's not right and i want to see if i can be a little more intelligent with the curly braces.
Any ideas?
Answer: I achieved what i needed by using the built-in PHP plugin, activated by putting this in my .vimrc file and not using any other folding settings.
let php_folding = 1        "Set PHP folding of classes and functions.
let php_htmlInStrings = 1  "Syntax highlight HTML code inside PHP strings.
let php_sql_query = 1      "Syntax highlight SQL code inside PHP strings.
let php_noShortTags = 1    "Disable PHP short tags.

Answer: IIRC folding do not work with regexes because it will slow vim down. You might get what you want by using foldmethod=indent and set foldnestmax to limit the number of nested folds created.
Answer: Check out the phpfolding plugin.
This is much better than the built-in php_folding syntax stuff because it understands phpdoc/doxygen docblocks, folds the code so you can still see the function name (but hides the documentation which precedes it).
Example:

It is a bit weird, you need to run :EnablePHPFolds to update stuff, and I get an odd message when I start up Vim (but that might be because I've installed it with Vundle), but it's a thing of beauty!
(Also referenced at https://stackoverflow.com/a/11859632/623519)
Comment: I've moved on to this other folding plugin https://github.com/swekaj/php-foldexpr.vim


Delphi FireMonkey botão em tTabControl não responde

Question: Estou criando uma App com o Berlin Starter Edition. Coloquei um tTabControl no Form, criei uma Tab e coloquei um tButton nela. Tanto o tTabControl quanto o tButton estão Enabled. Porém quando rodo o programa, o botão não reage (com se não estivesse Enabled). Alguem tem alguma dica? Grato.

O botão não reage porque no Style do tTabControl foi inserido um tRectangle para dar cor de fundo. Embora o texto do botão aparece, estou clicando no tRectangle. Não adianta enviar o tRectangle para trás e nem o botão para frente. Tem que achar outro modo de dar cor de fundo ao tTabControl que não seja inserindo um tRectangle no Style.
Alguém tem uma dica?
Answer: A solução é só marcar a propriedade Enabled do tRectangle como False.


Google Sheets - multiple increment buttons

Question: I would like to add buttons to a Google Sheet that allow me to increment or decrement a cell value.
I have gone through tutorials like the one here, and answers on Stack Overflow like the one here, however each of these talks about manually drawing shapes and assigning code to those shapes.
My situation has 2 problems with this approach:

I want to be able to add increment and decrement buttons to lots of
cells without having to draw and encode each button.
The drawing tools in Google Sheets is fairly basic and redrawing the same sized
button each time is proving to be difficult at best.

In trying to come up with a solution to this situation I have considered a few things.  The "buttons" don't have to look like buttons for my purposes, if I can trigger code by clicking on a cell this will suffice.
Hopefully there is a programatic way to create these buttons in Google Sheets, that would be ideal.  However at this point I would just settle for better drawing tools so I can at least have identical shaped buttons.
Is there a better approach to adding multiple increment buttons to Google Sheets?
Comment: Would you mind using the sidebar and making the button like this `` and it increments the value of the current selected cell by one if it is a number.  You can use the same button on all pages
Answer: Using the SideBar
Works on any page
Apps Script:
function increment() {
  const ss = SpreadsheetApp.getActive();
  const cell = ss.getActiveCell();
  const v = cell.getValue();
  if (!isNaN(v)) {
    cell.setValue(Number(v) + 1);
  }
}

function showMySidebar() {
  SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile("sidebar"))
}

HTML: (sidebar.html)
<!DOCTYPE html>

    <title>Sidebar Buttons</title>

    <input type="button" value="increment" onClick="google.script.run.increment();" />

Demo:

With what you have here adding the decrement should be a breeze
Answer: Alternative Solution #1: Register Scripts as Macros
You may bind scripts as Google Sheets macros for faster results. For a quick guide on macros with Google Apps Script, you may view the Google Sheets Macro page.
Script
You may bind the following scripts:
function increaseValue() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var values = ss.getActiveSheet().getActiveRange().getValues();
  var out = values.map(x=>x.map(y=>parseInt(y)+1));
  ss.getActiveSheet().getActiveRange().setValues(out);
}

function decreaseValue() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var values = ss.getActiveSheet().getActiveRange().getValues();
  var out = values.map(x=>x.map(y=>parseInt(y)-1));
  ss.getActiveSheet().getActiveRange().setValues(out);
}

Output:
For the script's function, I bound them to ctrl+alt+shift+1 and ctrl+alt+shift+2 macros.

NOTE: As what can be seen in the demonstration, the script would return #NUM! when the cell is empty.
Alternative Solution #2: You may use Check Boxes
I noticed that you can automate the addition and removal of check boxes using the insertCheckboxes() and removeCheckboxes() functions, respectively. So I had this idea wherein you may use check boxes as a substitute for buttons if you want to generate multiple check boxes.
Script
For this, an onEdit() script (which you may use as the basis for your code) is used.
function onEdit(e) {
  var column = e.range.getColumn();
  var row = e.range.getRow();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  if (column == 1) {
    try {
      if (e.value.length > 0) {
        ss.toast('Adding Checkboxes');
        ss.getActiveSheet().getRange(row,2,1,2).insertCheckboxes();
      }
    }
    catch {
     ss.toast('Removing Checkboxes');
     ss.getActiveSheet().getRange(row,2,1,2).removeCheckboxes();
    }
  }
  else if (column == 2) {
    var value = ss.getActiveSheet().getRange(row,1,).getValue() + 1;
    ss.toast('Increase Value');
    ss.getActiveSheet().getRange(row,1,).setValue(value);
  }
  else if (column == 3) {
    var value = ss.getActiveSheet().getRange(row,1,).getValue() -1;
    ss.toast('Decrease Value');
    ss.getActiveSheet().getRange(row,1,).setValue(value);
  }
}

Output
I have made a test case for the script wherein a user will add numerical values to column A which triggers the generation of check boxes in its corresponding columns B and C.

Removing a value in column A would remove the check boxes.

Changing the values of the check boxes from false to true and vice versa will trigger the increment or decrement of values (as seen below):

References:

Google Sheets Macro
Class Range: insertCheckboxes()
Class Range: removeCheckboxes()
Comment: Feel free to ask if you have other questions.


Basic pages are being rendered incorrectly do they differ at all to the article or custom content types in any fundamental way?

Question: I have a custom theme, all (custom) content types display as expected except basic pages. Is there something fundamentally different to basic pages that explains/ helps me to troubleshoot why the markup is different?
The site has custom theme/child-theme, custom modules, and a heap of contrib modules so I can't really "paste the code", and as it's a development site I can't give access to it.
The problem I'm experiencing seems to be HTML markup errors, some missing closing elements etc., but I've stepped through most of the code already and can't see anything. Is it something specific to basic pages that Drupal does differently?
Comment: No, Basic Pages are just another content type. I suggest checking elements related to basic pages: templates, blocks that are placed only on basic pages, etc.
Answer:
Is there something fundamentally different to basic pages that explains/ helps me to troubleshoot why the markup is different?

No, content types are completely generic. Drupal core processes them identically, but of course, custom and contrib code can heavily affect how they work.
You're going to need to check your theme, templates and custom modues, and maybe even contrib modules (depending on what you have installed and how you have them configured). The problem is with one or more of them, not with the content type itself.


Colocar header em metodo ajax get

Question: Boa tarde, eu tenho o seguinte pedaço de codigo:
function getData(){

    var url = "http://teste.com";
    var data = "";

    $.get(url, function(response){

    serverResponse = response;

        for(i in response.content){

            data +='\

\
                '+response.content[i].TesteId+'	\
                '+response.content[i].TesteNome+'	\
                '+response.content[i].TesteEmail+'	\

';
        }

        $('#corpotabela').empty();
        $('#corpotabela').append(data);

        var width = new Array();
        $(".table-body tr:eq(0)").find('td').each(function (position){
            width[position] = $(this).outerWidth();
        });
        $(".table-header tr").find('th').each(function (position){
            $(this).css("width", width[position]+2);
        });

    });
}

Porem, para conseguir fazer essa requisição eu preciso enviar um token no header. Eu consigo fazer isso utilizando esse metodo jQuery?
Comment: Testa passar um objeto de configuração com `{url: url, beforeSend: function(xhr){xhr.setRequestHeader('X-Token', 'meu-valor');}`.
Answer: Você vai precisar fazer algo assim
$.ajax({
   url : myurl,
   headers: {
        'X-Auth-Token' : token
   });

Mais informações de como fazer isso, leia o doc $.ajax();

Colocar header em metodo ajax get


Find $\int_{C}Fdr$ for the given $F$ and $C$

Question: I need to find $\int_{C}Fdr$.
$$F = (2x-y+4)i + (5y+3x-6)j$$
$C$ is the triangle with vertices $(0,0)$, $(3,0)$, $(3,2)$ traversed counterclockwise.
My first approach to doing this is splitting $C$ into $C1$, $C2$, $C3$
First is $C1$ from $(3,0)$ to $(0,0)$ so I plugged in the parametrization into the formula.
So my $F = (2(3-3t) -y +4)i + (5y + 3(3-3t) -6)j$
and $dr = (4-y)i + (5y - 6)j$
so then I have the integral...
$$\int_{0}^{1}((10 - 6t -y)i + (5y+3-9t)j) * ((4-y)i + (5y - 6)j)$$
(Note $*$ means dot product)
Solving this gives me just $C1$, I need to do this two more times to get $C$. This is seems way too long of a solution and there must be a much faster way of doing this using perhaps differential notation or something, I'm not sure.
Can anyone show me the better solution to this, I really don't think my answer is the way to go.
Answer: Use Green's theorem: $$\int_C Fdr = \iint_T\Big(\dfrac{\partial Q}{\partial x} -
 \dfrac{\partial P}{\partial y}\Big)dA,$$
where $F(x,y) = (P(x,y), Q(x,y)).$ Here, $C$ is the boundary of the triangle and $T$ is the region enclosed by the triangle.
Comment: Could you elaborate a little bit, I'm not sure I quite see how to use it
Comment: In this case, $F(x,y) = (2x-y+4, 5y+3x-6)$ and so $\dfrac{\partial Q}{\partial x} - \dfrac{\partial P}{\partial y} = 3 - (-1) = 4.$ Since this is constant, the integral is then simply equal to 4 times the area of the triangle.


Hibernate JPA @OneToOne Lazy loading

Question: I am trying to make @OneToOne association LAZY, which is EAGER by default.
I can think of two reasons:
1) Fake @OneToOne as @ManyToOne.
2) Have the foreign key column in owner table and then use fetch type as LAZY.
Can anyone please point out the pros/cons of the above strategies. Also, let me know if there is other better solution available.
Comment: Option 2 is the standard way for doing these things in JPA. I don't fully understand why you would consider option1?
Comment: Using `@OneToOne(fetch = FetchType.LAZY)` to enable lazy loading will only work if you enable weaving, either static (compile time) or dynamic (at runtime). Weaving will modify the code to have the `One` reference be "weak".
Comment: @mwhs- But, i didn't enable weaving and still it(@OneToOne(fetch = FetchType.LAZY)) worked.
Comment: @steelshark- I considered option1 only because for Option 2), foreign key column should be in owner table to make LAZY work. What if i can't change database schema.
Answer: More correct and clean solution is option 2 - you do not want to modify your model only to instruct underlying ORM framework how to load your data, unless absolutely necessary. However, there are situations where this does not work out of the box, and you must either tweak JPA to really turn on LAZY behavior, or go with option 1 (however, option 1 should use @OneToMany instead of @ManyToOne).
I will explain and try to demystify option 2 - ie. LAZY loading of @OneToOne and @ManyToOne, which map reference to a single entity (not a collection). Example:
@Entity
public class Main {
  @OneToOne(fetch = FetchType.LAZY)
  private Secondary secondary;
}
The way, how hibernate does the lazy loading, is that it creates a proxy object with the same methods as class Secondary, but only with @Id field set and all other data fields empty. When you call any method on this object for the first time, data is loaded into a new Secondary object and the method call is forwarded. Difference to EAGER loading is not only that data is loaded later only when needed, but also that there will always be an intermediary object between Main and Secondary entities, even after data is loaded. This can only be done by JPA if a subclass of Secondary can be created (if is not final).
Another way to achieve LAZY loading is to modify the original Secondary class to inject data loading code into each method, so that it does not need to be proxied. In fact, the functionality of a proxy object is merged into the code of original class. This is called weaving (or bytecode instrumentation), and can be done during compilation or even during runtime via a special classloader or attached java agent. When comparing efficiency of execution, following inequality applies: Proxying is slower than Dynamic weaving is slower than static weaving. Therefore waving is sort of optimisation. Though, in real world, you rarely care as the slowdown is insignificant.
Generally, if you inject EntityManager as a Java EE resource, via @PersistenceContext annotation, JPA does all the proxying/weaving for you, therefore LAZY loading always works. However, if you create EntityManager manually, like Persistence.createEntityManagerFactory('unit').createEntityManager(), then you might need to enable weaving.

Hibernate JPA @OneToOne Lazy loading


ler arquivos txt com php

Question: Tenho a seguinte situação: possuo arquivos em formato txt, que são gerados por um outro programa e vou ter que ler linha a linha esse arquivo para gerar boletos de pagamento, nesse arquivo aproximadamente eu terei 40 colunas com dados.
Bem, para efeito de processamento desses dados, seria melhor eu ler esse arquivo txt e ir diretamente fazer a geração dos boletos,ou seria melhor eu colocar esses dados num base de dados e depois para fazer a geração desses boletos eu faria uma leitura desses dados?
Terei arquivos que podem ter mais de 50 linhas de uma só empresa.
Fico preocupado com a performance para fazer tudo isso. Vai gerar os boletos em formato PDF estarei utilizando o HTML2PDF para gerar os pdfs.
Poderia ter uma outra forma de ler esses arquivos txt?
Answer: Tenta com o file do PHP mesmo.
<code>$f = file("arquivo.txt");
foreach($f as $item){
  echo $item .'<br>';
}
</code>
Comment: Imagino fazer isso,mas me preocupa a performance, imagine que vou ter umas 40 empresas para gerar boletos e cada empresa aproximadamente terá de 30 a 50 boletos.

ler arquivos txt com php


Is there a name for the matrix constructed in this way. Does it have any other interested properties?

Question: Recently I participated in a competition, where I was given two vectors $X$ and $Y$. A matrix is constructed from this two vectors in such a way that
$$M_{i,j} = \frac{1}{x_i + y_j}$$
The task was to find a determinant of this matrix (which I successfully done).

My question is whether this matrix has a specific name and may be some other (except of determinant) interested properties or applications? By specific name I mean something like this.
Comment: From the list you linked, it could be a cauchy matrix.
Comment: @DanielV you are right, this is it.
Comment: I'll write it as an answer so the question can be marked as closed.
Answer: If the sequences do not have any repeated values, then it is a Cauchy Matrix.


Initialization with empty curly braces

Question: First attempt and everything works fine:
class Base {
 public:
    Base() {std::cout << "default ctor!\n"; }
};
...
Base b{};
Base b_one = {};

Another way of implementation(add explicit):
class Base {
 public:
    explicit Base() {std::cout << "default ctor!\n"; }
};
...
Base b{};
Base b_one = {};  // error! Why?

I have read on cppreference that in both cases default initialization would be used and no diffences.
From list initialization:

Otherwise, If the braced-init-list is empty and T is a class type with a default constructor, value-initialization is performed.

From value initialization:

if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;
Answer:
I have read on cppreference that in both cases default initialization would be used and no diffences.

No they're not the same. To be precise, Base b{}; is direct-list-initialization, while Base b_one = {}; is copy-list-initialization; for copy-list-initialization, only non-explicit constructor may be called.
(emphasis mine)

direct-list-initialization (both explicit and non-explicit
  constructors are considered)
copy-list-initialization (both explicit and non-explicit constructors
  are considered, but only non-explicit constructors may be called)
Comment: @GusevSlava `operator=` will be tried to called. If the default constructor of `Base` is not `explicit`, then `{}` is implicitly converted to `Base`, then copy assignment operator (`Base::operator=(const Base&)`) is called. If the default constructor is `explict`, then it'll fail because implicit conversion fails.
Comment: Oh, thanks. Too simple question ;) So can you help with one more? What happens when we assign to already initialized variable `b_one = {}`

Initialization with empty curly braces


Save user info in one or multiple documents

Question: I am currently overthinking something that should be trivial.
I need to save user info that is composed of different sections like settings, weather, profile.
Should I be saving each in a different document or everything under one document?
For me it kind of seems ambiguous (since these docs wont be queried) and I am scared I am missing or not considering something.
Comment: "Should I be saving each in a different document or everything under one document?" => Your question is way too broad for SO and we don't have enough contextual elements to answer in a sensible way... In particular: size and structure of the sections, are they going to be accessed separately, with different access rights?, etc..., etc...
Comment: @RenaudTarnec Well it's personal user info. I said it is not going to be queried nor are there different access rights. Also the size of the documents are not big.
Answer: There is no singular right way to model data in Firestore, nor in most other NoSQL databases. It all depends on the use-cases of your app, and you likely don't know all of those yet. So I find it best to just pick an approach, and see how far it gets you.
If you want to train yourself to get better at this, I recommend reading NoSQL data modeling and watching Getting to know Cloud Firestore, which cover many scenarios of data modeling in Firestore (always in the context of a specific set of use-cases).


Remove extra bagage from string in javascript

Question: I am having an issue to replace "\r\n        Departing\r\n                  " with "Departing" in javascript.
Please suggest best way to do this.
Answer: This should work:
"\r\n Departing\r\n ".replace(/[^a-z]/gmi,'');

g => global
m => multi-line
i => case-insesitive
[^a-z] => chars, a to z, but thanks to case-insensitivity A-Z are not replaced, either.
If numbers might occur in the string, you can prevent them from being replaced pretty easily:
"\r\n Departing2\r\n ".replace(/[^a-z0-9]/gmi,'');

If all you want to do is remove line-feeds and trim the remaining string:
"\r\n Departing2\r\n ".replace(/[\r\n]/gm,'').replace(/^\s+|\s+$/g,'');
"\r\n We're Departing, too\r\n!".replace(/[\r\n]/gm,'').replace(/^\s+|\s+$/g,'');

Should take care of things for you rather nicely
Answer: This should work:
"\r\n Departing\r\n ".trim()

Comment: Word of warning: IE <9 doesn't have a trim method, you'll have to augment the prototype: `if (!String.prototype.trim){ String.prototype.trim = function(){ return this.replace(/[\r\n]/g,'').replace(/^\s\s*/,'')).replace(/\s\s*$/,'');};}`
Comment: @EliasVanOotegem I agree, but never the less, I'm still pointing it out for the user to notice in case it's not how we assume =)
Comment: The question doesn't state if to remove all white spaces, but if that would be the case, .trim() would only remove at the start and end.
Comment: @Mario: there's a space after the line-feed, just before `Departing`, and as the desired result is `'Departing'`, it's a fair assumption to make, IMHO
Answer: Use regexp.
str.replace(/\s/g,"");    /*  "\r\n Departing\r\n "(/\s/g,"") = "Departing" */

Comment: Shusi, it also removes spaces in between words which i don't want. like , `first name` is replaced by `firstname`.
Comment: @Ramiz-Raja, in that case, my suggestion is what you need: `"\r\n We're Departing, too!\r\n ".replace(/[\r\n]/gm,'').replace(/^\s+|\s+$/g,'');` returns: _"We're Departing, too!"_
Answer: var mystring = "\r\n Departing\r\n ";
mystring = mystring.replace(/\r\n/g, "");

Demo: JSFiddle
Comment: The suggested trim method is not to be recommended, it won't filter out unix-style line-feeds (`\n`) and breaks the expected behaviour of removing trailing spaces, too.


O que uma chave estrangeira realmente faz no banco de dados?

Question: A chave estrangeira no MySQL faz alguma ação no banco, ou só serve para eu "ver" quais campos estão relacionados há uma tabela auxiliar?
Como faço uma chave estrangeira no MySQL?
Comment: Seja bem vindo Samuel, acredito que você esteja fazendo confusão no conceito de chave estrangeira, 'só serve' ?  Leia está  pergunta: https://pt.stackoverflow.com/questions/106084/qual-a-utilidade-de-usar-chaves-estrangeiras/106087
Comment: Pra responder à sua segunda pergunta, especifique qual banco de dados você usa (SQL Server, MySQL, PostgreSQL...)
Comment: MySQL. @ViniciusBrasil
Answer: Chave estrangeira (foreign key) é o campo que estabelece o relacionamento entre duas tabelas. Assim, uma coluna corresponde à mesma coluna que é a chave primária de outra tabela. A função do  relacionamento entre tabelas através das chaves estrangeiras é manter a integridade referencial dos dados.
Fonte: Breve Conceito de Foreing key
No MySQL você pode criar a chave estrangeira quando criar a tabela:
CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (PersonID) REFERENCES Persons(PersonREF)
);

Ou após a criação da tabela:
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonREF);

Onde "Order" é a tabela da chave estrangeira e "PersonID" é o campo que buscará os dados do campo de referência "PersonREF" da tabela "Persons".


Loop infinito com "While not Cds.Eof do"

Question: Tenho um while not Eof normal num ClientDataSet.
O único detalhe é no AfterScroll, onde edito o dataset em questão e dou um post no mesmo. Quando o Eof é True, após o post ele altera para False. Depurando a situação, percebi que internamente o ClientDataSet chama a rotina Resync, que por sua vez, chama a rotina ActivateBuffers, e esta por fim, altera o controle FEOF para False. Nesse ponto, continuo no último registro do meu ClientDataSet, porém ele entende que não está no Eof.
Como posso resolver isso? É um bug do Delphi?
Código:
Cds.First;
While not Cds.Eof do
begin
  Sleep(10);//Exemplo
  Cds.Next;
end;

AfterScroll
Cds.Edit;
Cds.FieldByName('QTDE').AsFloat := 10;
Cds.Post;

No AfterScroll, quando está EOF, após o Post o EOF retorna para False.
Comment: Se ele esta posicionado no ultimo registro então não é EOF.
Comment: @ReginaldoRigo Você tem razão, me expressei errado (Desculpe). Mas após o *Cds.Next*, entra no *AfterScroll* e nesse momento já está como **EOF**, o problema é que após o post no CDS, o **EOF** é alterado para ***False***.
Comment: Andrey, posta seu código :)
Comment: Pelo o que você falou, ele reposiciona o ponteiro no último registro e isso confunde a lógica que você usou em seu fluxo. Eu acho que você precisa alterar esse fluxo ou essa lógica.
Comment: Pessoal, descobri com a ajuda do @ReginaldoRigo. Realmente era problema de lógica. Por já estar como EOF, não havia registro selecionado, quando era dado Edit/Post, retornava para o último registro válido, mas o EOF realmente deixava de ser True. Obrigado.
Answer: Com a ajuda dos comentários do Reginaldo, cheguei a uma solução.
No AfterScroll, antes de executar o Edit / Post, faço um if, verificando se o dataset não está como EOF.
if not Cds.Eof then
begin
  Cds.Edit;
  Cds.FieldByName('QTDE').AsFloat := 10;
  Cds.Post;
end;

Dessa forma, ele apenas executará o Edit / Post enquanto houver um registro sendo visualizado no DataSet.


Smooth function onto a regular submanifold

Question:
Let $M^m, N^n$ be smooth manifolds and $f:M\to N$ a continuous map such that $f(M)\subset S$, where $S$ is a regular submanifold of $N$ with codimension $k$. Prove that $f$ is smooth with respect to the submanifold atlas of $S \Leftrightarrow f$ is smooth with respect to the atlas of $N$.

Here is what I've thought so far:
Take $p\in M$ and a chart $(U, \phi)$ at $p$. Since $S\subset M$ is a regular submanifold, there is an adapted chart $(V, \psi)$ at $f(p)\in N$ such that $\psi(V\cap S)=\psi(V)\cap (\mathbb{R}^k\times\{0\}^{n-k})$. In particular, we have a chart $(V\cap S, \tilde{\psi})$ at $f(p)\in S$ , where $\tilde{\psi}(q):=(\psi^1(q),...,\psi^k(q))$.
Now, in some neighbourhood of $\phi(p)\in \mathbb{R}^n$ we have:
\begin{cases}
    \psi\circ f\circ\phi^{-1}(x_1, ..., x_n)=(y_1, ..., y_k, 0, ...,0) \\
    \tilde{\psi}\circ f\circ\phi^{-1}(x_1, ..., x_n)=(y_1, ..., y_k)
\end{cases}
Of course, $\psi\circ f\circ\phi^{-1}$ is smooth $\Leftrightarrow \tilde{\psi}\circ f\circ\phi^{-1}$ is smooth.
But that is still not enough, since $\psi$ is only an adapted chart, and I'm supposed to prove this for an arbitrary $\psi$. Besides, I can't see how the continuity of $f$ plays a role here. I'm stuck. Any sugestions? Thanks!
Answer: The adapted charts give an atlas for $S$ which is compatible with the usual one, so it's enough to check if for adapted charts as you've done. Continuity came into the picture when you said "in some neighbourhood of $\phi(p)$" -- this neighborhood would have to be $f^{-1}(V) \cap U$, and to know this is open you are using the continuity of $f$. But this doesn't need to be assumed, as either of the hypotheses (smooth as a map into $S$ or into $N$) imply the continuity (note that, since $S$ is embedded, it has the subspace topology, and hence continuous as a map into $S$ or $N$ are the same thing).


Update ear in web sphere from command line

Question: I have developed an java ear that i deploy from my local eclipse to my local websphere 8.5 by using the publish button in eclipse. When I try to deploy my ear from command line I get an error after I try to access the webpage.
I update my ear from common line like this:
${was.dir}/profiles/${was.profile}/bin/wsadmin.sh -lang jython -username ${was.username} -password ${was.password} -c AdminApplication.updateApplicationUsingDefaultMerge('${was.app.name}', '${build.dir}/${ear.name}')
The deployment is successful but when I access my application thru my web browser I get the following message instead of seeing my application:
Error 404: com.ibm.ws.webcontainer.servlet.exception.NoTargetForURIException: No target servlet configured for uri: /wwww/index.html
I have verified that the ear is ok by updating it thru the web admin interface of websphere without any configuration.
What am I doing wrong or what additional steps do I need to do to successfully update my ear?
Comment: Is there supposed to be four w's in that path? Either way, it is hard to tell based on the description. It looks like it doesn't find the url you are trying to access. What url are you using and what is the configured context root for that web application in the ear that you are trying to access?
Comment: I understand that its not finding the application. What I am looking for is the right way to update an existing ear and it looks like the command AdminApplication.updateApplicationUsingDefaultMerge is not enough. Thanks for taking the time to answer.
Answer: You are using wrong command. You should use something like this:

AdminApp.update('MyAppEAR', 'app', '[ -operation update -contents
  MyApp.ear -nopreCompileJSPs -installed.ear.destination C:\WAS\MyAppEAR
  -nodistributeApp -useMetaDataFromBinary -nodeployejb -createMBeansForResources -noreloadEnabled -nodeployws -validateinstall warn -noprocessEmbeddedConfig -filepermission ..dll=755#..so=755#..a=755#..sl=755
  -noallowDispatchRemoteInclude -noallowServiceRemoteInclude -asyncRequestDispatchType DISABLED -nouseAutoLink -noenableClientModule -clientMode isolated -novalidateSchema -MapModulesToServers [[ MyApp MyApp.war,WEB-INF/web.xml WebSphere:cell=Node02Cell,node=Node02,server=server1 ]]]' )

Also, in WebSphere Application Server you can log every command you issue through Administrative Console.
Steps

login to admin console with administrative user (e.g. wasadmin)
click "System Administration" -> "Console Preferences"
check "Enable command assistance notifications" and "Log command assistance commands"
click Apply button to save changes

You can see commands in help portlet on the upper-right side of admin console:

If you checked "Log command assistance commands", you can also see jython commands in a log file "<WAS_HOME>\profiles\<PROFILE_NAME>\logs\server1\commandAssistanceJythonCommands.log"
Answer: I'm not sure about updateApplicationUsingDefaultMerge vs update (the latter is what I use), but don't forget you also have to AdminConfig.save() after you're finished.


Adding a Button in the Status Bar

Question: I'm developing an android application where I want to add a Phone Button in Status Bar. Can I add a Phone button in Status Bar?

I want to add a button like showing in the above Image. I tried to do with the notification but the notification icon size is too small. How can I do it? Any Idea?
Answer: I think it goes against the design guidelines to put a button in the status bar since it's supposed to contain notification and system icons only. See https://material.io/design/platform-guidance/android-bars.html#status-bar.
Try a heads-up notification instead (https://developer.android.com/guide/topics/ui/notifiers/notifications.html).
You can put the button in the action area of the notification (https://material.io/design/platform-guidance/android-notifications.html#anatomy-of-a-notification).
Comment: thanks for the reply. The system phone app is doing this. How it's working in the System Phone/Calling app?
Comment: @SushilSolanki Try this: https://v4all123.blogspot.com/2018/11/simple-example-of-heads-up-notification.html
Answer: Looks like you need foreground service with notification icon -
here
Sample code for foreground service -
<code>public class ExampleService extends Service {

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String input = intent.getStringExtra("inputExtra");

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Example Service")
            .setContentText(input)
            .setSmallIcon(R.drawable.ic_android)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1, notification);

    //do heavy work on a background thread
    //stopSelf();

    return START_NOT_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
</code>
}

Adding a Button in the Status Bar


Values are not iterated in a HashMap in Java

Question: After initializing a HashMap, the values are inserted. But while trying to print the values, all the values are not printed. I am trying to solve this problem.
The code is as follows:
import java.util.Scanner;
import java.util.HashMap;
import java.util.Iterator;

public class test
{
    public static void main(String args[]) throws Exception
    {
        Scanner input = new Scanner(System.in);
        String inputString = input.next();
        int cases = input.nextInt();
        long max = 0;
        HashMap<Long, Long> points = new HashMap<>();
        while(cases>0)
        {
            points.put(input.nextLong(), input.nextLong());
            cases--;
        }
        Iterator iterator = points.keySet().iterator();
        while(iterator.hasNext())
        {
            long x = (Long)iterator.next();
            long y = points.get(x);
            if(x>max)
                max = x;
            if(y>max)
                max = y;
        }
        while(inputString.length()<=max)
            inputString = inputString.concat(inputString);

        iterator = points.keySet().iterator();
        while(iterator.hasNext())
        {
            long x = (Long)iterator.next();
            long y = points.get(x);
            System.out.println("x: "+x+" y: "+y);
/*          if(inputString.charAt(new Long(x-1).intValue()) == inputString.charAt(new Long(y-1).intValue()))
                System.out.println("Yes");
            else
                System.out.println("No");*/
        }
    }
}

Output:

The values 2 and 4 are not printed. They are not iterated by the HashMap. What is the issue?
Comment: You don't need to store the input to solve that problem. Just examine the input and produce output per input line (and throw away the input).
Comment: Bohemian but I need to find the maximum number of times I need to duplicate and concatenate the string right. So for that purpose. Otherwise it tells time exceeded
Answer: Map can have only one value per key.
If you put value 4 to key 2 and then you put value 5 to the same key you are overwriting the old value. Only the last one (5) remains in the map.
Answer: The root problem is that you are using the wrong data structure. You don't use the fact that it is a map. You only use it as a list of points. The best solution is to replace it with a list of points, as illustrated in the following program:
import java.util.ArrayList;
import java.util.List;

public class Test {
  public static void main(String[] args) {
    List<int[]> points = new ArrayList<int[]>();
    points.add(new int[]{2,4});
    points.add(new int[]{2,5});
    points.add(new int[]{7,14});
    for(int[] point : points){
      int x = point[0];
      int y = point[1];
      System.out.println("x: "+x+" y: "+y);
    }
  }
}

Output:
x: 2 y: 4
x: 2 y: 5
x: 7 y: 14


Reference for inequality on Frobenius/Hilbert-Schmidt matrix norm

Question: It is not hard to see that if ${\bf A}$ is a $d\times d$ matrix with unit determinant, $\det({\bf A})=1,$ then one has an upper bound on the Hilbert-Schmidt (Frobenius) norm of the inverse matrix ${\bf A}^{-1}$ in terms of the Hilbert-Schmidt norm of the matrix itself in the form
$$
\Vert {\bf A}^{-1}\Vert_{\bf{HS}}^2 \leq C_d \Vert {\bf A}\Vert_{\bf{HS}}^{2(d-1)}
$$
For some appropriately chosen constant $C_d.$ I am interested in the best constants.
Obviously $C_2=1$ and I computed that $C_3=\frac{1}{3}$. I believe that the best constant is $C_d=\frac{1}{d^{d-2}}$; one can obviously not do better, as the identity saturates this. I actually only need the case $d=3$, and I don't even really need the best constant, but I am curious, and my calculation for $d=3$ is a bit of a mess.
Does anyone have a reference for this inequality, ideally the best constants, or a slick proof of this?
Update I have done the calculation for all $d$ using Lagrange multipliers with the singular values as coordinates but I would still appreciate either a reference or a slick proof.
Answer: We will start by proving this inequality:

If $n\in \mathbb N$, $x_i\ge 0$, \begin{align}
\frac1n\left(\sum_{k=1}^n \frac1{x_k}\right)\prod_{k=1}^n x_k \le \left(\frac1n\sum_{k=1}^n x_k\right)^{n-1}
\end{align}

I will use induction the inequality is trivial for $n=2$. Assume that the inequality is true for $n$ numbers and denote $s = \frac1n\sum\limits_{k=1}^n x_k$, $p = \prod_{k=1}^n x_k$ and $q = \frac1n\sum\limits_{k=1}^n \frac1{x_k}$ Since the inequality is true then $s^{n-1} \ge pq$. Let $$f(x) = \left(\frac{x + ns}{n+1}\right)^{n} - \frac{px\left(\frac1x + nq\right)}{n+1} = \left(\frac{x + ns}{n+1}\right)^{n} - \frac{p\left(1 + nqx\right)}{n+1}.$$
So $$f'(x) = n \left(\frac{x+ns}{n+1}\right)^{n-1} - \frac{npq}{n+1}$$ and for $x\ge s$,
\begin{align}
f'(x) &\ge n \left(\frac{s+ns}{n+1}\right)^{n-1} - \frac{npq}{n+1}\\
&= ns^{n-1} - \frac{n}{n+1}pq\\
&\ge pq - \frac{n}{n+1}pq\\
&= \frac1{n+1}pq \ge 0.
\end{align}
This proves that $f$ is nondecreasing on $[s, \infty)$ and if we take $x_{n+1} \ge s$ then, $$f\left(x_{n+1}\right) \ge f(s) \ge 0.$$
This ends the proof.
Now back to the original problem and let $\lambda_1,\ldots,\lambda_d$ be the eigenvalues of $\mathbf A^\intercal \mathbf A$
\begin{align}
\left\|\mathbf A^{-1}\right\|^2_{\mathbf{HS}} &= \mathbf {Tr}\left(\left(\mathbf A^{-1}\right)^\intercal\mathbf A^{-1}\right)\\
&= \mathbf {Tr}\left(\left(\mathbf A^\intercal\mathbf A\right)^{-1}\right)\\
&= \sum_{i=1}^d\frac1{\lambda_i}\\
&\le d\frac{1}{\prod\limits_{i=1}^d \lambda_i}\left(\frac1d \sum_{i=1}^d\lambda_i\right)^{d-1}\\
&\le \frac{d}{d^{d-1}} \frac{\mathbf{Tr}\left(\mathbf A^\intercal \mathbf A\right)^{d-1}}{\det\left(\mathbf A^\intercal \mathbf A\right)}\\
&= \frac{1}{d^{d-2}} \left(\left\|\mathbf A\right\|^2_{\mathbf{HS}}\right)^{d-1}
\end{align}


EKCalendarChooser multiple selection does not work

Question: I'm trying to use EKCalendarChooser to get multiple calendars selected by the user. This is how I present the view:
EKCalendarChooser* dvc= [[[EKCalendarChooser alloc] initWithSelectionStyle:EKCalendarChooserSelectionStyleMultiple displayStyle:EKCalendarChooserDisplayAllCalendars eventStore:eventStore] autorelease];

dvc.selectedCalendars= self.selectedCalendars;
dvc.delegate= self;
dvc.contentSizeForViewInPopover= CGSizeMake(320.0, 480.0);

self.popOver= [[UIPopoverController alloc] initWithContentViewController:dvc];
[self.popOver release];
self.popOver.delegate= self;

UIBarButtonItem* item= sender;

[self.popOver presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

I get the calendarChooserSelectionDidChange message once I select one or more calendars, but every time the selectedCalendars property of the EKCalendarChooser is empty!
- (void)calendarChooserSelectionDidChange:(EKCalendarChooser *)calendarChooser
{
   NSLog(@"selected %d calendars", calendarChooser.selectedCalendars.count);
}

2012-02-26 12:50:39.137 MyApp[8604:707] selected 0 calendars
2012-02-26 12:50:42.100 MyApp[8604:707] selected 0 calendars

When I use EKCalendarChooserSelectionStyleSingle instead of EKCalendarChooserSelectionStyleMultiple, everything works fine and I will get the correct selected calendar through the selectedCalendars property.
Am I doing anything wrong, or is this a bug in EKCalendarChooser?
Answer: If your self.selectedCalendars are nil you have to initialize the dvc.selectedCalendars with an valid but empty set.
dvc.selectedCalendars = [[NSSet alloc] init];

Comment: 2015, still need to alloc init the `selectedCalendars` in order for the multiple selection style to work properly.
Comment: Are you sure about this? I don't have to do this in single selection mode. Will try when at home though.
Comment: I did this, but it did help. I wasn't initializing the NSSet variable earlier. Either way, using the multiple selection feature still doesn't work for me. I output the selected calendars at the instance they are selected, but when selected, null null null 0 0 0 pops up everywhere, I am doing alot of checks to see where they data is but NOTHING is being referenced. I feel like apple just forgot to implement the EKCalendarChooserSelectionStyleMultiple type or something. Because it clearly isn't returning any clicked cells.