Proof that convergent sequence in $\Bbb R$ is bounded.

Question: Convergent sequence in $\Bbb R$ is bounded. Proof:

In the definition of a convergent sequence:
$$(\forall \varepsilon>0), (\exists n_\varepsilon\in\Bbb N), (\forall n\in\Bbb N), ((n>n_\varepsilon)\Rightarrow(|a_n-a|<\varepsilon))$$
  let $\varepsilon=1$, then there exists $n_\varepsilon\in\Bbb N$ such
  that $(n>n_\varepsilon)\Rightarrow(|a_n-a|<1$). Now for
  $n>n_\varepsilon$ we have $|a_n|\leq|a_n-a|+|a|\leq 1+|a|$. Let
  $M=\max\{|a_1|,...,|a_{n_\varepsilon}|,1+|a|\}$ Then $\forall n\in\Bbb
> N, \ |a_n|\leq M$, i.e. the sequence is bounded.

What's the idea behind this proof? I understand the first part, but then when they define $M$ I'm lost. I don't see how is that related to the first part of the proof.
Comment: @ΘΣΦGenSan No problem, I always tend to upvote all the answers I get to show that I appreciate them.
Comment: In $|_| ≤ |_ − | + || ≤ 1+ ||$ there should probably be just $<$ there in the last inequality, because otherwise it'd imply $|_ − | ≤ 1 = \varepsilon$ which'd be a contradiction as $a_n \rightarrow a$.
Answer: The idea behind this proof is to separate the values of the sequence into 2 parts : the ones that are close to the limit (within distance 1 of it) and the ones that are "far" from the limit.
By definition of convergent sequences, those last ones are in finite number, so the set of their absolute values is bounded, by a real $M$. And the set of the others is bounded by $|l|+1$.
So the whole set of absolute values is bounded by $\max(|l|+1,M)$.
Answer: The idea is that after a while (i.e., after $n_\epsilon$), the sequence is bounded by $1+|a|$, and before that, the sequence is finite so it is bounded by the largest element.
What you do is you split the sequence into two parts, a starting part and "the rest"

The starting part, $a_1,a_2,\dots, a_{n_\epsilon}$, is clearly bounded by $M_1=\max\{a_1,a_2,\dots, a_{n_\epsilon}\}$. It's bounded by $M_1$ because $M_1$ is the largest element of a finite set, and so it must be larger than all elements of that set.
The rest of the sequence, $a_{n_\epsilon+1}, a_{n_\epsilon+2},\dots$, is infinite, so we can't just take its max. However, we know and can show that this part must be bounded by $M_2=1+|a|$.

Now, the first part of the sequence is bounded by $M_1$, and the second by $M_2$, so both together must be bounded by $\max\{M_1,M_2\}$, since $M\geq M_1, M_2$.

For example, you need to define $M$ because $1+|a|$ may not be the upper limit of the entire sequence. For example, the sequence $\frac2n$ has a limit of $0$, but the sequence is not bounded by $1+|0|$ since $2$ is also a part of the sequence.
However, the sequence is bounded by $\max\{2, 0+1\}=2$.
Comment: Thanks so much, I wouldn't have ever figured it out by myself.
Comment: @Lewis You're very welcome. The method of splitting the sequence into a finite and convergent part is actually quite common, as intuitively, anything that's finite shouldn't cause too much problems, so you start to only think about $a_n$ for large values of $n$, and then mop up the first couple of values (even if, of course, that might mean billions of values -- if it's finite, it's fine).
Answer: We want some $M>0$ so that $|a_n|\leq M$ for all $n\in\Bbb N$ and if this happens, we say that the sequence $(a_n)$ is bounded. Now, you already mentioned that
$$|a_n|<1+|a|\quad\text{for  }n=n_{\epsilon}+1,n_{\epsilon}+2,n_{\epsilon}+3,\dots.\tag{$*$}$$
What we gonna do to the numbers $|a_1|,|a_2|,|a_3|\dots,|a_{n_{\epsilon}}|$? This give an idea of  taking
$$M=\max\{|a_1|,...,|a_{n_\varepsilon}|,1+|a|\}.$$ So, using the definition of our $M$ together with $(*)$, we get
$$\begin{align}
&|a_1|\leq M\\
&|a_2|\leq M\\
&|a_3|\leq M\\
&\quad\vdots\\
&|a_{n_{\epsilon}}|\leq M\\
&|a_{n_{\epsilon}+1}|< 1+|a|\leq M\\
&|a_{n_{\epsilon}+2}|< 1+|a|\leq M\\
&|a_{n_{\epsilon}+3}|< 1+|a|\leq M\\
&\quad\vdots\\
\end{align}$$
With the above, we conclude that $|a_n|\leq M$ for all $n\in\Bbb N$.
Answer: See the main idea is that ,, by the convergence  property , you get a bound of an infinite part of the sequence  i.e of all the $x_n$'s after some stage.
Now then the bound becomes easy to define , just take the maximum of all the $x_n$'s before that particular $N_0$  with the bound you have got for the infinite part. Hence the bound of the sequence gets defined.


Do we have any better/richer framework for understanding rhythm and timbre?

Question: A large chunk of music has been made in the last 50+ years that largely cannot be analysed (in any meaningful way) via notes, focused instead on variations on repetition/timbre/rhythm/dynamics/etc.  Hence my distinction of "notes" below.
From my relatively layman point of view, the fundamentals of western music theory seem to focus mainly on notes. Pitch, scales, melody, chords, modes, consonance, and many other things are frameworks to understand notes.  However it seems very limited by comparison in terms of understanding rhythm or timbre.
I appreciate that timbre is somewhat problematic and abstract, especially if the instruments or timbres are themselves abstract (i.e. electronic music).
We have stuff like meter, syncopation, and swing for rhythm, but there doesn't seem to be much underlying it. By which I mean that we don't seem to have anything comparative to keys, melody, harmony, etc.  For rhythm, we seem to do little more than define intervals, and name styles.  There seems to be no understanding as deep as the circle of fifths.
Do we have any better/richer frameworks for a deeper understanding of rhythm and timbre? Particularly rhythm, and how certain rhythmic intervals sound good together.
Comment: I wonder if your personal knowledge of rhythm is lacking in areas that the general body of knowledge and theory on rhythm is not. There's plenty of analysis of rhythm in the world, it's just not as famous/popular as tonal analysis.
Comment: I always just got away with. "It goes, a bom ana chack, and boom chicka chack" which works just fine so long as you never have to write it down;)
Comment: Given even simple  quavers in one bar of 4/4, if my calculations are correct, there are over 40,000 ways they could be played. If that's so, there's a lot of research needed.
Comment: @ToddWilcox I thought that might be the case. I pretty much know the fundamentals. Do you have any examples of deeper theory on rhythm?
Comment: The circle of fifths is not a "deep" concept. Anyone should be able to discover the circle of fifths ater noticing that a G7 leads to C and C7 leads to F.
Comment: @piiperiReinstateMonica  I don't know the term.  I didn't mean it wasn't basic.  Basic theory of notes often reveals a deeper understanding of notes.  Basic theory of rhythm seems to consist of little more than a description of placement.  Rather than a "deeper" explanation of placement.
Answer: There is a huge amount of stuff written about rhythm. William Rothstein's "Phrase Rhythm in Tonal Music" is one. A quick check on Google Scholar turns up quite a few papers on the subject. There is probably a lot also in dissertations which could be found in a dissertation index.


In how many ways can $3$ boys and $4$ girls be seated under the following conditions?

Question: Having an issue with a permutation question.

$3$ boys $4$ girls need to sit down in a row

(a) How many ways can you arrange them if there are no restrictions?

$7! = 5040$.     I think anyway!

(b) How many ways can you arrange them if the girls have to sit together?

$(4 \times 3 \times 2 \times 1) \times3 \times2 \times 1 = 144$ permutations. Not sure on this one. Do i count the boys as a seperate entity and only allow one permutation?

(c) How many ways can you arrange them if no two girls can sit beside each other?

My thoughts on this are
$4\times3\times3\times2\times2\times1\times1$
I have put the numbers that i think represent the girls in italics
Thanks for any help!
Comment: sitting on a linear bench, or around a circular table? do you distinguish only between boys and girls, or also between each boy and each girl ?
Comment: That is actually a fantastic question. I assume a linear bench but its definately worth asking! Thanks for the input
Answer: I'm assuming by your answers that you are arranging these people side-by-side instead of circularly, and that you distinguish between different boys and girls.
How many ways can you arrange them with no restrictions?
You're correct, there are $7!$ ways to arrange them.
How many ways can you arrange them if the girls have to sit next to each other?
Then we can treat all the girls as though they are one entity, so there are $4!$ ways - three boys, and one "girl". The "girl", however, can be arranged in $4!$ ways. Thus there are $4! * 4! = 2 * 4!$ ways to arrange them.
How many ways can you arrange them if no two girls can sit beside each other?
There are four girls and three boys, so necessarily the arrangement looks like:
$$YXYXYXY$$
Where $X$ is a boy and $Y$ is a girl. There are $3!$ ways to arrange the boys, and $4!$ ways to arrange the girls, so the total number of arrangements is $3! * 4!$.
Comment: see my question above
Comment: Thanks for the taking the time to help. I can see where I was going wrong now! Much appreciated!
Comment: Hi Just another quick question on this, If there are 3 girls, 4 boys and the girls have to sit beside eachother would I be right in saying.                   GBBBB = 5!                                                                                3! for the different way the girls can be arranged.                                    5! * 3! = 720 arrangements. Thanks
Comment: In the second question, $4!4! = (4!)^2$, not $2 \cdot 4!$.


Capture sub-directories from path

Question: my $path= "/tmp/main/store/important/file/log"; ##string

$path =~ m/file/;

print "$&/$'\n";

I want to capture file/log/.*/.*/ .. . . ..
And the path may vary, any other way to solve this?
Thanks guys
Answer: Just use greedy matching (.*):
my $path= "/tmp/main/store/important/file/log";
my ($tail) = $path =~ m!(/file/.*)!;
print $tail;  # /file/log

Here I also use a custom delimiter for the m// operator to avoid escaping slashes.

Capture sub-directories from path


additional Social icons in ShareThis module

Question: I am using ShareThis module for social icons. Can anybody please tell me how to add a new social icon not provided by this module? Flickr,Feed and Email icons are not present in the list.
Answer: You can do this by using Social Media Links Block module.

The modules provides a configurable block that display links (icons)
  to your profiles on various popular networking sites.

For Flicker, use Flicker module.
Comment: Thanku @NishantP, but `flickr` is not there


How to fix validation errors Response in Netcore 2.2 Web API

Question: I'm handling asp.netcore-2.2 errors but I'm still getting ErrorMessage details from Response
I have a login and register methods with a required username, password and a required password length for registration between 8 and 4 characters the problem is that I get the error messages expected or handled for the login method and I get validation error when I register with empty username and password.
I added this code in ConfigureApiBehaviorOptions:
options.SuppressModelStateInvalidFilter = true;

and this I tried this option too:
options.SuppressUseValidationProblemDetailsForInvalidModelStateResponses = true;

but it doesn't work.
This is my Register DTO:
using System.ComponentModel.DataAnnotations;

namespace DatingApp.Api.Dtos
{
    public class UserForRegisterDto
    {
        [Required]
        public string Username { get; set; }
        [Required]
        [StringLength(8, MinimumLength= 4, ErrorMessage= "password between 4 and 8 charracters")]
        public string Password { get; set; }
    }
}

I expected this error message:

"password between 4 and 8 charracters"

but I get this before I change ConfigureApiBehaviorOptions:

"title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "0HLJIO56EGJEV:00000001"

and a full table with error detail if I use ConfigureApiBehaviorOptions.
Answer:   public class UserForRegisterDto
    {
        [Required(ErrorMessage = "username is required")]
        public string Username { get; set; }
        [Required(ErrorMessage = "password is required")]
        [StringLength(8, MinimumLength= 4, ErrorMessage= "password between 4 and 8 charracters")]
        public string Password { get; set; }
    }

i just add error message for required fields .
Comment: Annotations do not make "One or more validation errors occurred." go away. However, the response have errors field as given below

{
    "errors": {
        "Username": [
            "username is required"
        ]},
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "0HM4INHKS81G6:00000001"
}


Multivariate nonparametric divergence (or distance) between distributions

Question: For example, we could say I have two fruit classes (oranges and apples) and for each one I measured different statistics of interest, for example: width, height, sugar, water... of a lot of fruit units. Therefore, for each of the statistics I have a probability distribution based on the, let's say, 100,000 different fruits measured.
<code>           Width    Height  Sugar
Apple       X1       Y1      Z1
Orange      X2       Y2      Z2
</code>
In this case, the distributions are probably normal distributed, but in my case they are not. I don't know the type of distribution.
I would like to compare them in order to see «how similar» they are. I searched and I found a lot of tests for checking the divergence (or distance) between distributions (Kullback-Leibler, Kolmogorov-Smirnov, Hellinger, Jensen-Shannon...). The problem is that with them I can only compare two distributions (for example apple and orange width). It would be better to take all the statistics of interest together for the comparison.
Therefore, I would like to know a Multivariate nonparametric technique for comparing the divergences/distances between the distributions that gives a number. For example, DIST(X1,Y1,Z1 | X2,Y2,Z2) = value between [0,1], meaning that there is no divergence or there is a lot, respectively.
Answer: Multi-response Permutation Procedures (MRPP) is one possibility, with the two groups being apples and oranges. Note that both the degree of overlap and overall within-group variation matter for the final difference between groups, so it is possible to have two groups that overlap completely be different if they differ in within-group distance. So best to use an ordination technique such as NMDS to visualize the results. Significance value is obtained via permutation.
Check the documentation of this R package.
Comment: I have added the latest active site. Check your post after the edit when you visit again here.


How to use two pages of a View with the same path depending on users's profile?

Question: I created a View on a custom Content Entity.
I'd like to have 2 pages:

the first with all the fields from my entity, no filters, accessible
by users with Edit rights on the entity,
the second one with some of
the fields, filtered by one criteria, accessible by users with View
rights on the entity.

And, of course, with the same path, e.g. [mysite]/myEntity.
How do I do that?
I use Drupal 8.3.4.
Answer: In Drupal 7 this was quite easy to implement just using Views. In D8 I couldn't manage to implement it only with Views.
You can create a panel page with two different variants. Place the relevant block in each variant and control the accessibility though the 'Page access'. (I used roles but you can even create your custom condition)


DataTables nested table with collapse : how remove padding?

Question: I created a demo to play with Datatables to have child row with Collapse/Expands. I'm not able to align the nested table within the parent.  I'll  like to have the same columns width.
You can see the JSFiddle here   enter link description here
I try to add this but it didn't work.
<code>.childtable.dataTable tbody th, .childtable.dataTable tbody td {
    padding: 0;
}
</code>
Comment: It is a real challenge since you are using a dataTable inside a dataTable, and the inline dataTable is a clone of another hidden . There is so many aspects where any attempt to alignment is overruled by dataTable or injected styles.  **If** you really want dataTabled' rows as child rows, why not just add / remove those rows to the dataTable, below their "parent", instead of injecting a child table? It is really easy and would give you the desired layout right away.
Comment: That is what I was doing before, but the problem was the sorting done by Datatables.  My children rows were sorted too, and this isn't desired.  I try to make it works like this example : https://www.datatables.net/examples/api/row_details.html   but you have to create the row by hand instead of using the json array received from ajax.
Comment: Then you must go the hard way, programmatically update the child columns to have the same width as their "parent" columns, and you must do a lot of CSS to prevent the inner dataTable to be styled the same way as the outer.
Comment: I did a demo here https://jsfiddle.net/survivant/811b41kL/2/   it works
Answer: The best approach to your problem is using a combination of selectors (+ and >):
<code>// For remove padding of nested table-cell
table.dataTable tbody tr.shown + tr > td {
    padding: 0;
}

// For set the width of first column
table.dataTable tbody tr.shown + tr table.dataTable tbody td.sorting_1,
td.details-control {
    width: 40px;
}
</code>
http://jsfiddle.net/alexndreazevedo/jpnr2e6c
Unfortunately, is only possible align nested columns setting a fixed percentual for each column. However it probably couldn't be readable with fluid text.
A workaround is change your markup. Depends of you!
Comment: thanks for the help.  I did some progress too.  here a more complete with javascript example : https://jsfiddle.net/survivant/qxfhh024/2/


Interpret interaction effect of 2 continuous variables

Question: My dependent variable is house prices. And my interaction term contains two continuous variables 1) log of employment at the nearest firm 2) log of distance to the nearest firm.
House price = b0 + b1 lemployment + b2 lnrdistance +
-0.0014 (lemployment*lnrdistance)
I am confused on how to interpret this interaction coefficient and what it means for the relationship between employment/distance and price. Any help is greatly appreciated.
I have seen previous posts about similar topics, but I still cannot solve my problem
Comment: This appears to be an exact duplicate of the (unanswered) question at http://stats.stackexchange.com/questions/143256/how-does-one-interpret-a-demeaned-log-interaction-term.
Answer: The way to interpret the coefficient is to think of cross partial derivatives.
So, to answer your question, you can think of the marginal effect of employment on house price as depending on distance.
The effect of log of employment on nearest firm on houseprice depends negatively on distance.
So for a given increase in log of employment in the nearest firm, the effect depends negatively on distance- ie. the effect will be lesser if the closest firm is farther away.
Comment: Thank you! That makes so much sense! You are my saviour.


What scales and or modes are used in rebetiko?

Question: What scales and / or modes are traditionally used in rebetiko music?
Answer: They quite often use the western major and minor scales we all use, but since it is strongly influenced by eastern civilizations, mainly from Turkey, they use eastern-inspired scales from their traditional music. Some examples are Makam, and from what I see on a quick search, among other scales they also use the phrygian dominant scale, which is called 'hijaz' in Arab and the Persian scale Rast


An exposed filter works only with certain taxonomy terms (weird to me)

Question: I have a "commercial property" and "residencial property" node types.
One for offices, cellars, etc and the other to houses, apartments, etc
They share some fields (price, address, etc) and also a field that I called "Kind of property" that is a taxonomy dictionary:
Kind of property:

Office
Cellar
House
Apartment
Estate

I have a View that works like a "Property search" and I have exposed the field "Kind of property". I created a menu for each one, so the visitor can go to "Sales - Apartments" and the View will show all the available apartments that are on sale.
This is the example URL for Apartments on sale: http://www.asir.com.co/inmuebles/buscar?asignacion[]=Venta&field_tipo_de_inmueble_tid=18
See that "asignacion" is a field that I use to mark the property if it is for sale or for rent (in this case Venta means Sale)
And also see that "field_tipo_de_inmueble_tid" point to the taxonomy term that is on the field "Kind of property".
The issue that I'm having is that field_tipo_de_inmueble_tid=18 works good, and also field_tipo_de_inmueble_tid=19 workds good, but if field_tipo_de_inmueble_tid=20 then it dosen't work and the view result is empty. (18 = Apartments, 19 = Houses, 20 = Estates, wich are the taxonomy terms).
I checked the nodes and there are nodes created that are using the termin id 20, but the View is not showing them so don't know how to troubleshoot this, any idea?
Thanks a lot for your time!
Comment: add what you found out as an answer, and then once permitted, mark it as accepted - that way it doesn't show up as unanswered, but is still available to the community if someone searches for a similar problem.
Comment: does the view filter by content type, and if so, are Estates of the same content type as apartments and houses?
Comment: I have a "commercial property" and "residencial property" content types and both are included in the View filters. Weird is that Estates are in the "residencial property" content type; houses and apartments as well and those shows without a problem.
Comment: Have you added any relationship, if you have DB access then try to execute the view query manually in the DB.
Comment: Yes, there is a relationship in the View (field_tipo_de_inmueble_tid).

When try to execute the view query in the DB I get error: ` #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '} node LEFT JOIN {field_data_field_tipo_de_inmueble} field_data_field_tipo_de_i' at line 3`
Comment: Found my mistake !!

I rechecked every value on the View filters, and the city filter had a value on it, so I left empty the city and now the property is showing ok, because that property is not on the city that was the default.

Thanks to all for the help and sorry to waste your time.

PS: How do I should to mark this question? Do I have to erase it? post my own solution?
Answer: Found my mistake. I rechecked every value on the View filters, and the city filter had a value on it, so I left empty the city and now the property is showing ok, because that property is not on the city that was the default.


BorderBrush in wpf doesn't work

Question: I am trying to replace this default border color in a groupbox but it doesn't work.

here code snippet:
<GroupBox x:Name="groupBox" BorderBrush="Red" BorderThickness="5" HorizontalAlignment="Center" Height="278" Margin="107,74,33,0" VerticalAlignment="Top" Width="760">
  <GroupBox.Header>
    <Border  Background="#FFDAD5D5" BorderBrush="#FFDAD5D5" BorderThickness="56">
      <TextBlock Text="Installation data" />
    </Border>
 </GroupBox.Header>

Comment: Have you set the border brush of the group header instead?
Comment: It doesn't work even if I run the app
Comment: It works just fine for me. Make sure that you set the BorderBrush property of the correct GroupBox.
Answer: Try to use Style definitions, like this: How to use style for GroupBox header?.
You can avoid, that any other style will override yours.
Besides your code gets a cleaner structure and you can re-use this style for other GroupBoxes.

Use it as follow:
<GroupBox x:Name="groupBox"
          Style="{StaticResource MyGroupeBoxStyle}"
          Header="Installation data" />

Comment: Note that I changed the `TextBox` element to `Label`, because it has led to problems in the solution of the link.
Answer: i think GroupBox is inside another control which overlays your Border.
Maybe you can try to place your GroupBox to the front - just to try
Let me know whats happening.
Greedings

BorderBrush in wpf doesn't work


Erro: undefined depois de uma requisição ajax dentro de outra

Question: Segue o código:
$("#l_linha").change(function(){
    var linha = $(this).val();
    var dados = $("#l_linha").serialize();
            $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'buscarPonto.php',
            async: true,
            data: dados,
            success: function (response) {
                console.log(response);

                for(i = 0; i < response.length; i++){
                var localizacao = new Array(response.length);

                localizacao[i] = L.latLng(response[i].lat, response[i].lng);

                console.log(localizacao[i]);

                $("#r_ponto").val(response[i].id);
                var ponto = new Array();
                ponto[i] = $("#r_ponto").serialize();
                var address = new Array();
                address[i]= response[i].address;
                var ultimo = new Array();
                var proximo = new Array();

                $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'buscarHorario.php',
                async: true,
                data: ponto[i],
                success: function (response) {
                        console.log(localizacao[i]);
                    for(j = 0; j < response.length; j++){
                        ultimo[j] = response.ultimo;
                        proximo[j] = response.proximo;
                    }
                }
                });
                L.marker(localizacao[i], {icon: icone}).addTo(map).bindPopup(address[i] +'
Próximo horário:'+ ultimo[j] +'').openPopup();
            }
        });
});

O problema é que a variável ultimo[j] fica undefined. E se eu passo a parte:
L.marker(localizacao[i], {icon: icone}).addTo(map).bindPopup(address[i] +'
Próximo horário:'+ ultimo[j] +'').openPopup();

para dentro do for(j = 0; j < response.length; j++)... a variável localização fica undefined. Esse trecho de código tem o objetivo de fazer 2 requisições ajax uma para listar os pontos dos marcadores e outra para listar os horários específicos destes marcadores, a parte do back-end está ok só essa ai que não.
Comment: Utilize o `L.marker(localizacao[i]...` dentro de `complete: function (data) {     }` para garantir que a variável `ultimo` tenha um valor vindo do success.
Comment: success: function (response) {
                        console.log(localizacao[i]);
                    for(j = 0; j < response.length; j++){
                        ultimo[j] = response.ultimo;
                        proximo[j] = response.proximo;
                    }
                },
                complete: function(){
                  L.marker(localizacao[i], {icon: icone}).addTo(map).bindPopup(address[i] +'Próximo horário:'+ ultimo[j] +'').openPopup();
                }     - - Aparece erro de syntax
Answer: Sim, a segunda requisição ela vai ficar com dados undefined nesse código:
$("#l_linha").change(function(){
    var linha = $(this).val();
    var dados = $("#l_linha").serialize();
            $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'buscarPonto.php',
            async: true,
            data: dados,
            success: function (response) {
                console.log(response);

                for(i = 0; i < response.length; i++){
                var localizacao = new Array(response.length);

                localizacao[i] = L.latLng(response[i].lat, response[i].lng);

                console.log(localizacao[i]);

                $("#r_ponto").val(response[i].id);
                var ponto = new Array();
                ponto[i] = $("#r_ponto").serialize();
                var address = new Array();
                address[i]= response[i].address;
                var ultimo = new Array();
                var proximo = new Array();

                $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'buscarHorario.php',
                async: true,
                data: ponto[i],
                success: function (response) {
                        console.log(localizacao[i]);
                    for(j = 0; j < response.length; j++){
                        ultimo[j] = response.ultimo;
                        proximo[j] = response.proximo;
                    }
                }
                });
                L.marker(localizacao[i], {icon: icone}).addTo(map).bindPopup(address[i] +'
Próximo horário:'+ ultimo[j] +'').openPopup();
            }
        });
});

Pois, o "sucess" é quando houver sucesso na requisição, então a segunda continua sem esperar a primeira, pois o Ajax é assincrono* e por ser assincrono ele acontece simultaneamente com outras requisições.
Para corrigir coloque dentro da clausula complete:
tente isso:
$("#l_linha").change(function(){
    var linha = $(this).val();
    var dados = $("#l_linha").serialize();

            $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'buscarPonto.php',
            async: true,
            data: dados,
            success: function (response) {
                console.log(response);

                for(i = 0; i < response.length; i++){
                var localizacao = new Array(response.length);

                localizacao[i] = L.latLng(response[i].lat, response[i].lng);

                console.log(localizacao[i]);

                $("#r_ponto").val(response[i].id);
                var ponto = new Array();
                ponto[i] = $("#r_ponto").serialize();
                var address = new Array();
                address[i]= response[i].address;
                var ultimo = new Array();
                var proximo = new Array();

            }
        }).done(function() {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'buscarHorario.php',
                async: true,
                data: ponto[i],
                success: function (response) {
                        console.log(localizacao[i]);
                    for(j = 0; j < response.length; j++){
                        ultimo[j] = response.ultimo;
                        proximo[j] = response.proximo;
                    }
                }
                });
                L.marker(localizacao[i], {icon: icone}).addTo(map).bindPopup(address[i] +'
Próximo horário:'+ ultimo[j] +'').openPopup();

        });;
});

Na documentação do jQuery diz:
"complete faz o callback, quando a requisição finaliza"
Comment: Não funcionou, o erro diz que $ajax(...).complete is not a funciton. Estou usando o jQuery 3.3.1
Comment: usa .done vou alterar na resposta. o complete seria tipo o succes: function, sabe?


Countdown timer in service class

Question: Currently I am creating a Service for countdown timer and I want to run the timer even if the application is destroyed.
If I use  START_NOT_STICKY than it stops the service on Application destroy. and If I use START_STICKY than its restart the service on Application destroy.
Here is my code:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements   View.OnClickListener{
Button btn_testing;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
    listener();

}

private void init(){
    btn_testing = (Button)findViewById(R.id.btn_testing);

}

private void listener(){
    btn_testing.setOnClickListener(this);

}

@Override
public void onClick(View v) {

    switch (v.getId()){

        case R.id.btn_testing:
            startService(new Intent(this, Service_Tesing.class));
            break;
    }

}

}
Here is my Service class:
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

public class Service_Tesing extends Service {

@Override
public void onCreate() {
    super.onCreate();
    CountDownTimer countDownTimer = new CountDownTimer(30000,1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            Log.e("Timer", millisUntilFinished+"");
        }

        @Override
        public void onFinish() {
            Log.e("Finish","Finish");

        }
    }.start();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    stopSelf();
    return START_STICKY;

//        return Service.START_STICKY_COMPATIBILITY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

}
Comment: `I want to run the timer even if the application is destory` then run it in separate process
Answer: To solve this problem I had use the TimerTask in service. Here you can find the demo of Android Countdown Timer Run In Background
Thanks

Countdown timer in service class


Exibir produtos de várias categorias

Question: Essa é minha primeira postagem, estou tentando resolver um problema há algum tempo já, porém sem sucesso.
Tenho a tabela CATEGORIAS e a tabela PRODUTOS
Preciso exibir da seguinte maneis:
CATEGORIA 1
- Produto 1
- Produto 2

CATEGORIA 2
- Produto 1
- Produto 2

Estou fazendo da seguinte maneira (APENAS UM EXEMPLO)
$var = SELECT * FROM categorias INNER JOIN produtos ON categorias.id = produtos.fk_idCategoria

Porém estou perdido ao organizar quando uma categoria possui mais de 1 produto, quando dou print_r($var) exibe o seguinte:
CATEGORIA 1
- Produto 1

CATEGORIA 2
- Produto 1

CATEGORIA 2
- Produto 2

Alguém poderia me dar uma luz ?
Answer: Pra trazer em uma linha só, você pode usar o GROUP_CONCAT  e usar um delimitador para retornar os produtos. o Padrão é vir da maneira que está vindo mesmo, se você tivesse 10 produtos para a mesma categoria, vai retornar 10x a mesma categoria e os produtos diferentes, porém se usar o GROUP_CONCAT você retornar apenas 1 vez a categoria e os produtos separados por um delimitador a sua escolha, não entendi se é isso mesmo que precisa, mas seria assim:
$sql = "SELECT
            c.*,
            p.*,
            GROUP_CONCAT([produto] SEPARATOR ',') AS produtos
        FROM categorias c
        INNER JOIN produtos p ON categorias.id = produtos.fk_idCategoria
        GROUP BY c.id";

Onde [produto] é o nome do campo da sua tabela  produtos e a ',' é o separador que você deseja.
Comment: Olá, primeiramente obrigado. Esqueci de mencionar, eu preciso acessar outras colunas do produto, por exemplo PRODUTO 1, preciso acessar o preço, a descrição etc. Dessa maneira que vc mencionou, eu só consigo retornar uma coluna que seria o [produto], correto ?
Comment: consegue sim, editei a resposta
Comment: Obrigado arrllondias, resolveu meu problema.
Comment: De nada @Jonas.
Answer: Apenas ordenar pela categoria
Se você quer apenas mostrar primeiro todos os dados dos produtos da categoria X e depois da Y e assim por diante, pode fazer um select simples com order by
SELECT * FROM produdo ORDER BY fk_idCategoria

Dividir por categoria
Mas se você quer fazer uma divisão por categoria, por exemplo, criar uma tabela por categoria você pode (além do comando a cima) criar o início de uma tabela e, ao fazer o loop para buscar os dados do banco, verificar se o id da categoria mudou, no caso fecha a tabela atual e abre outra, aqui tem uma resposta que faz isso
Answer: Já tentou ordenar a sua query por Id da categoria?
$var = '
    SELECT *
    FROM categorias
    INNER JOIN produtos ON categorias.id = produtos.fk_idCategoria
    ORDER BY produtos.fk_idCategoria
';

Dessa forma provávelmente o seu print_r retornará algo mais próximo do que você precisa, porém será necessário controlar como exibir os dados com testes lógicos e estruturas de repetições.

Exibir produtos de várias categorias


The body too small even when I use a "clear" div

Question: Take a look at my code and tell why things don't work out please. The blue line should be on the bottom of the page. The body seems to be really small even though I used clear divs. If you find what went wrong please explain the solution. I'm new in coding so an explanation will be really useful to me. Thank you on advance.

    @charset "utf-8";
    /* CSS Document */
    .clear {
     clear:both;
    }

    .wrapper {
     width:80%;
     margin: 0 auto;
    }

    header {
     margin-top:40px;
     border-bottom:1px solid black;
     padding-bottom:10px;
    }

    header img {
     float:left;
     width: 250px;
    }

    #socialmedia {
     float:right;
     padding:0;
     margin-top:-2px;
    }

    #socialmedia li {
     float:left;
     list-style-type:none;
     padding-left:10px;
    }

    li img {
     width:40px;
    }

    #listmenu {
     float:left;
     margin-top:80px;
     margin-right:5px;
    }

    #listmenu li {
     display: block;
     margin-bottom:40px;
     font-family:Arial;
     Font-size: 30px;
     border-right:1px solid black;
    }

    #leftmenu li:first-child {
     color:#3598db;
    }

    #right {
     float:right;
     width:60%;
    }

    #signupline {
     background-color:#3598db;
     height:50px;
     width:auto;
    }

    button {
     float:left;
    }
    <!doctype html>

       <meta charset="utf-8">
       <title>Untitled Document</title>
       <link rel="stylesheet" type="text/css" href="stylesheet.css" />

Home

What's e-friendship

Lanching Day

About Us

Contact

Welcome to e-Freindship

e-Friendship is the new unbelievable website where you can make new friends from all over thr world. Reading is a complex cognitive process of decoding symbols in order to construct or derive meaning (reading comprehension). Reading is a means of language acquisition, of communication, and of sharing information and ideas. Like all languages, it is a complex interaction between the text and the reader which is shaped by the reader's prior knowledge, experiences, attitude, and language community which is culturally and socially situated. The reading process requires continuous practice, development, and refinement. In addition, reading requires creativity and critical analysis. Consumers of literature make ventures with each piece, innately deviating from literal words to create images that make sense to them in the unfamiliar places the texts describe. Because reading is such a complex process, it cannot be controlled or restricted to one or two interpretations. There are no concrete laws in reading, but rather allows readers an escape to produce their own products introspectively. This promotes deep exploration of texts during interpretation.[1] Readers use a variety of reading strategies to assist with decoding (to translate symbols into sounds or visual representations of speech) and comprehension. Readers may use context clues to identify the meaning of unknown words. Readers integrate the words they have read into their existing framework of knowledge or schema (schemata theory).

Take your place and sign up

      <button>Sign Up</button>

Comment: What do you mean with `bottom of the page`? That it should be always on the bottom of the screen or that you just want that it is at last position of the page? Have you tried using `position: absolute; bottom: 0;`? or `position: fixed; bottom: 0`?
Answer: Try move the clear div out of  the right div:

...

Comment: It worked. But why "clear" has to be out of the ... ?
Comment: In fact no float elements surround the `clear` div, so it clears nothing...`clear` doesn't work for parent elements.


PHP cURL randomly timeouts with 100% of body received

Question: We have an app with ~50 front servers with PHP code that make total 15-25k HTTP RPS to GO API servers via nginx with 100ms timeout using guzzle library. From time to time (randomly, few times in a day) we see that 500-10k RPS are failed with curl timeout error in PHP front servers logs. All exceptions inside logs look like:
cURL error 28: Operation timed out after 100 milliseconds with 143 out of 143 bytes received.
The most interesting part is that it's always 100% out of 100% bytes received, there are never 100 of 102 or 0 of 70. So the PHP receives complete body (we're sure about that because when we replay these requests via CLI curl, its size always equals to failed response body size).
When we start to trace these timed out requests inside nginx-access logs we see, that each of that requests is successfully proceeded by upstream services (Go API) in 1ms (average) and returned by nginx without any delay. Nginx access logs:
GET [path] HTTP/1.1" 200 228 "-" [...] request_time: 0.001 upstream_addr: [addr] upstream_response_time: 0.001 upstream_status: 200

nginx is tunned for max clients (millions of connections) as i talked to our dev-ops guys;
99-th percentile of response time in Go service < 1ms;

What can be the problem of 100ms timeout and where to dig to solve it?
UPD:
NGINX configuration related to client connections:
worker_processes        32;
worker_rlimit_nofile    65535;

events {
    worker_connections      32767;
    accept_mutex on;
}

upstream [service] {
    server [main] max_fails=0;
    server [...] backup max_fails=0;
    keepalive 16;
}

location ^~ /[path]/ {
    proxy_pass http://[service]/;
    proxy_http_version 1.1;

    keepalive_timeout 30;
    keepalive_requests 500;

    reset_timedout_connection on;

    proxy_set_header Connection "";
}

GO version 1.13. net/http is used to serve clients. The service has no external dependencies (databases, cache, etc.), it's just calculating hash for incoming request based on input data.
PHP version 7.2.0 uses firstname.lastname@example.com HTTP client
Comment: Why is Nginx involved?
Comment: @Adrian because it's used as proxy + load balancer from public clients to internal go services. Go service is running on 3 instances.
Comment: Given how much is going on, there's a bunch of potential points of failure, from the Go code, to the Nginx configuration, to the PHP code, to whatever is serving PHP (php-fpm in nginx?). It's impossible to say without seeing any of it.
Answer: On your Load balancer you should force close connection when request is finish
backend nodes
  ...
  option forceclose
  ...

By doing this the load balancer will close the connection when it see the response transfered
https://cbonte.github.io/haproxy-dconv/1.7/configuration.html#option%20forceclose
Comment: Why?  This answer doesn't give any justification as to why this is causing the problem.
Comment: We don't have haproxy as balancer, only nginx


Drupal commerce user based percentage discount

Question: I need to have different order total discount rates in % for each customers. The default discount is 10% for all users and it need to be override for certain users too. i.e administrator can set the different discounts such as 12% for user1 and 15% discount for user2 etc on a specific interval (between valid from and to dates). Is it possible using rules or custom module?
Please help.
Answer: Yes, Rajeesh, anything is possible with Rules. : P
In this case, I'd recommend something like a discount percentage field on user profiles that defaults to 10% and is only visible to administrators who can then override the field value on a user-by-user basis. Your product pricing rule can then look for this field to have a value on the order's user (i.e. use commerce-line-item:commerce-order:owner as the token, not the site:current-user) and then apply it as a discount using the appropriate line item action.
Answer: Can you try using commerce discount module which supports dates as well as users... See screenshot below of Create Discount Form..

Provides a user-friendly UI for managing discounts. The discounts are
  exportable entities based on which the discount rules are generated.
Contains two submodules:
commerce_discount_date: Allows limiting discount validity by date,
  requires the Date module. commerce_discount_usage: Allows limiting
  discount validity by number of uses (as of alpha1, still needs work!).
Comment: I tried commerce discount module but using this module we can set one Order discount to one User only. If we have 100 users and different discounts we need to create 100 rules.  But administrator is asking for another form . What he wants is Select user from a list box and add Discount rate, select  Discount dates and Save discount.
Answer: Thanks @Ryan Szrama, the product pricing rule and user account new field 'field_vip_disc_perc' worked for me. Now I can override the discount field integer value of each user and gets it deducted from the order total as discount percentage value. In pricing rule event 'Calculating the sell price of a product' I added the action "Multiply the unit price by some amount" for Data Selector 'commerce_line_item' with the Amount 'field-vip-disc-perc'. To get the discount percentage deducted from order total, I added the PHP evaluation return value, $value = 1-($value/100); return $value; which is applied to the Price component type Discount.


Retrieve transactions from APM using NEST

Question: I have an asp.net core web app application that will write logs using serilog to elasticsearch and also can read the logs from elasticsearch using NEST. I also have it set up where I can use APM for my application. If I wanted to retrieve the transactions that are in APM using NEST or the transactions on a specific date, is this something possible? Any advice/tutorial/documentation on this would be great!
Answer: You'll want to target the apm-*-transaction aliase(s)
In Kibana Dev tools
GET apm-*-transaction/_search
{
  "query": {
    "range": {
      "@timestamp": {
        "gte": "2021-06-04T00:00:00Z",
        "lte": "2021-06-05T00:00:00Z"
      }
    }
  }
}

In NEST (change dynamic to your document type)
var client = new ElasticClient();

var searchResponse = client.Search<dynamic>(s => s
    .Index("apm-*-transaction")
    .Query(q => q
        .DateRange(dr => dr
            .Field("@timestamp")
            .GreaterThanOrEquals("2021-06-04T00:00:00Z")
            .LessThanOrEquals("2021-06-05T00:00:00Z")
        )
    )
);

Comment: Thank you! I appreciate your explanation and help!


Limit results of the entity reference

Question: I have been trying to find the solution to this problem. I am referencing a serial of nodes with entity reference, but I just want to display the latest 3 nodes. Is there any way I can limit the results of the entity reference? I need to have unlimited Number of values but just need to display the last 3 for that case. I am not using views.
I am using Drupal 7
Thanks :)
Answer: You can always use the Views: Filter by an entity reference view option from Entity selection mode and then create a view and set the number of items to 3.
Answer: @junedkazi your point is valid. However, a more flexible solution is to install Display Suite so you can control and limit the number of items on a multiple value field, and works also with entity reference.
There is an extra textfield on the manage display screens to limit the output per field instead of # (to show them all) you can write the number of the items that you would like to display.
I have attached a video that explains better the solution. It is necessary to active the extras that comes with Display Suite in modules administration.
Limiting the number of fields

Limit results of the entity reference


Neural network: finding irrelevant inputs

Question: I am training a neural network and I suspect that some of the inputs might be irrelevant -- they might not have any relationship to the output. How do I identify these inputs so I can get rid of them? (I am assuming that I should get rid of irrelevant inputs, right?)
Example:
set.seed(123)
nr = 1000
nc = 25
xx = as.data.frame(matrix(runif(nr * nc, min=-1, max=1), nrow = nr, ncol = nc))
# y is only a function of V1 - V5
xx = within(xx, y <- V1^2 + V2*V3 + V4^3 + log(V5 + 2))
# But we train using V1 - V25
nn = nnet(y ~ ., size = 5, linout = TRUE, data=xx, MaxNWts = 10e3, maxit=10e3)

Now what? nn$wts has all the weights, and summary(nn) presents the same weights in a more human-readable format. Can these be used for anything? Ideally, a function / package for doing this has already been written -- I just have not been able to find it.
Answer: I am suggesting a general solution for any model that you can also use to neural networks as well. Unfortunately, I am not a R user. So, I cannot ensure that the R functions for R below really work.
You may select features considering the importance of the features for out of sample prediction. In this context, I suggest two very interesting and general methods that you can use:
1) Permutation importance: The permutation feature importance is defined to be the decrease in a model score when a single feature value is randomly shuffled
Solution in R: Permutation importance in R
2) Shap values: It is not an easy concept since it is based in game theory, but it shows the importance of each feature.
Solution in R: Shap values in R


Input which fills all the available height

Question: I want to set the height of my textarea "comment-rdv" so that it occupies the available height of its parent "col-lg-6". Here is my current code :

Title

Text 1

Text 2

Text 3

            Comment :
            <textarea class="form-control" id="commentaire-rdv">Not defined</textarea>

Thank you in advance for your help.
Comment: Could you please add your current CSS and what you've tried so far to your question?
Answer: You can do that by making the container flex and giving the textarea flex-grow:1 (use full page in snippet below or bootply link and view on desktop):

@import url("https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css");

/* CSS used here will be applied after bootstrap.css */
.zone-padding {
  border:1px solid red;
}
/* below 2 styles are to get equal height columns */
.box-content {
  height:320px;
}
.zone-padding {
  display:flex;
  flex-direction:column;
}

/*below styles are to get textarea to fill div*/
.info-rdv.flex {
  flex-grow:1;
  display:flex;
  flex-direction:column;
}
.info-rdv.flex textarea {
  flex-grow:1;
}

Title

Text 1

Text 2

Text 3

            Comment :
            <textarea class="form-control" id="commentaire-rdv">Not defined</textarea>

Example bootply


How to create a sequence of up to 200-500 thousands numbers in just few microseconds

Question: I need to create a sequence of numbers in the shortest amount of time, ideally in the microseconds range. The total length of this sequence is generally in the range of 20-100 thousand numbers, but sometimes I need to create a sequence of 200-300 thousands numbers.
For the moment I have implemented my code in R (just because I know the language fairly well).
Assuming my sequence should start from 1 and end up to 25, with an increment of 0.0001, in R I would do
s <- seq(1, 25, by = 0.0001)

Although blazingly fast, this takes few milliseconds to complete
> library(microbenchmark)
> microbenchmark(seq(1, 25, by = 0.0001))
Unit: milliseconds
                   expr    min      lq     mean median     uq     max neval
 seq(1, 25, by = 1e-04) 1.6098 2.14505 3.741858 2.2324 2.3554 83.8912   100

Here my questions:
1- is it possible to make the sequence generation faster in R? ideally < 0.5 milliseconds?
2- at some point I would need to implement the code in another (faster) language, would any language able to generate such a sequences in less then 100-200 microseconds?
Comment: I believe the answer to both questions is yes, it is possible to make `seq.default` faster. 1) In your use case you only have arguments `from`, `to` and `by`, `seq.default` has more. And if you know in advance that `from < to && by > 0` you will be able to simplify the original code. 2) `seq.default` is written in pure R, take a look at package `Rcpp` for ways of using `C++` from R. Or write a shared lib in C, C++ and load it when needed, for instance, included in a R package.
Answer: Using Rcpp you can improve the speed by ~ 60%. Though, still not "a few" µseconds.
library(Rcpp)
library(microbenchmark)

cppFunction(
  "
  NumericVector cpp_seq(double &from, double &to, double &by){
    int length = abs((to - from) / by);

    NumericVector out(length + 1);
    int pos = 0;

    for (double i = from; i < to; i += by){
      out[pos] = i;
      pos +=1;
    }

    out[length] = to;
    return out;
  }
  "
)

x <- cpp_seq(1, 25, 0.0001)

microbenchmark(
  seq = seq(1, 25, 0.0001),
  cpp_seq = cpp_seq(1, 25, 0.0001),
  times = 1000
)

# Unit: microseconds
#     expr      min        lq     mean   median       uq      max neval
#     seq  2425.694 2630.6595 4262.708 2847.697 3256.618 99978.10  1000
# cpp_seq   670.949  794.6625 1239.710  903.714 1005.736 12892.09  1000

Both vectors are the same, when you account for floating point errors:
x_R <- seq(1, 25, 0.0001)
x_cpp <- cpp_seq(1, 25, 0.0001)

identical(round(x_R, 9), round(x_cpp, 9))
# [1] TRUE

Comment: this will do it for now, thanks. As I said, at some point I will have to move to another language. I guess a language that support concurrency would be a good choice. Not an expert on this topic, but maybe a way to make it faster would be to split the from-to range in chunks and do the operation in parallel on the sub-ranges...
Answer: seq.int() is 30-40% faster..
microbenchmark::microbenchmark(
  seq = seq(1, 25, by = 0.0001),
  seq.int = seq.int(1, 250000, by = 1) / 10000
)

# Unit: milliseconds
#    expr    min      lq     mean median      uq     max neval
#     seq 2.0749 2.16525 3.375812 2.2222 2.31935 95.9553   100
# seq.int 1.3184 1.35860 1.458503 1.3855 1.42940  6.9268   100

Also, beware of the floaring point errors!!
sprintf("%.100f", seq(0,0.01,0.0001) )
  [1] "0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
  [2] "0.0001000000000000000047921736023859295983129413798451423645019531250000000000000000000000000000000000"
  [3] "0.0002000000000000000095843472047718591966258827596902847290039062500000000000000000000000000000000000"
  [4] "0.0003000000000000000279290479632265942200319841504096984863281250000000000000000000000000000000000000"
  [5] "0.0004000000000000000191686944095437183932517655193805694580078125000000000000000000000000000000000000"
  [6] "0.0005000000000000000104083408558608425664715468883514404296875000000000000000000000000000000000000000"
  [7] "0.0006000000000000000558580959264531884400639683008193969726562500000000000000000000000000000000000000"

Comment: I commented this - note also that the 'int' in `seq.int()` means internal not integer so you don't need to use integers and divide, fractional sequences are fine.
Comment: @H1, so i see , hadn't read the comments..... you can add your comment as an answer if you want, so I can delete mine...
I was under the assumption that the deviding would prevent floating point errors.. but this seems to be wrong....
Comment: thanks for pointing out the floating point issue, did not think about it. Fortunately for now I am interested in the first 4 decimals, but this could easily change in the future, and I would have spent a bit of time before realizing it


Core Data constraint with "includesPropertyValues"

Question: I would like to make a more efficient fetch on Core Data entities and I have a query.
I want to delete a large amount of records (millions).
My logic is:

fetch all records for the entity
delete all fetched records.
To improve fetching,

I set the following constraint:
fetch.includesPropertyValues = NO;

My question is: will the relationships (which are kept as properties in the managed objects) also be deleted?
Answer: Yes, if you delete a managed object, the relationship delete rules apply regardless of this flag.
With so many records you might also want to want to process the instances in batches. Use setFetchLimit: to get a subset of the instances, delete those, save changes, and repeat until no more instances are found.


Capybara Unable to find visible field

Question: Ao rodar o comando rake cucumber eu recebo o seguinte erro:
Unable to find visible field "article[text]" that is not disabled (Capybara::ElementNotFound)

Mas o campo está visível
Arquivo de StepDefs.rb:
Given("Eu abro a pagina {string}") do |string|
    visit '/articles'
    expect(page).to have_current_path('/articles')
    expect(page).to have_content(string)
end

When("Eu crio o artigo {string} com o titulo {string}") do |string, string2|
    click_link 'New article'

    fill_in 'article[text]', :with=> string2

    click_button 'submit'
    expect(page).to have_content(string2)
end

Then("Eu vejo que o artigo com o titulo {string} nao foi salvo, pois o titulo do artigo tem menos de {int} caracteres") do |string, int|
    pending # Write code here that turns the phrase above into concrete actions
end

HTML da página:
<!DOCTYPE html>

    <title>Blog</title>
    <meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="dTLPqUV7sBKcQVLEC7llglxP8asnwITQ1QA5xptHlE+sfDBcQjd85659a7Q5Wr6toEpfo/k/PdZEzIpspqcgYg==" />

    <link rel="stylesheet" media="all" href="/assets/articles.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/comments.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/welcome.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/application.self-f0d704deea029cf000697e2c0181ec173a1b474645466ed843eb5ee7bb215794.css?body=1" data-turbolinks-track="reload" />

New article

<form action="/articles" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="OgAVazJworw8k92uuCCf8UurnXh/cMRAR299FEYX0dcLxAew0HL0q/oD7MSTQeh3phhWACcspk5Rqohog9ydaA==" />

    Title

    <input type="text" name="article[title]" />

    Text

    <textarea name="article[text]">
</textarea>

    <input type="submit" name="commit" value="Create Article" data-disable-with="Create Article" />

</form>

Back

Já tentei usar article_text ao invés de article[text], porém sem sucesso
Answer: Cara, isso e um form?
tipo:
 stado

    <input type="text" name="article[sp]" />
    <input type="text" name="article[rj]" />
    <input type="text" name="article[ms]" />
    <input type="text" name="article[pa]" />

Se sim, use:
find('label[for="name_stado"]', visible: false).send_keys('rj')

Caso não funcione dê uma olhada nestes métodos: https://github.com/Vilariano/Automation_Practice/tree/master/features/page
Abs,

Capybara Unable to find visible field


How to prove the uniqueness of the minimal polynomial?

Question: I have here the definition:

Let $T$ be a linear operator on a finite-dimensional vector
  space $V$ over the field $F$. The minimal polynomial for T is the (unique)
  monic generator of the ideal of polynomials over $F$ which annihilate $T$.

I would like to know how to prove the uniqueness of it, how would I start?
Answer: You can start with proving

If $f(T)=g(T)=0$ for some polynomials $f,g$, then $\gcd(f,g)(T)=0$

and then the uniqueness will follow from a simple proof by contradiction.


Change "scale" attribute in CSS "transform"

Question: I have the following div

As you can see, transform contains scale(1). What's the best way to change scale value?
Thank you for your help.
Answer: Sure, using javascript. There are many ways to do it, I'd do it using a regex.
function changeScale(newScale){
    var div = document.getElementById('theID');
    var curTrans = div.style.transform;
    var newScaleString = 'scale(' + newScale + ')';
    var regex = /scale\([0-9|\.]*\)/;
    var newTrans = curTrans.replace(regex, newScaleString);
    div.style.transform = newTrans;
}

Or with less lines:
function changeScale(newScale){
    var div = document.getElementById('theID');
    div.style.transform = div.style.transform.replace(/scale\([0-9|\.]*\)/, 'scale(' + newScale + ')');
}

Comment: @AndiPavllo Great :)
Comment: I've edited it not to repeat the terms "scale(" and ")" manually plus converted it to runnable code.
Answer: You could use a regular expression (assumed you have your div DOM element in a variable 'el' and want to change scale to 2):
el.style.transform.replace(/scale\(\d+\)/, 'scale(2)');

Comment: Unfortunately, unlike [that answer](https://stackoverflow.com/a/36997091/4829915) this one suffers from multiple issues: it doesn't escape string brackets and assumes the scale multiplier is an integer and not floating.
Comment: Thanks for your remark about the brackets, @lwc, I changed that to prevent readers copy&paste wrong code. However, the OP didn't ask for a certain multiplier, but only for replacing the scale.
Comment: Nevertheless, I don't see any advantage.


What are all the solutions to $\sin(x)^{\sin(x)} = 0.7$?

Question: I could only find $x = \sin^{-1}(e^{W(\ln 0.7)}) + 2πk$ and  $x = \left(π -\sin^{-1}(e^{W(\ln 0.7)})\right) + 2πk$ where $k = (-1,0,1,2,3,4,5...)$, $W$ being the lambert $W$ function.
Basically I did:

$\sin(x)^{\sin(x)} = 0.7$
$\sin(x)\ln(\sin(x)) = \ln(0.7)$
$\ln(\sin(x))e^{\ln(\sin(x))} = \ln(0.7)$
$\ln(\sin(x)) = W(\ln(0.7))$
$\sin(x) = e^{W(\ln(0.7))}$

giving the solutions given above.
But the problem is that there are 2 more solutions that I can't find (total of 4 solutions for a $2π$ cycle). I'm just really interested in what I'm doing wrong here, was just learning about the lambert $W$ function.
Comment: Welcome to MSE! You have a good question, but it's a little bit difficult to understand because of the formatting. I recommend checking out the following reference for Mathjax, so that you can learn how to properly format math expressions: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference/5024#5024
Comment: Wolfram alpha gives 4 solutions and explanations.
Comment: Why did someone downvote this question? You should consider leaving feedback for this new user.
Answer: The Lambert W function $W(x)$ is defined as the inverse function of $f(x) = xe^x$. However, notice that this function is not actually injective, so it doesn't have an inverse. That is, for some values of $W$, there exist $2$ solutions to the equation
$$xe^x = W$$
For example, if $W = -\ln 2 / 2$, then $x$ could be either $x=-\ln 2$ or $x=-2\ln 2$.
In your solution, you find  yourself with the following equation:
$$\ln(\sin x) e^{\ln(\sin x)} = \ln (0.7)$$
From this, you cannot validly deduce that
$$\ln(\sin x) = W(\ln(0.7))$$
because there are actually two values of $y$ solving the equation $ye^y = \ln(0.7)$, and they are $y\approx -0.77$ and $y\approx -1.27$.
Answer: There are two branches of the $W$ function that have real values, the $0$ branch and the $-1$ branch.  Wikipedia has a plot of these together.  (Exactly the same thing happens with $x^2 = 4$.  The square root function gets the solution $x = 2$, but you have to know another solution is given by the "other branch" of the square root function, $x = -2$.)
Additionally, $\sin(x) = U$ has two solution families
$$  x \in \{ \arcsin(U) + 2\pi k : k \in \Bbb{Z} \} $$
and
$$  x \in \{ \pi - \arcsin(U) + 2\pi k : k \in \Bbb{Z} \}  \text{.}  $$
So, in the interval $[0,2\pi]$, the four solutions are \begin{align*}
\arcsin \left( \mathrm{e}^{W_0(\ln 0.7)} \right) &= 0.4806{\dots}  \\
\pi - \arcsin \left( \mathrm{e}^{W_0(\ln 0.7)} \right) &= 2.6609{\dots}  \\
\arcsin \left( \mathrm{e}^{W_{-1}(\ln 0.7)} \right) &= 0.2847{\dots}  \\
\pi - \arcsin \left( \mathrm{e}^{W_{-1}(\ln 0.7)} \right) &= 2.8568{\dots}
\end{align*}
This is all four solutions in the first period of sine.

(The plot does not cover $(\pi, 2\pi)$ because noninteger powers of negative numbers are only rarely real.  Over most of this interval, $\sin^{\sin x}x$ is complex and not real.)


Logistic Regression and Normality Testing?

Question: I am a bit confused regarding normality testing for predictor variables in logistic regression.
Example - If I am looking at an older population, and two of the predictors are continuous, fasting blood glucose and high blood pressure, inherently as the population gets older, both endpoints tend to skew to the right. However, if I intend on stratifying each on three levels (high/pre/normal bp and hi/pre/normal diabetes), is it necessary to transform these variables to have a more normal distribution?
I am not sure if this is to improve the linearity of the logIT between the dependent and independent variable.
Comment: No linear or generalized linear model makes any assumptions about the distribution of the *predictor* variables.
Comment: Do you mean that you will make blood pressure categorical rather than continuous? Isn't that just gratuitously discarding relevant information?
Comment: Logistic regression does not require residuals to follow a Normal distribution so testing for normality is not needed like it is in Linear regression. Normalizing your data may help if your data sees a wide variation in measurements (e.g. age ranges 0-80, income ranges 10000-90000)
Comment: From what I have been reading, normality testing is not needed, however, other studies have mentioned normalizing data, but I think this is because the data points are so small that a transformation is needed.
Comment: @Jon, I do have some data points with wide variations, biomarkers, which I tend on normalizing first.
Comment: I don't think it is discarding information. Categorizing as high blood pressure, borderline, normal captures the relevant information.
Comment: I'm with @MichaelHardy that binning this way loses information. // If you're going to bin, why care what the original distribution looks like?
Answer: Having normally distributed predictor variables is not an assumption of logistic regression. Use the predictors as they are, without stratifying them (turning them into categories).
Answer: If normality is an assumption of your analysis (which as @Matthew Drury has pointed out is not true of linear or general linear models), then you should test for normality with by looking at a QQ-Plot, judging skew and kurtosis, and choosing a test of normality. In order of liberal to conservative tests of normality, you can choose from: Kolmogorov-Smirnov, Kolmogorov-Smirnov with Lilliefors correction, or Shapiro-Wilk. If the ocular test, skew, kurtosis, and statistical significance of the tests point to deviation from normality AND your analysis assumes normality, then a transformation can be applied.
"Traditional" transformations include: square root, log, inversion, reflection, and trigonometric. However, the Box-Cox series of transformations has two advantages over the others: 1) you can fine tune your transformations and 2) it applies easily to positively and negatively skewed distributions (whereas other transformations require a reflection and then a transformation for negatively skewed data).
Most transformations are based on raising data to a power and are thus power transformations. For example, a square root transformation is $x^{1/2}$. Why not use $x^{0.9}$? There's a continuum of transformations that lead to the best transformation. Box and Cox showed that there is a continuum of transformations:
$$y_i^\lambda=(y_i^\lambda-1)/\lambda, \lambda\neq0$$
$$y_i^\lambda=\log_e y_i, \lambda=0$$
Discovery of the $\lambda$, or the Box-Cox transformation coefficient can be estimated through a variety of means. Specific lambda coefficients are the same as other transformations: $\lambda=0.5$ is a square root transformation, $\lambda=0$ is the log transformation.
Osborne, J. W. (2013). Best practices in data cleaning: a complete guide to everything you need to do before and after collecting your data. Los Angeles: Sage.
Comment: The sting is in the first sentence. As marginal normality is **not** an assumption here, how to test for it or bring it about is itself a secondary issue.
Comment: What do you mean by sting?
Comment: "If normality is an assumption of your analysis ..." But it isn't an assumption. For example, binary predictors are fine in this kind of model, even they fail absolutely at being normally distributed.
Comment: Proper notation is not $log_e(y_i)$ but $\log_e(y_i)$, coded as \log_e(y_i). This gets you proper spacing in things like $a\log b$ (coded as a\log b) and $a\log(b)$ (coded as a\log b). I included both examples to show the context-dependent nature of the spacing: there is less space to the right of $\log$ in the second example. $\qquad$
Comment: This is a nice example for using a Box-Cox transformation.


Drupal 301 redirects for matching paths without .htaccess

Question: I am using a Drupal site on top of nginx, and would like to be able to redirect a set of pages from an old style url, to a new one, using 301s. The content has already been migrated over to the new urls, but there may be links elsewhere with the old style. How can I achieve 301 redirects for matching paths, to redirect using part of the information from the old url to inject into the new one (namely [timestamp]).
From:
example.org/article/[timestamp]

To:
example.org/article/doi/static-[timestamp]

I know how I would do this with .htaccess, but is there a way to do this in Drupal itself, or a module to achieve this?
Having looked at the docs, I think that
drupal_goto($path = '', array $options = array(), $http_response_code = 301)

May be the best way to go, with a corresponding (pseudocode):
if path == oldpath,
    drupal_goto(etc.)

Answer: Probably the Global Redirect module suits your needs.
You may have to implement the timestamp feature as a new token with a custom module.
Comment: Thanks for the answer - as it happens, Global Redirect is overkill for what I need, and so have implemented as per the answer.
Answer: In this case, I looked at @Arosboro's suggestion about using Global Redirect. This was a bit more than I actually required, as all I needed was a simple redirect for a particular page. What I did instead was implement a quick module which handled the redirect based on a regex match for the old URL.
function redirect_init() {
    if (isset($_GET['destination'])) {
        $destination = $_GET['destination'];
        unset($_GET['destination']);
    }

    $request_path = redirect_request_path();

    // If the request_path() matches an article, redirect to the new URL
    // for articles.
    if ($request_path) {
        drupal_goto($request_path, array(), 301);
    }
}

function redirect_request_path() {
    $path = ltrim(request_path(), '/');

    if (preg_match('/^article\/\d+$/', $path)) {
    $path_list = explode('/', $path);
    $timestamp = $path_list[1];
        return 'article/doi/10.7244/cmj-' . $timestamp;
    } else {
        return;
    }
}


Converting fetch PUT request into axios request

Question: I have been using fetch on the frontend to make a PUT request. My code looked like the following:
fetch(url, {
  headers: {
    'content-type': 'png',
  },
  method: 'PUT',
  body: file,
})

I am trying to write the same using axios but doesn't seem to be working
await axios.put(url, {
     data: {
        body: file
    },
    headers: {
       'content-type': 'png',
    },
})

Answer: Take a look at the axios.put signature:
axios.put(url[, data[, config]])
The second argument is treated as data, so your headers end up as part of the request body.
Further, data: { body: file }, is redundant. axios.put()'s data argument is already treated as body.
So you can either do:
await axios.put(url, file,
  {
    headers: {
      'content-type': 'png'
    }
  }
)

or:
await axios.put(url, {},
  {
    data: file,
    headers: {
      'content-type': 'png'
    }
  }
)

Or, for even more resemblance with fetch API,
await axios(url,
  {
    method: 'PUT',
    data: file,
    headers: {
      'content-type': 'png'
    }
  }
)


Comportamento inesperado ao atualizar o estado do componente

Question: Estou trabalhando num projeto com muitos componentes, e, a maioria deles precisam compartilhar o mesmo estado, fazer isso através das props funciona, mas é de difícil manutenção, se um componente filho precisar de mais algum valor, é preciso alterar todos os componentes pai até a origem do dado
Como alternativa, há os Contexts, porém os mesmos são ruins, para usar mais de um Context no mesmo componente, deve adicionar um Comsumer no método render, mas o acesso a ele será apenas dentro desse método, no meu caso, preciso acessar múltiplos contexts em todo o componente, além disso, há lugares em que preciso acessar antes do render ser chamado, então, é ruim esperar passar de dentro do método para uma propriedade do componente
Uma terceira alternativa é o uso do Redux, seu funcionamento é exatamente como preciso, um local que armazene todos os estados e disponibilize aos componentes. Porém, ele é um pouco complicado, requer um certo mapeamento do estado para uma propriedade, além disso, um dos pré requisitos do projeto é ser o menor possível, sendo assim, é preferível utilizar o mínimo de bibliotecas possível
No final, criei um pequeno utilitário simples que mantinha um estado global dentro dos componentes sempre atualizado:

Um arquivo contém a variável do estado global e disponibiliza três métodos para criar e alterar um "subestado" (para não manter tudo no mesmo estado, assim organizar melhor) e um listener para avisar quando houver uma alteração do estado, esse arquivo é utilizado apenas pelo utilitário, não pelo projeto todo

const globalState = {};

const listeners = [];

function createState(name, initialValue = {}) {
    globalState[name] = initialValue;

    callListeners();
}

function setState(name, state) {
    globalState[name] = { ...globalState[name], ...state };

    callListeners();
}

function onChange(listener) {
    listeners.push(listener);
}

function callListeners() {
    for (const listener of listeners)
        listener(globalState);
}

const store = { createState, setState, onChange };

export default store;

Uma classe que deve ser utilizada para criar o estado, através de extensão, nela é definido um nome único para o subestado e seu valor, que será setado no estado global (global[name] = value)

import store from './store';

export default class State {

    name;

    state = {};

    constructor(name) {
        this.name = name;

        store.createState(name);
    }

    setState(state) {
        this.state = { ...this.state, ...state };

        store.setState(this.name, this.state);
    }

}

Por último, um componente abstrato para ser estendido no lugar de React.Component, ele adiciona um listener no primeiro arquivo, quando houver uma mudança no estado global, atualiza o estado do componente

import { Component as ReactComponent } from 'react';

import store from './store';

export default class Component extends ReactComponent {

    mounted = false;

    state = {
        global: { }
    };

    constructor(props) {
        super(props);

        store.onChange(state => {
            if (this.mounted)
                this.setState({ global: state });
            else
                this.state = { ...this.state, global: state };
        });
    }

    componentDidMount() {
        this.mounted = true;
    }

}

Seu uso é simples, para criar um estado, basta criar uma classe que estenda State e instanciar. Para usar, basta o componente estender de Component, o estado global sempre se manterá atualizado em this.state.global:
import React from 'react';

import states from './components/states';

// Defini o subestado
class MyState extends states.State {

    state = { myValue: Math.random(), change: () => this.change() };

    constructor() {
        super('myState');

        this.setState(this.state);
    }

    change() {
        this.setState({
            myValue: Math.random()
        });
    }

}

export default class App extends states.Component {

    constructor(props) {
        super(props);

        // Adiciona ao estado global
        new MyState();
    }

    render() {
        // Utiliza através de this.state.global
        return (<>

{ JSON.stringify(this.state.global) }

            <button onClick={() => this.state.global.myState.change()}>change</button>
        </>);
    }

}

Até aí tudo funcionando, porém, em dado momento, precisei observar as mudanças no estado global, e fazer algumas ações ao ocorrer uma alteração em determinada propriedade:
componentDidUpdate(prevProps, prevState) {
    if (prevState.global.myState.myValue !== this.state.global.myState.myValue)
        // ...
}

Quando há uma alteração no estado global, o componentDidUpdate é chamado e this.state.global.myState.myValue é alterado pelo novo valor, porém prevState.global.myState.myValue também é alterada pelo novo valor, em vez de manter o antigo. Nenhuma outra alteração é feita para que o componentDidUpdate seja chamado por outro motivo se não a alteração em myState.myValue, as comparações JSON.stringify(prevState) === JSON.stringify(this.state) e JSON.stringify(prevProps) === JSON.stringify(this.props) retornam verdadeiro. Então por que a variável que deveria manter o estado anterior, é alterada pro novo estado?

const globalState = {};

const listeners = [];

function createState(name, initialValue = {}) {
    globalState[name] = initialValue;

    callListeners();
}

function setState(name, state) {
    globalState[name] = { ...globalState[name], ...state };

    callListeners();
}

function onChange(listener) {
    listeners.push(listener);
}

function callListeners() {
    for (const listener of listeners)
        listener(globalState);
}

const store = { createState, setState, onChange };

class State {

    name;

    state = {};

    constructor(name) {
        this.name = name;

        store.createState(name);
    }

    setState(state) {
        this.state = { ...this.state, ...state };

        store.setState(this.name, this.state);
    }

}

class Component extends React.Component {

    mounted = false;

    state = {
        global: store.globalState
    };

    constructor(props) {
        super(props);

        store.onChange(state => {
            if (this.mounted)
                this.setState({ global: state });
            else
                this.state = { ...this.state, global: state };
        });
    }

    componentDidMount() {
        this.mounted = true;
    }

}

class MyState extends State {

    state = { myValue: Math.random(), change: () => this.change() };

    constructor() {
        super('myState');

        this.setState(this.state);
    }

    change() {
        this.setState({
            myValue: Math.random()
        });
    }

}

class App extends Component {

    constructor(props) {
        super(props);

        new MyState();
    }

    componentDidUpdate(prevProps, prevState) {
        console.log(JSON.stringify(prevProps) === JSON.stringify(this.props))
        console.log(JSON.stringify(prevState) === JSON.stringify(this.state))
        console.log(prevState.global.myState.myValue, this.state.global.myState.myValue)
    }

    render() {
        return (

{ JSON.stringify(this.state.global) }

            <button onClick={() => this.state.global.myState.change()}>change</button>

);
    }

}

ReactDOM.render(<App />, document.getElementById('root'));

Comment: @VirgilioNovic para alterar o estado do componente eu utilizo o `setState` do React, então deveria alterar normalmente. Adicionei um executável, obrigado pela dica
Comment: talvez porque já atualizou.
Comment: você que criou todo o código tipo um context ou redux ???
Comment: @VirgilioNovic também pensei nisso, porém não há nenhuma outra alteração que possa chamar o `componentDidUpdate`, como ele é chamado só pode ser por causa da alteração do estado global. Sim, isso seria só um protótipo, pra ver se funciona, mas por enquanto não está funcionando 100%
Comment: então é isso, eu estudo `react` você que fez o código, talvez (estou só achando tá) não tenha o estado junto ao `react`, possa ser uma mudança somente no valor da variavel e não no estado. esse o código é muito grande não testei
Comment: Monta com código na sua pergunta acho melhor igual eu faço nas minhas https://pt.stackoverflow.com/questions/463410/problema-na-l%c3%b3gica-react-n%c3%a3o-calcula/463417#463417 dá para testar
Answer: Depois de mais alguns testes, descobri o motivo, a variável globalState é um objeto, e, por isso é passada sempre como referência, ao atualizar o valor do subestado (MyState, classe que herda de State), a variável do estado do componente era alterado, mas não seu "estado real" (o que é renderizado), semelhante ao que ocorre quando você altera o estado do componente fora do construtor diretamente (this.state = { ... }), em vez de usar setState, porém o React não percebe e não houve uma exceção avisando do erro, depois da variável de estado do componente ser alterada, o estado real do componente é alterado (no store.onChange(state => { ...) e o componentDidUpdate é chamado, mas o estado anterior que é passado já tinha sido alterado, por ser uma referência. Isso pode ser percebido com algumas alterações...
O componente deve alterar o estado apenas na primeira vez, para que o método change seja setado no estado global, então verifique se já foi setado, se sim, não atualiza
_setted = false;

constructor(props) {
    super(props);

    store.onChange(state => {
        // Se o estado já foi definido, não atualiza o estado
        if (this._setted)
            return;

        // Verifica se o estado já foi definido
        if (state.myState && state.myState.change)
            this._setted = true;

        if (this.mounted)
            this.setState({ global: state });
        else
            this.state = { ...this.state, global: state };
    });
}

No componente de teste adicione um segundo botão para logar o valor da variável de estado do componente

{ JSON.stringify(this.state.global) }

<button onClick={() => this.state.global.myState.change()}>change</button>

<button onClick={() => console.log(this.state.global.myState)}>log</button>

Se clicar em "change" e depois "log", vai perceber que this.state.global.myState.myValue mudou, mesmo que o estado real não tenha sido alterado no listener, e portanto, a tela também não mudou

const globalState = {};

const listeners = [];

function createState(name, initialValue = {}) {
    globalState[name] = initialValue;

    callListeners();
}

function setState(name, state) {
    globalState[name] = { ...globalState[name], ...state };

    callListeners();
}

function onChange(listener) {
    listeners.push(listener);
}

function callListeners() {
    for (const listener of listeners)
        listener(globalState);
}

const store = { createState, setState, onChange };

class State {

    name;

    state = {};

    constructor(name) {
        this.name = name;

        store.createState(name);
    }

    setState(state) {
        this.state = { ...this.state, ...state };

        store.setState(this.name, this.state);
    }

}

class Component extends React.Component {

    mounted = false;

    state = {
        global: store.globalState
    };

    _setted = false;

    constructor(props) {
        super(props);

        store.onChange(state => {
            // Se o estado já foi definido, não atualiza o estado
            if (this._setted)
                return;

            // Verifica se o estado já foi definido
            if (state.myState && state.myState.myValue)
                this._setted = true;

            if (this.mounted)
                this.setState({ global: state });
            else
                this.state = { ...this.state, global: state };
        });
    }

    componentDidMount() {
        this.mounted = true;
    }

}

class MyState extends State {

    state = { myValue: Math.random(), change: () => this.change() };

    constructor() {
        super('myState');

        this.setState(this.state);
    }

    change() {
        this.setState({
            myValue: Math.random()
        });
    }

}

class App extends Component {

    constructor(props) {
        super(props);

        new MyState();
    }

    componentDidUpdate(prevProps, prevState) {
        console.log(JSON.stringify(prevProps) === JSON.stringify(this.props))
        console.log(JSON.stringify(prevState) === JSON.stringify(this.state))
        console.log(prevState.global.myState.myValue, this.state.global.myState.myValue)
    }

    render() {
        return (

{ JSON.stringify(this.state.global) }

            <button onClick={() => this.state.global.myState.change()}>change</button>

            <button onClick={() => console.log(this.state.global.myState)}>log</button>

);
    }

}

ReactDOM.render(<App />, document.getElementById('root'));

A solução é simples, quando o componente for atualizar o estado, deve criar uma nova variável, em vez de passar a referência do objeto:
store.onChange(state => {
    if (this.mounted)
        this.setState({ global: { ...state } });
    else
        this.state = { ...this.state, global: { ...state } };
});


Why is the given smooth vector field non zero?

Question: Let $S^n$ be the unit sphere in $\Bbb R^{n+1}$ where n is odd.   Assume $n = 2k-1$ where $k \in \Bbb N$ and consider the vector field on $S^n$ given by
$$X_p = \left( -x_2 \frac{\partial}{\partial x_1} + x_1 \frac{\partial}{\partial x_2} \right)+\left( -x_4 \frac{\partial}{\partial x_3} + x_3 \frac{\partial}{\partial x_4} \right)+ \dots+\left( -x_{2k} \frac{\partial}{\partial x_{2k-1}} + x_{2k-1} \frac{\partial}{\partial x_{2k}} \right)$$
This is a smooth vector field on $S^n$ because the $x_i$ are smooth for each $i$. But I'm not able to deduce the fact that it's a non-zero vector field which I'm told it is. I'm new to differential geometry and I hope someone can explain clearly as to why it's a non-trivial smooth vector field.
Answer: The $\frac{\partial}{\partial x_i}$ are linearly independent. So, for it to be zero one must have $x_1=x_2=...=x_{2k-1}=0$, but this point is not on the sphere.
Comment: @JohnMitchell I am not using it. You are using it when you proved that $X_p$ is a vector field on $S^n$.
Comment: Where are you using the fact that n is odd?


Computing ratio $ \frac{\int_{0}^{1}\left(1-x^{k}\right)^{n} d x}{\int_{0}^{1}\left(1-x^{k}\right)^{n+1}dx} $ by other means than Beta integrals

Question: For any positive numbers $k$ and $n$, converting the integral
$$
I_{n}:=\int_{0}^{1}\left(1-x^{k}\right)^{n} d x
$$
into a Beta Function by letting
$y=x^{k}$, gives  $d x=\frac{1}{k} y^{\frac{1}{k}-1} d y$ and
$$
\begin{aligned}
I_{n} &=\int_{0}^{1} \frac{1}{k} y^{\frac{1}{k}-1}(1-y)^{n} d y \\
&=\frac{1}{k} B \left(\frac{1}{k} , n+1\right) \\
&=\frac{\Gamma\left(\frac{1}{k}\right) \Gamma(n+1)}{k \Gamma\left(\frac{1}{k}+n+1\right)}
\end{aligned}
$$
Then the ratio becomes
$$
\frac{I_{n+1}}{I_{n}}=\frac{\Gamma\left(\frac{1}{k}\right) \Gamma(n+2)}{k \Gamma\left(\frac{1}{k}+n+2\right)} \cdot \frac{k \Gamma\left(\frac{1}{k}+n+1\right)}{\Gamma\left(\frac{1}{k}\right) \Gamma(n+1)}
$$
Using the identity $\Gamma(z+1)=z \Gamma(z)$, we can simplify the ratio
$$
\frac{\int_{0}^{1}\left(1-x^{k}\right)^{n} d x}{\int_{0}^{1}\left(1-x^{k}\right)^{n+1}dx}=1+\frac{1}{k(n+1)}
$$

By the way, $$
\lim _{n \rightarrow \infty} \frac{\int_{0}^{1}\left(1-x^{k}\right)^{n} d x}{\int_{0}^{1}\left(1-x^{k}\right)^{n+1}dx}= \lim _{k \rightarrow \infty} \frac{\int_{0}^{1}\left(1-x^{k}\right)^{n} d x}{\int_{0}^{1}\left(1-x^{k}\right)^{n+1} d x}=1
$$
My Question: Is there any method other than Beta Function?   Your opinion and alternative method is warmly welcome.
Comment: $\int (1-x^k)^n\,dx=x\,\, _2F_1\left(\frac{1}{k},-n;1+\frac{1}{k};x^k\right)$
Answer: Integrate by parts
\begin{align}
I_{n+1}=&\int_{0}^{1}\left(1-x^{k}\right)^{n+1}dx\\
=&\>k(n+1) \int_{0}^{1}x^k\left(1-x^{k}\right)^{n}dx
= k(n+1) (I_n-I_{n+1})
\end{align}
which is $
\frac{I_n}{I_{n+1}}=1+\frac{1}{k(n+1)}
$.
Comment: Thank you for your simplest solution!


strip() method does not work on str class

Question: First, I have bytes class object "myst". I then convert it to a str class using str(), and remove the whitespace using the strip() method. The problem is that the whitespace "\r\n" is not removed.
>>> myteststring=b'asdf\r\n'
>>> str(myteststring)
"b'asdf\\r\\n'"
>>> str(myteststring).strip()
"b'asdf\\r\\n'"

But, using the strip() method on a byte class works properly.
>>> byteclass=b'asdf\r\n'
>>> byteclass.strip()
b'asdf'

What's wrong here?

I think when I use str(), the resulting string includes double back slash \\. This is may be root of my problem.
>>> myteststring
b'asdf\r\n'
>>> str(myteststring)
"b'asdf\\r\\n'"   # << this is problem ??

Comment: i don't know why image doesn't uploaded. so i add my code and execution result as text.
Comment: I reversed my downvote on the basis of you you converting the images to text. You shouldn't have been posting images of code in the first place. This is not.. great... but it's much better, thanks.
Comment: `strip()` removes characters only from edges of the string. When converting bytes to string, you add quotes on the edges of the string, so nothing is removed.
Answer: When passed a bytes object without an encoding argument, the str function would simply call the repr function to return the string representation of the given bytes object, which is why str(myteststring) returns "b'asdf\\r\\n'", with \r\n escaped with additional backslashes.
You can properly convert a bytes object to a string by passing to the str function an encoding argument instead:
>>> myteststring=b'asdf\r\n'
>>> str(myteststring, encoding='utf-8')
'asdf\r\n'
>>> str(myteststring, encoding='utf-8').strip()
'asdf'


Stop for loop iteration trough a list at a certain point

Question: Basically I want that my for loop stops itself after a certain element in the list is being processed. Here is the code:
vids = [
    'https://www.itatv.com/ita_video.php?viewkey=626de171d928a',
    'https://www.itatv.com/ita_video.php?viewkey=6050c75748399',
    'https://www.itatv.com/ita_video.php?viewkey=6277dbe97910c',
    'https://www.itatv.com/ita_video.php?viewkey=5d660515990ec&pkey=150469821',
    'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811',
    'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811',
    'https://www.itatv.com/ita_video.php?viewkey=60dd6838ce483',
]

for v in vids:
    try:
        vids.remove(v)
        if '&pkey=' in v:
            raise StopIteration
    except StopIteration:
        break

print(vids)

The output is:
[
        'https://www.itatv.com/ita_video.php?viewkey=626de171d928a',
        'https://www.itatv.com/ita_video.php?viewkey=6050c75748399',
        'https://www.itatv.com/ita_video.php?viewkey=6277dbe97910c',
        'https://www.itatv.com/ita_video.php?viewkey=5d660515990ec&pkey=150469821',
        'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811',
        'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811',
        'https://www.itatv.com/ita_video.php?viewkey=60dd6838ce483',
    ]

As you can see nothing changes, but i don't know where my code is faulty. Does anyone have any suggestions?
Comment: In general it's not a good idea to modify the list you are iterating over.
Comment: the code works for me (it modifies the list) but you should change it to ```for v in list(vids):``` to get the behaviour I think you expect
Comment: If you are going to stop the iteration you must use a while loop, your code doesn't follow pip8 guidelines and it's not readable
Answer: The best way to go about this would probably be to create a new list which is basically a copy of the previous one from the wanted item onwards. There are many ways to do that but, probably the cutest one is the following:
new_list = vids[next((i for i, v in enumerate(vids) if '&pkey=' in v), len(vids)):]

What you are basically doing is:

finding the first element that satisfies your condition by
next((i for i, v in enumerate(vids) if '&pkey=' in v) and then
slicing the list from that element onwards.

Note that if the string you are searching for does not exist, the new_list comes out empty ([]).
Also note, that the code as given above, also returns the element you are searching for (inclusive). If you want to make it exclusive, just add one (next((i+1..). The rest stays the same.
Comment: this keeps the item that contains ```'&pkey='``` whereas I believe OP also wants this removed
Comment: @Nin17 if OP does not want that element, they have to also specify what happens if it is the last one in the original list. The code is easy to adjust whatever the desired behaviour may be.
Answer: A simple solution uses another list and a for loop:
vids = [
    'https://www.itatv.com/ita_video.php?viewkey=626de171d928a',
    'https://www.itatv.com/ita_video.php?viewkey=6050c75748399',
    'https://www.itatv.com/ita_video.php?viewkey=6277dbe97910c',
    'https://www.itatv.com/ita_video.php?viewkey=5d660515990ec&pkey=150469821',
    'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811',
    'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811',
    'https://www.itatv.com/ita_video.php?viewkey=60dd6838ce483',
]
new_vids = []
seen = False

for vid in vids:
    if '&pkey=' in vid:
        seen = True
    if seen:
        new_vids.append(vid)
print(new_vids)
# ['https://www.itatv.com/ita_video.php?viewkey=5d660515990ec&pkey=150469821', 'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811', 'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811', 'https://www.itatv.com/ita_video.php?viewkey=60dd6838ce483']

Note that it is usually a bad idea to modify the list while iterating over it. Hence, a new list is used. While not the most efficient, this solution is easy to understand and maintain.
Comment: why `new_vids += [vid]` and not just `new_vids.append(vid)`


Apache solr is not accessible by my server but accessible by my localhost

Question: I have a solr installed in my server(centos 6.5).and everything works fine and my conf files exist where they should be. I try to connect to solr by help of search_api_solr module in drupal. Everything works fine on my localhost and one other host I try my website on,but when I try to connect to this solr using a website on the same server as the solr I'm get error

The Solr server could not be reached

where should I start looking for something that went wrong?
Comment: This question appears to be more about server configuration and it's iptables (or equivalent) than about Drupal.
Answer: problem was caused by selinux on my server.
by disabling selinux and rebooting centOs I could connect to my solr apache.
I found the answer here


Alternative to Firewalld on memory critical servers?

Question: I've bought a 512MB VPS @ DigitalOcean. Currently, I use Firewalld to allow/deny access to certain ports (probably 22, 80, 443 are open). It uses around 25-30MB of memory.
EDIT: Not to forget that I've only 489MB of usable memory out of which 50MB is already used. So if I switch to someother light-weight alternative, I would probably save 15-20MB.
So, is it really necessary to use Firewalld? Or can I use something like iptables (I've never used it before BTW). Is there any major difference between the two? How do I configure iptables to close all ports except port 22, 80, 443?
I'm asking because I even have to consider server security. Because one cannot compromise server security just to save few MBs.
I've read this thread, it says

if possible, you should use the new firewalld system
Answer: Yes, you can use the old system. It's not less secure than firewalld (provided you write your firewall rules correctly). It also doesn't run a daemon, so it's not using a (relatively) large amount of your limited RAM.
Comment: OK. Thanks Michael Hampton. I'll go with iptables then. Can you please help me with iptables rules on Fedora 21 x64 or point me to any good guide? I probably want to open only port 22, 80, 443 and block every other. I've IPv6 on my server too. Thanks.
Comment: if you go [here](https://www.google.ca/webhp?ion=1&espv=2&es_th=1&ie=UTF-8#q=iptables+firewall) it should help you find what you're looking for.
Comment: Thanks GregL. I also read that nftables is going to replace iptables in future. Is nftables ready for production use? I'm using Linux Kernel 3.19.1 right now from Official Fedora and it has nftables support.
Answer: Just googled trough the internet to look for replacement candidates for my 15 years old solution called shorewall. Stumbled over firewalld and this thread... finding dbus, a daemon and XML. Seems like Red Hat catches us all: NetworkManager and systemd, just to name a few.
So looking for a professional solution on memory constrained systems, shorewall is the right one: no daemon, plain text config. Works even on openwrt (your rouer/access point etc). Of course it's overkill for a host firewall with just 3 rules, but hey it will work.