How to interpret this loadings statement in PCA given the example in R?

Question: I am reading in the fabulous book of "Exploratory Multivariate Analysis by Example Using R" 2nd edition by Husson, however when I came across this sentence about PCA loadings and their calculation I couldn't get its math or how to prove it in R code:

Loadings are interpreted as the coefficients of the linear combination
of the initial variables from which the principal components are
constructed. From a numerical point of view, the loadings are equal to
the coordinates of the variables divided by the square root of the
eigenvalue associated with the component.

How can loadings be calculated given the above statement in this R example from the variables divided by the square root of the eigenvalue of the principal component?
I know that each principal component is a linear combination of the variables and loadings are the coefficients of these linear combinations.
Example
A <- as.matrix(data.frame(mtcars[,c(1:7,10,11)]), nrow = 9, byrow = TRUE)
S <- scale(A)
pca_svd <- svd(S)

pca_svd$v # here is the loading matrix
        [,1]    [,2]    [,3]     [,4]   [,5]    [,6]    [,7]    [,8]    [,9]
 [1,] -0.393  0.0275 -0.2212 -0.00613 -0.321  0.7202 -0.3814 -0.1247  0.1149
 [2,]  0.403  0.0157 -0.2523  0.04070  0.117  0.2243 -0.1589  0.8103  0.1627
 [3,]  0.397 -0.0889 -0.0783  0.33949 -0.487 -0.0197 -0.1823 -0.0642 -0.6619
 [4,]  0.367  0.2694 -0.0172  0.06830 -0.295  0.3539  0.6962 -0.1657  0.2518
 [5,] -0.312  0.3417  0.1500  0.84566  0.162 -0.0154  0.0477  0.1351  0.0381
 [6,]  0.373 -0.1719  0.4537  0.19126 -0.187 -0.0838 -0.4278 -0.1984  0.5692
 [7,] -0.224 -0.4840  0.6281 -0.03033 -0.148  0.2575  0.2762  0.3561 -0.1687
 [8,] -0.209  0.5508  0.2066 -0.28238 -0.562 -0.3230 -0.0856  0.3164  0.0472
 [9,]  0.245  0.4843  0.4641 -0.21449  0.400  0.3571 -0.2060 -0.1083 -0.3205

pca_svd$d # here are the eigenvalues
[1] 13.241  8.034  3.954  2.866  2.383  1.959  1.805  1.347  0.829

sqrt(pca_svd$d) # the square root of the eigenvalues
[1] 3.639 2.834 1.988 1.693 1.544 1.400 1.343 1.161 0.911

So the A matrix has 32 rows and 9 columns (variables), so what is meant by variable coordinates and what does this statement really mean?
Update: using FactoMineR package
When I use the FactoMineR package which the above book deals with, I even get more confused as the meaning of the statement in question, see the code below:
library(FactoMineR)
res.pca <- FactoMineR::PCA(mtcars[, c(1:11)], ncp = 9, quali.sup = c(8, 9))

head(res.pca$var$coord) # here store are the coordinates of the variables
R> head(res.pca$var$coord)
      Dim.1   Dim.2   Dim.3    Dim.4   Dim.5    Dim.6   Dim.7   Dim.8    Dim.9
mpg  -0.935  0.0397 -0.1571 -0.00315  0.1373  0.25338  0.1236 -0.0302  0.01712
cyl   0.957  0.0227 -0.1792  0.02095 -0.0501  0.07893  0.0515  0.1960  0.02423
disp  0.945 -0.1283 -0.0556  0.17477  0.2083 -0.00692  0.0591 -0.0155 -0.09860
hp    0.873  0.3888 -0.0122  0.03516  0.1261  0.12453 -0.2257 -0.0401  0.03751
drat -0.742  0.4930  0.1065  0.43535 -0.0693 -0.00541 -0.0155  0.0327  0.00567
wt    0.888 -0.2481  0.3222  0.09846  0.0802 -0.02947  0.1387 -0.0480  0.08479

# actually these are the loadings (V . Sigma) as proof to that:
res.pca$svd$V %*% diag(res.pca$svd$vs) == res.pca$var$coord # TRUE

So how can we compute loadings according to the statement in question of FactoMineR book and package from the variable coordinates when the coordinates themselves are actually the loadings matrix as we know it ($V \cdot \Sigma$)?
Accordingly, my guess is that this statement could read like the following:

Loadings are interpreted as the coefficients of the linear combination
of the initial variables from which the principal components are
constructed. From a numerical point of view, the loadings are equal to
the coordinates of the variables divided which are the eigenvectors scaled up by the square root of the eigenvalue associated with the component.
Comment: I believe you should rather be using the `FactoMineR` package (which is what the authors use) to understand the above statement: `FactoMineR::PCA` doesn't return the loadings but the coordinates of the variables on each PC. Usually, [we say](https://is.gd/SX2byr) that the eigenvector times the square root of the eigenvalue gives the component loadings which can be interpreted as the correlation of each item with the principal component. More information in this [great post](https://stats.stackexchange.com/a/104640/930) by @amoeba.
Comment: I believe the confusion comes from the fact that the authors of the `FactoMineR` package use terminology related to PCA "à la française" (French school of data analysis), according to which factorial coordinates reflect correlations between variables and factor axis (or components).
Comment: On loadings and eigenvectors of PCA https://stats.stackexchange.com/q/143905/3277
Comment: @chl, I added the FactoMineR package code as requested, but the statement gets more confusing by the word divided by, what could be the better wording for that then?
Comment: @ttnphns, I am aware of that excellent post on this confusion between the two, and how prcomp() output `$rotation` refers to loadings when they are actually eigenvectors (direction only devoid of magnitude reflected by the variance). But would you agree with the statement made by the author? If not, how would you re-phrase it correctly? –
Answer: I'm answering only to the citation at the beginning of the question. I did not consider the analysis in R provided in the question.
I admit that the author of the first passage may have made some confusion in terminology. Let us define properly.
$v$ is the eigenvector's values. It is the eigenvector from eigencecomposition of the covariance matrix of the variables or, equivalently, the right eigenvector from SVD decomposition of the data matrix. Eigenvector values are the standardized coordinates of the variables as vectors in the space of the principal components, i.e. on a biplot or loading plot - see last paragraph here.)
$\lambda$ is the corresponding eigenvalue (the component's variance).
$a=v \sqrt{\lambda}$ is the loading vector. Loadings $a$ are the coefficients of the linear combination predicting a variable by unit-scaled principal components. $V_i= a_{i1}F_1+a_{i2}F_2...$.
While the coefficients of the linear combination to compute unit-scaled principal component values (scores), $F_j= b_{1j}V_1+b_{2j}V_2...$, are given by
$b=a/\lambda=\frac{v\sqrt{\lambda}}{\lambda}=v/\sqrt{\lambda}$
(see here, "Computation of B in PCA: ... When component loadings are extracted but not rotated (...) amounts to simply dividing each column of A by the respective eigenvalue - the component's variance").
So you have eigenvector divided by the square root of the corresponding eigenvalue. The original citation was:

Loadings are interpreted as the coefficients of the linear combination
of the initial variables from which the principal components are
constructed. ... the loadings are equal to
the coordinates of the variables divided by the square root of the
eigenvalue associated with the component.

Then, if my interpretation is correct, that passage should sound like:

Component score coefficients are the coefficients of the linear
combination of the initial variables from which the principal
components [component scores] are constructed. ... the coefficients are
equal to the coordinates of the variables [the eigenvectors] divided
by the square root of the eigenvalue associated with the component.

In this case, the author seems to mean component score coefficients by the term "loadings".
This is so if by "coordinates of the variables" the author meant eigenvectors (standardized = normalized = unit-scaled coordinates of the variables) and implied the components themselves to be unit-scaled (as we often think in factor analysis context).
But if by "coordinates of the variables" the author meant loadings (variance-scaled or full-scaled coordinates of the variables) and implied the components themselves to be variance-scaled or full-scaled (as we often think in PCA context), then we are in the situation of tautology:
Since $a=v \sqrt{\lambda}$, then $v=a/ \sqrt{\lambda}$,
and also we know that then eigenvector values are the coefficients $b$ to compute the full-scaled principal components from the input variables. If that is what the author meant, then the passage should sound like:

Eigenvectors are the component score coefficients, the coefficients of the linear
combination of the initial variables from which the principal
components [component scores] are constructed. ... the coefficients are
equal to the coordinates of the variables [the loadings] divided
by the square root of the eigenvalue associated with the component.

In this case, the author seems to mean eigenvector entries by the term "loadings".

I might recommend to read the paragraph "Digression" in my answer about the similarities and differences between PCA and Factor analysis.
Comment: from the above R analysis, by numbers I would confirm that per `FactoMineR` package, the `output$var$coord` means *loadings* (variance-scaled or full-scaled coordinates of the variables) then according to your second premise we are in the situation of tautalogy...
Comment: can I say that the $B$ matrix would be the change of basis matrix that would transform my newly obtained data in the experiment to the newly projected PCA space spanned by the first plane for example of PC1 and PC2? So $B$ is $V$ when $XV$= $U \Sigma$ = PC scores.
Comment: Yes, correct. PC scores (unstandardized, i.e. with their native variance) are computed directly by eigenvectors, so B=V then.


Do there exist families of groups $G_{s}$ such that $\forall s\in[0,1], |G_{s}|=\mathfrak{c}$

Question: Do there exist families of isomorphism classes of groups $G_{s}$ such that $\forall s\in[0,1], |G_{s}|=\mathfrak{c}$, where $\mathfrak{c}$ is the cardinality of the continuum, and for any $a,b\in[0,1], a\neq b$, $G_{a}$≇$G_{b}$?
Comment: Given your tags: presumably you are asking for these to be Lie groups? and if so, by (non)isomorphism, do you mean in the sense of bicontinuous group isomorphism?
Comment: I don't think I actually require that they be Lie groups -- that would be a nice bonus, though, and yes, if they were Lie groups, then I do mean in the sense of a bicontinuous group isomorphism.
Comment: Well, if you didn't need them to be Lie groups, my guess would be that one could cook up discrete examples, although I don't claim to see exactly how to do it
Answer: I think you are asking if there are families $\{G_t:t\in[0,1]\}$ of Lie groups of positive dimension whose elements are non-isomorphic in pairs.
There are examples of curves of non-isomorphic Lie groups in the class of nilpotent groups. In fact, as soon as the dimension is greater or equal to $7$, there are continuously-many non-isomorphic filiform Lie algebras, so the same thing happens for groups (filiform Lie algebras are "maximally non-abelian" nilpotent Lie algebras) This is discussed in detail, for example, in the book by Goze on Nilpotent Lie algebras.
As the dimension grows, we find families of unbounded dimension.
In general, the nilpotent part of the world is filled with many, many examples.
Comment: (Notice that a bicontinuous isomorphism between Lie groups is in fact a bidifferentiable, so looking at Lie algebras is enough to tell groups apart)
Answer: Apparently the question was about bicontinuous isomorphism classes of Lie groups, and that question was answered by Mariano Suarez-Alvarez.
Now, I suspect that many of these Lie-groups are in fact isomorphic algebraically, just not by a bicontinuous isomorphism.
Let me answer the question literally:  There is a family of continuum many, pairwise non-isomorphic groups of size continuum.  Actually, there is such a family of countable groups.
Namely, let $\mathbb P$ denote the set of prime numbers.
For each infinite set $S\subseteq\mathbb P$ let $G_S$ be the direct sum of the abelian groups $\mathbb Z_p$, $p\in S$.  The groups $G_S$ are pairwise non-isomorphic since if $S,T\subseteq\mathbb P$ and $p\in S\setminus T$, then $G_T$ has no element of order $p$ but $G_S$ does.
Now, the groups $G_S$ are countable.  If you want size continuum, you can either take the cartesian product instead of direct sum, or simply multiply everything with $\mathbb R$.  In either case you get a family of pairwise nonisomorphic groups of size $2^{\aleph_0}$.


How to send Text and Images to server using NSURLConnection in ios

Question: Hi i am very beginner in Ios and in my project i need to send "Username" and "Password"  and "UserImage" to server using NSURLConnection and for this i have inserted this three fields(username,password,userimage) in one Dictionary and i am posting this dictionary to server but using my below code details are not sending to server please help me what did i do here wrong
my code:-
@interface SendingImagesToServer ()
{
    NSMutableData *body;
}
@end

@implementation SendingImagesToServer

- (void)viewDidLoad {
    [super viewDidLoad];

    NSData *imageData;
    UIImage * image;
    NSError *error = nil;
    image = [UIImage imageNamed:@"friendship.jpg"];
    imageData = UIImageJPEGRepresentation(image, 0.1f);

    NSDictionary *mainDict = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"James"  ,@"username",
                              @"1234",@"Password",
                              imageData,@"image",
                              nil];

    NSString *jsonString = [mainDict JSONRepresentation];

    NSData * webbody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    body = [webbody mutableCopy];

    NSString *urlstr = [NSString stringWithFormat:@"My url here"];

    NSURL *url = [NSURL URLWithString:urlstr];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

    [request setHTTPMethod:@"POST"];

    NSString *boundary = @"----WebKitFormBoundarycC4YiaUFwM44F6rT";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];

    body = [NSMutableData data];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"Content-Disposition: form-data; name=\"imagename\"; filename=\"picture.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    if(imageData == nil && error!=nil) {
        NSLog(@"nil");
    }
    else
    {
        NSLog(@"not nill");
    }

    [body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Successfully sending to server");
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    NSLog(@"error is %@",[error localizedDescription]);
}

@end

Comment: Ouch. You have a mix of JSON and multipart/form-data (and you overwrite one with the other). You try to include binary data in JSON. You don't actually create or call a request. Before anybody can actually help you, you need to specify exactly how the data should be send: multipart/form-data or JSON, if JSON how the image data is encoded (base64?), etc.
Answer: You create the request, but don't start it anywhere in your code. Also you don't create the NSURLConnection anywhere (at least not in the posted part).
The easiest way to achieve this would be to simply add this line at the end of your viewDidLoad method :
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

You can read more here
Comment: ,can you please edit my code and please post working code because i am very new for IOS
Comment: what did you change here it was seems like copy and paste of my above posted code and  there was no change
Comment: As I said before : I've added the line from my answer at the end of your `viewDidLoad` implementation (line 60 in pastebin) and made sure that your `SendingImagesToServer` class conforms to `NSURLConnectionDelegate` protocol (line 1). Please read carefully.
Comment: oh sorry Losiowaty i did not see these two chnages in your updated code(    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self],NSURLConnectionDelegate protocol)
Comment: so is these two changes enough to send my fields to server?
Comment: They should be. If the server understands your request is another thing. You should consider the comment by @jcaron under your question.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/96668/discussion-between-abhiram-and-losiowaty).


Stream mp4 file with watermark through a web using ffmpeg

Question: I'm having problems with ffmpeg, probably due to my inexperience with this software.
My basic need is the following: I have a series of videos with material that I want to protect so that it is not plagiarized. For this I want to add a watermark so that when a user views it, they also see some personal data that prevents them from downloading and sharing it without permission.
What I would like is to create a small Angular + Java application that does this task (invoking ffmpeg via Runtime#exec)
I have seen that from ffmpeg I can emit to a server, like ffserver but I wonder if there is a somewhat simpler way. Something like launching the ffmpeg command from my java application with the necessary configuration and having ffmpeg emit the video along with the watermark through some port/protocol.
EDIT
I have continued to investigate and I have seen that ffmpeg allows you to broadcast for WebRTC, but you need an adapter. What I would like and I don't know if it is possible is to launch ffmpeg so that it acts as a server and it can be consumed from the web.
Comment: _"...Invoking FFmpeg one way or another"_ That's called running an external process. Java has a **Process** API for that. Not sure what operating system you're using but try to read tutorials for it and run a simple app. Try running FFmpeg with some arguments (options) as a test like convert input JPG to output PNG or MP4. If working okay, then finally test telling FFmpeg to output video to a server location/port. Those are the steps to try and ask a question about...
Comment: My problem is not how to call ffmpeg from java, my problem is what arguments to pass to it to act as a server
Comment: FFmpeg cannot be used as a server. Your options are.. **(Option 1)** Make your own computer (IP) open to the internet, then FFmpeg can output to that same IP/port and outside listeners can see the video stream. You open by configuring your router, and forwarding one of its ports (same port as FFmpeg output). **(Option 2)** Just get webspace (that can run PHP) and put there a script that receives input data (video chunks) and stores them on server. FFmpeg can output to the url of server script, and listeners can connect to the stream via a second script that manages multi listener connects.
Comment: PS: **(Option 3)** Is to use FFserver. I think it does temporary port forwarding silently in the background... Further options include not using FFmpeg and instead use an encryption tool like WideVine, **..or...** Chrome/Edge browsers can decode/encode video frames (using their WebCodecs API) so you can modify pixels of input frames before outputting to connected user (via sockets or web server script).  **...or...**  Prepare the videos in such a way that frames can be replaced dynamically with a frame that has "user information" (_eg:_ every X mins your video cuts to a blue screen for 4 secs)
Answer: I don't have a Java example but we do something similar in our WebRTC .NET application. The code should be fairly straightforward to port to Java.

FFMpeg parameters

Audio: https://github.com/liveswitch/liveswitch-connect/blob/486b35684e1e9be0df87937fe41e223a87a92219/src/FM.LiveSwitch.Connect/FFCapturer.cs#L151
Video: https://github.com/liveswitch/liveswitch-connect/blob/486b35684e1e9be0df87937fe41e223a87a92219/src/FM.LiveSwitch.Connect/FFCapturer.cs#L244

RTP Reader (to process output from FFMpeg): https://github.com/liveswitch/liveswitch-connect/blob/master/src/FM.LiveSwitch.Connect/RtpReader.cs

The RTP packets received in the reader can be streamed over most Java WebRTC libraries.


How to classify graph symmetry group with an algorithm?

Question: I'm trying to develop (or if possible find an implementation of) an algorithm to classify the symmetry group of an undirected graph.
Consider an undirected graph $G = \{N, E\}$, where $N = \{n_i\}$ - nodes and $E = \{(n_i, n_j)\}$ - edges. Nauty one of the popular tools people use to work with graph symmetries can be used to obtain generators of the symmetry group. Let's call the symmetry (automorphism) group $A(G)$ and it's generators $a_1...a_l$. I want to consider a simple graph, that is, the graph in which the orbit of $A(G)$ is all the nodes of $G$ (any graph can be factorized in the independent graphs, some of which may have only one node, that have this property). The question is how can I algorithmically classify $A(G)$ i.e. how can I tell that it's $D_4$ or $C_{15}$ or $S_3$ or whatever else? My only idea is to come up with the logic similar to what people do with point groups in crystals, like here, but I wonder if there is an easier way.
I may not be formulating this clearly, so I would be happy to correct it in accordance to your corrections. Thanks in advance!
Comment: Can you clarify what the following sentences mean: "all the nodes of the graph are touched by at least one permutation of the symmetry group",  " entire graph is symmetric", "any graph can be broken down into parts that have this property"? I think your question will be easier to understand if you use proper well-defined mathematical language.
Comment: I'm not 100% sure what you are referring to. Do you mean the set of all automorphisms of a given graph when you are talking about symmetry group?
Comment: @verret Thank you for the question. Corrected the question a little bit. Is this clearer? What I meant is that all nodes of the graph are an orbit of the automorphism group. Any graph can be decomposed into induced subgraphs that have this property, some of which will obviously have only one node
Comment: @DavidScholz yes. Corrected that. Thank you for the correction
Comment: Ok, this is a little better. First, such graphs are usually called vertex-transitive graphs, and are very well-studied. (For example https://en.wikipedia.org/wiki/Vertex-transitive_graph) They are still too wide a class to admit a complete classification in any meaningful way. If you just want an algorithm to find the automorphism group, you already know about Nauty, so what is missing?
Comment: @verret so, I can find an automorphism group with nauty, but what I want is to classify it algorithmically. I need to run this algorithm on the big set of graphs and I want to see if the class of an automorphism group is correlated with some other information I have about these graphs. Does this make sense?
Comment: Just to give a random recent example, this paper: https://arxiv.org/abs/2102.07183 appeared on the arxiv about a week ago. Among other things, they computed all the vertex-transitive graphs of order 48 (with 48 nodes). There are 1538868366, and many different automorphisms groups. So there is no hope of getting a nice classification like in the case of crystals.
Comment: Automorphisms groups of vertex-transitive graphs are a very rich class, and cannot be classified in the same way as symmetry groups of molecules (finite subgroups of $SO(3)$) can. The best you can hope for in that direction is to put them in very wide categories, such as "does it contain a regular subgroup (so the graph is Cayley)?", "is it regular itself?", "is it some kind of nice product?", etc.
Comment: I think it's probably true in general, but my experience with problems like this is that in practice most of the graphs that are based on the real data have a fairly simple structure. That is, most of them would be dihedral or cyclic or cyclic with mirror. Do you have any thoughts on how I can check for these three types of groups? Or maybe how I can check if it has a subgroup that is one of them?
Comment: Most graphs that are based on real data are not vertex-transitive. In fact, I would expect most graphs based on "real data" to have trivial automorphism group.
Now, if you obtain these vertex-transitive graphs as "factors" from bigger non-vertex-transitive graphs (I'm not sure what factorisation you have in mind exactly), I would expect them to generally be fairly small. So the most common types of automorphism groups would $S_n$ and $D_n$. (A simple undirected vertex-transitive graph actually cannot have a cyclic automorphism group, except for $C_2$.)
Comment: If you have the generators given by nauty, you can simply plug those in into a system for dealing with groups, such as magma and GAP, and test for isomorphism with whichever groups you like. For example, go to http://magma.maths.usyd.edu.au/calc/ and try the following program
G:=Sym(4);
g:=G!(1,2,3,4);
h:=G!(1,3);
IsIsomorphic(sub,DihedralGroup(4));
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/120064/discussion-between-ian-and-verret).
Comment: We came to a tentative solution. Will share if I'll make this work. Meanwhile, would be happy to take any other ideas.
Comment: @verret Actually, in a sense, the arXiv article that you refer to does classify the automorphism groups of the vertex-transitive graphs of degree $48$. They are all conjugate in the symmetric group to one of $195,826,352$ transitive groups of degree $48$. OK, perhaps that cannot be described as a nice classification :(
Comment: I found a tool that has an interface to Magma and GAP from Python and it's called [Sage](https://www.sagemath.org/). Going to install and play with it. To be continued...
Answer: I published a preprint in which I discuss solution to this problem in section VII.
There are two steps to this problem:
(1) decompose the automorphism group into subgroups to be classified and
(2) classify each subgroup.
I was able to solve problem 1 by using the approach proposed by MacArthur et. al.. Namely, I used geometric decomposition (see the paper for more details) of the automorphism group, which factorizes the symmetry group into normal subgroups acting on the different parts of the graph.
Problem 2 was solved after a very helpful discussion with @verret. Proposed approach is computational and is based on a very simple idea: take a subgroup and check if it is isomorphic to any of the traditional symmetry groups. In my case I compared them with $S_n$, $D_n$, $C_n$ and $A_n$, for $n$ between 1 and the number of nodes.
Implementation of the solution to both problems (1) and (2) and a little more can be found at my GitHub.


Setting width of a web form using Stylesheet

Question: I have created a default web project using Visual Studio 2013. I am able to run the default project created. I am trying to adjust the width of the form and increase it from its default size.
I have added a new page and placed a div as follows

I have created a custom style sheet and added to the page. The content of the style sheet is as follows
.container-fluid {
  margin-right: auto;
  margin-left: auto;
  max-width: 1600px;
}

if I change decrease max-width to 400, the screen is shown small. If increase it to higher values it doesnt move beyond the width shown in the attached picture. I am using Bootstrap 2.2.0
Comment: but what is the problem you are facing..?
Comment: use min-width instead of max-width
Comment: I want the contents to occupy the whole page - from corner to the other corner with a minimal border. But I could not extend it beyond the table shown in the above image.
Comment: ind bootstrap 3  container-fluid default value occupy the whole page .. try don't redefine ..
Comment: It's working. Thanks
Answer: Bootstrap will help you one this.
There are two container classes to choose from:

The .container class provides a responsive fixed width container
The .container-fluid class provides a full width container, spanning the entire width of the viewport

Note: Containers are not nestable (you cannot put a container inside
  another container).

The following example shows the code for a basic Bootstrap page (with a full width container):
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

My First Bootstrap Page

This part is inside a .container-fluid class.


Javascript image onload method - catching errors

Question: This (getSizeFromObjectUrl) function works well to calculate height and width for actual images. I tried this with files (objectURLs) other than images (ex: text files), the code never reaches to catch block in try-catch. What are ways for catching errors/load-exceptions with img.onload?
function getSizeFromObjectUrl(dataURL: string): Promise<{ width: number; height: number }> {
    return new Promise((resolve) => {
        try {
            const img = new Image();
            img.onload = () => {
                const ratio = Math.min(maxImageWidth / img.width, maxImageHeight / img.height, 1);
                resolve({
                    width: img.width * ratio,
                    height: img.height * ratio
                });
            };
            img.src = dataURL;
        } catch (exception) {
            logCalculateImageSizeFailed(exception);
            // handle error
        }
    });
}

Answer: Use promise reject for img.onerror
note, added reject argument to Promise executor callback - see comments in code
function getSizeFromObjectUrl(dataURL: string): Promise<{width: number;height: number}> {
    return new Promise((resolve, reject) => { // amended this line
        const img = new Image();
        img.onerror = reject; // added this line
        img.onload = () => {
            const ratio = Math.min(maxImageWidth / img.width, maxImageHeight / img.height, 1);
            if (img.width && img.height) {
                resolve({
                    width: img.width * ratio,
                    height: img.height * ratio
                });
            } else {
                reject('Bad Image');
            }
        };
        img.src = dataURL;
    }).catch(exception => {
        logCalculateImageSizeFailed(exception);
        // handle error
    });
}

Comment: If you bothered to run the code, you'll see the error in `catch` @Prakhar
Comment: Do we know the cause of error? Like any thrown error/exception?
Comment: This doesn't work, error is not getting caught in catch block.
Comment: I assumed too much about your original code - didn't notice the try/catch inside the Promise executor - I've rewritten the code, should work now - there's also a check to see if the image has a width and height
Comment: I don't think it ever goes inside image.onload when it is not an image. The else rejection seems never executed. Neither goes to catch while onload by other means.
Comment: something like this would work - img.onerror = (error) => { console.log(`error: ${error}`); };
Comment: Oh well ... I can't see why you can't get it working, works fine for me @Prakhar
Comment: your `img.onerror` *"solution"* would result in the promise never settling (neither resolved nor rejected) on error - I highly doubt that's your intention - but if it is, go for it @Prakhar


WordPress Conditional if_page not working

Question: my Conditional PHP is not working and i dont know why. Can you help me?
Here the Code:
<?php
if( is_page(array('5279','4945') ))
{
echo '';
}

elseif( is_page(array('5656','5668','5672','5677','5682','5690','5735','5738','5741','5744','5749','5752')))
{
echo '';
}
else
{
echo '';
}
?>

But i need it in this way... (letters are the Pages ids)
For pages a,b,c,d i need a own logo
For pages e,f,g,h i need a own logo
For pages j,k,l,m i need a own logo
and for Page n,o,p,q i need a own logo
Comment: What exactly is the issue with your code? Does it not work at all? Give you an error message? Show the wrong thing? The right thing, in the wrong place?
Comment: Are you sure your page ID is 5279? Seems quite large
Comment: Yes, page id in wordpress is 5279.

The problem is, that i dont get the Image from the "else" condition placed in the webside.

Only if (is page...) and elseif are working.
Comment: @emitremmus - What do you get if the page_id _isn't_ in your `if` or `elseif` arrays, in that case?
Comment: The real problem is, that i need FOUR conditional statements. And i only have three here.

I need it in this way:
if page id is 1,2,3 then load image 1.png
if page id is 4,5,6 then load image 2.png
if page id is 7,8,9 then load image 3.png
if page id is rest, then load image 4.png
Comment: @emitremmus - why can't you add an extra `elseif`?
Answer: Try this code, literally just tidied it slightly and removed the quotation marks round the page numbers.
<?php
if(is_page(array(5279,4945) ))
{
    echo '';
}
elseif(is_page(array(5656,5668,5672,5677,5682,5690,5735,5738,5741,5744,5749,5752)))
{
    echo '';
}
else
{
    echo '';
}
?>

Just make sure you have the right pages. To do this go to pages in the dashboard and hover over the link to the page you want, you should see it shows the id number in the url, ie post=100. This is the id for that page and the one you will need to use. Using the id means that regardless of the page name, this code will always work for you.
An extreme test would also be using the below instead of the else
elseif(!is_page(array(5279,4945,5656,5668,5672,5677,5682,5690,5735,5738,5741,5744,5749,5752)))
{
    echo '';
}

Comment: I need the condition in this way...

if page is 1,2,3 then image1.png
if page is 4,5,6 then image2.png
if page is 7,8,9 then image3.png
if page is 10,11,12 then image4.png
Comment: I would try `echo 'hello';` for the else statement as this may be as simple as an image not being loaded. Please clarify though what you see on other pages. Do you see an image? No image? One of the images already used?
Comment: the first two conditions are working if(is_page...) and elseif. only "else" is not working. i dont get a image here placed on the side.
Comment: Ok then it could potentially be an image issues, just try `echo 'hello';` for the else instead of the image and confirm if this works.
Comment: Ok then the issue must be to do with the image you are trying to show. Either it is not on the server or the path is incorrect. Before messing with this though, try pressing CTRL+F5 if on windows/CMD+F5 for mac. This does a refresh whilst clearing the cache, do this a few times in case the page is cached. Also try to navigating directly to the image via the url to ensure it is present.


Cloud Firestore whereNotEqual

Question: Does Firestore support something like whereNotEqual?
For example, I need to get exact documents where key "xyz" is missing.
In Firebase realtime db, we could get it by calling *.equalTo(null).
Thanks.
Comment: My understanding of your question is that you want to query a collection to get all the documents that do not have an "xyz" field.  Based on my reading of the documentation and experiments, I don't believe the Firestore API supports that.
Answer: Firestore does not support a direct equivalent of !=. The supported query operators are <, <=, ==, >, or >= so there's no "whereNotEqual".
You can test if a field exists at all, because all filters and order bys implicitly create a filter on whether or not a field exists. For example, in the Android SDK:
collection.orderBy("name")

would return only those rows that contain a "name" field.
As with explicit comparison there's no way to invert this query to return those rows where a value does not exist.
There are a few work-arounds. The most direct replacement is to explicitly store null then query collection.whereEqualTo("name", null). This is somewhat annoying though because if you don't populate this from the outset you have to backfill existing data once you want to do this. If you can't upgrade all your clients you'll need to deploy a function to keep this field populated.
Another possibility is to observe that usually missing fields indicate that a document is only partially assembled perhaps because it goes through some state machine or is a sort of union of two non-overlapping types. If you explicitly record the state or type as a discriminant you can query on that rather than field non-presence. This works really well when there are only two states/types but gets messy if there are many states.
Answer: Cloud Firestore now supports whereNotEqualTo in database queries.
Keep in mind if you have more than one field in your query you may have to create a composite index in Cloud Firestore.

Cloud Firestore whereNotEqual


the [] operator in matrices R

Question: So I know that if you have:
m = matrix(1:9, 3,3)
z = as.matrix(expand.grid(1:3, 1:3))

and you do
m[z]
# you get back 1 2 3 4 5 6 7 8 9

But if you do
m[] = m[z]
# You get back a matrix..

I'm a little confused as to what this [] operator does? why doesnt something like m[][z] or m[z][] return a matrix? and how would I get it to return a matrix without assigning it to a variable m[]
Thanks!
Comment: The documentation for "[" can be found with either `?Extract` or `?"["`. It should be studied _carefully_ if you want to avoid other common pitfalls, I would suggest at least 5 complete readings.
Comment: What do you expect to get back from `m[z]`?  Where is the inconsistency? Remember, in R a `matrix` is just a `vector` with dimensions...
Comment: Well, I expect a matrix. I know that it will return a vector. but instead of creating a new matrix out of the vector like: `matrix(vector, nrow, ncol)`, I found this useful operator. I just couldn't find any documentation on it
Answer: The key here is that when the argument to "[]" (which is really a function) is a two column matrix as you provided, the result will be a vector where the first column specifies the row and the second column specifies the column in operated-upon matrix. This is a "feature" ( and a very handy one I might add)  of the language.
The arguments might or might not contain all of the possible combinations of row and column so the result would not predictably be something that would sensibly be a matrix of the same dimensions. The form: m[] <- m[ z[1:4, ] ] will produce a result but also a warning. You should look at the result and then make an effort to understand what is happening.

the [] operator in matrices R


What is the ideal way to restore a previous version of a site with Backup & Migrate files?

Question: So I've been backing up my sites with backup and migrate and I always found weird that the backup&migrate .mysql files are smaller than the "drush sql-dump" sql files. Does anyone know why?
Also what is the quickest way to do a restore using backup&migrate? I usually unzip the gz files that gets saved to my server and just do a mysql drop database and then recreate it again and just fill it in with the sql files. I'm not sure if im doing it the long way or not.
Comment: backup&migrate .mysql file excludes the cache tables, that's why db size is small when compared to drush sql-dump.
Answer: You can restore using backup & migrate itself.
If you've backup and downloaded the file, then you can use Restore tab (/admin/config/system/backup_migrate/restore) to upload the zipped file and restore.
If you've backed up to the Manual Backups Directory, then you can restore from the directory listing (/admin/config/system/backup_migrate/destination/list/files/manual).
There are Drush commands for the above as well, see drush help after you enabled backup & migrate module.
Comment: yea just used the restore tab...
Answer: BaM files likely smaller than drush dump files becuase BaM profile is leaving out data from accesslog, cache tables, search history, session history and watchdog as defined by default BaM profile > Default Database Backup Options "Exclude the data from the following tables". I believe BaM drush commands have opt out options that can be used similarly.


Requisição Ajax Retornando em Branco

Question: tudo bem ?
Minha duvida é a seguinte: Estou fazendo uma requisição ajax para meu servlet e o retorno dele esta sendo em branco.
JS:
$('#pesquisar').click(function() {
    $.ajax({
        url: '../UsuarioController',
        type: 'POST',
        data: {nome_pesquisa: $('#nome_pesquisa').val()},
        success : function(data) {
            console.log(data);
        },
        error: function(){
            console.log("erro");
        }
    });
    return false;
});

Servlet:
if(request.getParameter("nome_pesquisa").equals("") || request.getParameter("nome_pesquisa") != null){
        try {
            List<Usuario> usuarios = this.dao.search(request.getParameter("nome_pesquisa"));
            String json = new Gson().toJson(usuarios);

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json);
        } catch (Exception ex) {
            Logger.getLogger(UsuarioController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

JSP:
<form class="col-md-10">

                    <input class="form-control border-secondary py-2" type="search" id="nome_pesquisa" name="nome_pesquisa" placeholder="Pesquisar...">

                        <button class="btn btn-outline-secondary" type="submit" id="pesquisar" name="pesquisar">

                        </button>

            </form>

Retorno obtido:
Comment: Com base nesses três *snippets* que forneceu: pode ser qualquer coisa.  Tentou usar `print` ao invés de `write`?
Comment: Tentei, mas não printa nada no console :/
Answer: Talvez seja porque você esqueceu de negar a condição
 !request.getParameter("nome_pesquisa").equals("")

Comment: Além disso, você deve primeiro fazer a validação de nulo, depois usar o `"equals"`. Caso contrário pode ocorrer `NullPointerException`.

Requisição Ajax Retornando em Branco


JQgrid show message before update and multiple update

Question: I am working on JQgrid and trying to achieve some specific functionality. These functionalists are
1)inline update with message shown before update.
2)Multiple update
I tried to read jqgrid and got this code https://jsfiddle.net/OlegKi/byygepy3/11/ . Which is quite approximate to my requirement but it doesn't contain multiple update and message shown before update.
I tried to overwrite these code but maximum i reached is this https://jsfiddle.net/byygepy3/72/  but failed because multiple update only updating half of record and it doesn't show any message before updating either single row or multiple row.
code is inserting just allow me to ask question.
$(function () {
    var myData = [
            { id: 10, ParameterName: "Test", ParameterValue: "" },
            { id: 20, ParameterName: "Test 1", ParameterValue: "" },
            { id: 30, ParameterName: "Test 2", ParameterValue: "" },
            { id: 40, ParameterName: "Test 2", ParameterValue: "" },
            { id: 50, ParameterName: "Test 2", ParameterValue: "" },
            { id: 60, ParameterName: "Test 2", ParameterValue: "" }
        ],
        $grid = $("#list");

    // change the text displayed on editrules: {required: true }
    $.extend(true, $.jgrid.locales["en-US"].edit.msg, {
        required: "No value was entered for this parameter!!!"
    });

    $grid.jqGrid({
        datatype: "local",
        data: myData,
        colNames: ["", "Parameter Name", "Parameter Value"],
        colModel: [
            { name: "act", template: "actions" }, // optional feature
            { name: "ParameterName" },
            { name: "ParameterValue", editable: true,
                editoptions: { maxlength: 100 }, editrules: {required: true } }
        ],
        cmTemplate: { autoResizable: true },
        autoResizing: { compact: true },
        pager: true,
        pgbuttons: false,     // disable page control like next, back button
        pgtext: null,         // disable pager text like 'Page 0 of 10'
        viewrecords: true,    // disable current view record text like 'View 1-10 of 100'
        sortname: "Name",
        iconSet: "fontAwesome",
        caption: 'Parameters',
        autowidth: true,
        hidegrid: false,
        inlineEditing: {
            keys: true
        },
        singleSelectClickMode: "selectonly", // prevent unselect once selected rows
        beforeSelectRow: function (rowid) {
             // allow selection if saving successful
        },
        onSelectRow: function (rowid) {
            $(this).jqGrid("editRow", rowid);
        },
        afterSetRow: function (options) {
            var item = $(this).jqGrid("getLocalRow", options.rowid);
            if (item != null) {
                item.dirty = true;
            }
        },
        navOptions: {
            edit: false,
            add: false,
            search: false,
            deltext: "Delete",
            refreshtext: "Refresh"
        },
        inlineNavOptions: {
            save: false,
            savetext: "Save",
            cancel: false,
            restoreAfterSelect: false
        },
        formDeleting: {
            // delete options
            url: window.g_baseUrl + 'MfgTransactions_MVC/COA/Delete?',
            beforeSubmit: function () {
                // get value
                var selRowId = $(this).jqGrid('getGridParam', 'selrow');
                var parametricValue = $(this).jqGrid('getCell', selRowId, 'ParameterValue');

                // check if empty
                if (parametricValue === "") {
                    return [false, "Cannot delete: No value exists for this parameter"];
                }

                return [true, "Successfully deleted"];
            },
            delData: {
                batchId: function () {
                    return $("#BatchId").val();
                }
            },
            closeOnEscape: true,
            closeAfterDelete: true,
            width: 400,
            msg: "Are you sure you want to delete the Parameter?",
            afterComplete: function (response) {
                if (response.responseText) {
                    alert("response.responseText");
                }

                //loadBatchListIntoGrid();
            }
        }
    }).jqGrid('navGrid')
    .jqGrid('inlineNav')
    .jqGrid('navButtonAdd', {
        caption: "Save Changed",
        buttonicon: "fa-floppy-o",
        onClickButton: function () {
            var $self = $(this), i,
                // savedRows array is not empty if some row is in inline editing mode
                savedRows = $self.jqGrid("getGridParam", "savedRow");
            for (i = 0; i < savedRows.length; i++) {
                    $self.jqGrid("saveRow", savedRows[i].id);
            }

            var localData = $(this).jqGrid("getGridParam", "data"),
                dirtyData = $.grep(localData, function (item) {
                    return item.dirty;
                });
            alert(dirtyData.length > 0 ? JSON.stringify(dirtyData) : "no dirty data");
        }
    });

    // make more place for navigator buttons be rwducing the width of the right part
    var pagerIdSelector = $grid.jqGrid("getGridParam", "pager");
    $(pagerIdSelector + "_right").width(100);

    // make the grid responsive
    $(window).bind("resize", function () {
        $grid.jqGrid("setGridWidth", $grid.closest(".container-fluid").width());
    }).triggerHandler("resize");
});

Comment: It's not full clear what you want to implement. You use both `template: "actions"` (`formatter: "actions"`) and calls `editRow` inside of `onSelectRow`. Which way should use the user? Additionally you call `editRow` without calling `saveRow` on selection of another row (holding other changed **unsaved**). On the other side you want "1)inline update with message shown before update". Do you want to display messages only on clicking "Save Changed" button? In general "Save Changed" looks good. You wrote about "2)Multiple update". What is not working currently?
Comment: the code was written by someone other.....i found it and tried to manipulate it according to my needs, which i failed.....what i basically wants is 1)  before saving or updating anything either single or multiple row together  a confirmation dialog box should appear and 2) multiple update on single click ( save changes button) i.e if user edit many rows and want to save altogether (which is currently not working and it saves only alternate rows).
Answer: Free jqGrid supports a lot of callbacks, which will be used during saving the rows. You can use for example beforeSaveRow callback of inline editing, custom validation via editrules.custom callback function, beforeSelectRow and other. Additionally, your code seems to distinguish the initial empty value "" of ParameterValue column from any other values. The final code you should made yourself. I posted an example
beforeSelectRow: function (rowid) {
    // allow selection if saving successful
    var $self = $(this), i,
        savedRows = $self.jqGrid("getGridParam", "savedRow");

    for (i = 0; i < savedRows.length; i++) {
        if (rowid !== savedRows[i].id) {
            if (allowSaving.call(this, savedRows[i].id)) {
                $self.jqGrid("saveRow", savedRows[i].id);
            } else {
                $self.jqGrid("restoreRow", savedRows[i].id);
            }
        }
    }
    return true;
},

with allowSaving function defined as
var allowSaving = function (rowid) {
        var item = $(this).jqGrid("getRowData", rowid);
        if (item.ParameterValue !== "") {
            return confirm("Do you want to save \"" +
                        item.ParameterValue  + "\" value in \"" +
                        item.ParameterName + "\"?");
        } else {
            return false;
        }
    };

It allows to ask the user to confirm the changes of ParameterName. Additionally the code of "Save Changed" button should be adjusted too.
See https://jsfiddle.net/OlegKi/byygepy3/74/


How to play next file using Audio Queue Services

Question: What is the right way to play next file using Audio Queue Services? When "play next" button is pressed should I first call AudioQueueStop and then AudioQueuePrime/AudioQueueStart or it is enough to just fill buffers with next file data?
The problem is that the latter gives me sound glitches on iPhone.
Answer: Did you find a good solution?
You may have to reset the audio queue also, as the encoding might be different for each file.


How to replace large, original images used for image caching?

Question: All of the content types on my site allow users to upload up to 10 images. Each file is around 2 to 6 mb in original size.
I don't want to add another layer of complexity to their posting experience by enforcing that they use photoshop or some other software to 'format for web.' before uploading (which would be the case if I set the max file size to, 512k, for example).
Instead, how can I do like other services where you can upload whatever size and then the backend takes care of formatting them to a much smaller size for storage as well as the be the original that image caching uses for its work?
I see two ways of handling it:
write a module that understands when the file is saved and use PHP to reformat via its image functions, and then save that new file on the file system as well as be the source of any related image information needed in the database.
or, if the image data in the database is not dependent on the uploaded file size, etc, then why not just write an independed script to loop through all the images and reformat their sizes? Doesn't even have to be a module really.
Thoughts on the best way to do that?
Comment: or, maybe there is already a module for this? if so please share!
Answer: hook the image while finishing the upload process, then compress the size is a good Drupal approach much better than another batch job since the project can be managed in a good scope.
If it is a once-off task, script batch job is fast and efficiency but regarding the daily normal usage, a module is more preferable.
There is a module ImageAPI Optimize (or Image Optimize)
BTW, the theory could be:
Something like the following may be what you need:
<code>function MYMODULE_node_insert($node) {
</code>
// See if a file has been added
  if ($file_items = field_get_items('node', $node, 'field_file')) {
    // Get the first file item
    $file_item = array_shift($file_items);
<code>// Load the file object from the cache/database
$file = file_load($file_item['fid']);

// The path to the file is in $file->uri
do_something_with($file->uri);
</code>
}
}
REF: https://api.drupal.org/api/drupal/includes%21file.inc/group/file/7
Answer: Hi you can try this very helpful Module Original image with style
https://www.drupal.org/project/original_image_style


Limitar o valor máximo de um input number e ao mesmo tempo mostrar esse valor em um input text

Question: Tenho um formulário onde para cada tipo de despesa haverá um valor limite a ser enviado pelo usuário. O que estou utilizando no meu formulário é o tipo da despesa (sendo uma option), o valor da despesa a ser enviada pelo usuário (sendo um number) e usei um readonly com, por exemplo, "Limite de R$30".
O problema é que esse valor iria alterar conforme o usuário fosse mudando o tipo de despesa. Por exemplo:
Supondo que o usuário selecione despesa X que tem como limite R$20

Se ele selecionar essa despesa, só poderá colocar no campo de valor (que está habilitado pelo ) o máximo de R$20, mais do que isso irá ficar preenchido os R$20.

No meu código abaixo, fiz apenas o teste para que haja este campo onde o usuário não consegue alterar (no caso o "Limite de R$30").
<select name="tipoDespesa" required>
        <option value="" disabled selected>Tipo</option>
        <option>Almoço</option>
        <option>Jantar</option>

</select>
        <input type="number" name="precoDespesa" placeholder="R$" id="valor" step=".01" required placeholder="Insira um valor!">

<input type="text" name="limiteDespesa" id="limite" readonly value="Limite de R$30">

Comment: O que você quer é: mudar o valor do segundo input conforme o que for selecionado no select?
Comment: Sim, essa seria a primeira etapa. A segunda é que, de acordo com o valor do segundo input que vai ser alterado, eu não possa ultrapassar esse valor no primeiro input.
Comment: Isso não é uma questão relacionada ao php e sim a tecnologia front-end que você está usando. Qual seria essa? html/css/js/jquery/vue..?
Comment: eu estou utilizando o html para o formulário, e para os estilos o css. desculpe, sou iniciante, mas acho que é essa a resposta
Comment: Sugiro que dê uma olhada numa linguagem chamda javascript. _Com o JS, você pode mostrar mensagens e outras informações interessantes, fazer verificações ou mudar dinamicamente a apresentação visual das páginas, conforme o comportamento que você deseja que sua página (ou aplicação) possua._
Comment: Com javascript você consegue alterar facilmente os values e atributos do input
Comment: mas eu posso colocar direto no código embaixo algo com javascript? ou teria q refazer todo meu código...
Comment: Vai precisar de  jquery
Answer: Acredito que a melhor forma de fazer isso é com Javascript, pois com ele você pode pegar o evento de quando o usuário altera o tipo de despesa e usar para alterar valores de outros campo sem a necessidade de enviar para o servidor.
<select name="tipoDespesa" required>
<option value="" disabled selected>Tipo</option>
<option>Almoço</option>
<option>Jantar</option>

</select>
        <input type="number" name="precoDespesa" placeholder="R$" id="valor" step=".01" required placeholder="Insira um valor!">

<input type="text" name="limiteDespesa" id="limite" readonly value="Limite de R$30">

Caso não domine js para web segue alguns link que possa te ajudar.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement
https://www.w3schools.com/js/js_htmldom.asp
Answer: A solução completa passa por JQUERY
Ao selecionar uma option

o value do input text muda
o valor máximo para o input number muda
Ao submeter o formulário só é enviado se a condição max (valor máximo) for satisfeita

O atributo max especifica o valor máximo para um elemento <input>

 $( document ).ready(function() {

  $('.select').change(function (e) {
      var selectedIndex = $('select').prop("selectedIndex");
      var selectedOption = $('select').find("option")[selectedIndex];

      $('input[type=number]').attr('max', $(selectedOption).data('max'));

      $("#limite").val("Limite de R$" + this.value);

  });

 });

 <form>

 <select size="1" name="options" class="select">
   <option value="" disabled selected>Tipo</option>
   <option value="20" data-max="20">Almoço</option>
   <option value="30" data-max="30">Janta</option>
 </select>

      <input type="number" name="precoDespesa" placeholder="R$" id="valor" step=".01" required min="1" max="30">

<input type="text" name="limiteDespesa" id="limite" readonly value="Limite de R$30">

 <input type=submit>

 </form>


Service is not starting in Windows

Question: I have created an executable in Go and I am running it as a windows service.
I am using golang.org/x/sys/windows/svc package, and provide it with the Execute method which gets called by the SCM
<code>run := svc.Run
_ = run(svcName, &myservice{})

func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {

    changes <- svc.Status{State: svc.StartPending}

    go mainmethod()

    changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}

}
</code>
The service works most of the time but the problem is that whenever I restart my system, the service gives me a Error 1053 : "The service did not respond to start or control request in a timely fashion" error and does not start,
After adding the log statements in my run and Execute methods, I figured out that when the service starts without error the logs get printed, but when the services gives a 1053 error the SCM does not even invoke my exe, since none of the log statements get printed.
Has anyone tried creating a windows service in a similar way? Is it a problem with implementation or the windows svc package?
Comment: Does your Execute function have an empty body? If so, you need to send status updates to the system via the `changes` channel. Use the [svc service example](https://github.com/golang/sys/tree/master/windows/svc/example) as a base for your service.
Comment: no it does not, it sends data to SCM, my bad, i will add that code
Comment: Can you show `main.go` file and how you build it?
Comment: When I change the "Log On As" attribute of the Service to "administrator", the Service starts on windows reboot, It does not start for "Local System" or "Local Service". I know its not a good practice to have Service "RunAsAdministrator", what could be the issue here, why wont it accept "LocalSystem" user.
Answer: I have the GO exe deployed in Program Files, I changed the LogOnAs attribute of Windows Service to "Local Service" and gave "Local Service" complete Access to the installation folder in "Folder Security".
This seems to fix the issue for windows10. The service starts on windows restart, But this fix still does not work for windows 7 and windows8.
Edit:
Making the service "Automatic Delayed" works, however you have to wait for the service start after boot which takes 2-3 minutes.
The answer mentioned here helped: https://serverfault.com/questions/697608/automatic-windows-service-not-starting/697852#697852?newreg=788f7ab0bb084fec85d1ce2e51bf8317

Service is not starting in Windows


How to define in R the most important variables?

Question: I have a data set with my target gene and more than thousand transcriptional factors somehow correlated with this gene. There is data of  these factors in more than  70 variable conditions. What I'm looking to do is use CV to find most useful variables which correlate with my target gene. How could I do that in R please?
Comment: I'm used to 'CV' being used for 'coefficient of variation'; given the potential confusion, it's probably best to spell it out as 'cross-validation' the first time you use it. (Yes, I was able to work it out from your tags, but requiring readers to go tag hunting to resolve a confusion they may not even realize they have is not particularly comprehension friendly)
Answer: TL/DR:
CV won't help you with that, at least not directly. Make some model of the data and then use some feature selection algorithm, preferably all-relevant one, for instance RF-ACE or Boruta. And then validate it, possibly with CV.
Actual answer:
Let's start from the beginning.
So, you have some attributes (transcription factor levels) and one decision (likely the gene expression), and want to find attributes that are correlated -- ok, so the first approach is to actually calculate correlations and do some (multiple-testing resistant) test to find significant correlations. This is a somewhat trivial approach but people are doing it -- google for feature/gene selection filters and you'll find tons of algorithms with various adjustments, fixes and refinements.
But you can also step further and use a model of TF-gene iterations; if it should appear accurate, you can hope that the fact that it uses certain attributes means they are important in the original process.
Now, how to execute this? Depends on the model. If it is a statistical model (like lassoed robust regression or carefully pruned and refined tree) all you have to do is to dissect it and extract important features (base of the statistical modelling is to minimize parsimony of the model, so it shouldn't contain any noise).
If the model is an ML model (kNN, RF, SVM, GBM, ...; hopefully more sensitive and robust than statistical modelling/hypothesis-testing approach, but also more dangerous) you cannot directly infer anything from its black-box structure, you need some trick to extract this information. This trick is called either a feature selection wrapper or a feature selection embedded method; again, there are tons of them (many actually involve some cross-validation, and this is likely why you thought it is a good algorithm for this job), usually designed specifically for some modelling method.
Now, some of those methods are minimal-optimal, which aim in increasing model accuracy, and all-relevant, which aim at providing possibly complete subset of important features. The latter aim is more compatible with your aims, so you should use an algorithm from this class.
Finally, whatever method you use, you must validate its output to make sure it does not simply overfit (the more dimensional data you have it is more likely that noise will produce strong correlations at random, and FS is just great at inflating this effect). To this end, leave some data untouched for the whole analysis and use it to test the final model or (better) repeat this in a cross-validation fashion, also assessing stability of the feature selection output.
And be prepared for an option that your data is an unpublishable noise (;
Comment: Oh! Thank you very much for you exhaustive answer! It helped me a lot but still I am a little bit lost - because I am beginner. Are there any tutorials anywhere to use these methods..?


Should I discard a feature whose max - min is smaller than 1e-5?

Question: I'm training a neural network for regression. The input vector consists of $140$ entries.
For each feature vector entry, I calculate both min and max over the training set. The difference max-min of some entries are smaller than 1e-5. I understand I can normalize such feature entries by say MinMaxScalar. However, if the difference max-min is this small, can I discard such entries since they seem to be so insensitive?
Answer: You can't really know if they are 'insensitive' based on the magnitude of the values alone; it's the variation in the data that is relevant. It's entirely possible to have meaningful variation even when the magnitude is low. Since very small values sometimes lead to algorithmic problems, such features are frequently rescaled before use.
Of course, if you have practical reasons to expect that such a small range of values is not meaningful in your data, it would be reasonable to drop these features.
Comment: @meTchaikovsky That rather depends on your dataset and question. But the *covariance* between the feature in question (with low variation) and the variable you are trying to predict is frequently informative. For e.g., if lower values for the predictor corresspond to lower values in your variable of interest, the variable is probably informative even if the range is 1e-5 or lower.
Comment: @Hi, could you elaborate a little on what makes a variation meaningful? And how to detect it?


Python - Requests Failed to establish a new connection BCB

Question: I am trying to download this excel file https://www.bcb.gov.br/content/estatisticas/Documents/Tabelas_especiais/BalPagM.xlsx using the requests library.
When I open it in Google Chrome, it shows the following headers:
Request URL:
https://www.bcb.gov.br/content/estatisticas/Documents/Tabelas_especiais/BalPagM.xlsx
Request Method: GET
Status Code: 200
Referrer Policy: strict-origin-when-cross-origin

:Authority: www.bcb.gov.br
:Method: GET
:Path: /content/estatisticas/Documents/Tabelas_especiais/BalPagM.xlsx
:Scheme: https
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Accept-Encoding: gzip, deflate, br
Accept-Language: pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: no-cache
Pragma: no-cache
Sec-Ch-Ua: "Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/188.8.131.52 Safari/537.36

When I run it from my Python code, I keep receiving "Failed to establish a new connection".
import requests

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7',
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache',
    'Sec-Ch-Ua': '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
    'Sec-Ch-Ua-Mobile': '?0',
    'Sec-Ch-Ua-Platform': '"Windows"',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-User': '?1',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.96.36.199 Safari/537.36'
}

url = 'https://www.bcb.gov.br/content/estatisticas/Documents/Tabelas_especiais/BalPagM.xlsx'

response = requests.get(url, headers=headers)

To me, it seems that I am correctly setting all the headers. What am I missing here?
Comment: Just to set an answer here, the code was properly working. It was a firewall issue.
Answer: Your code is correct, but you're missing to write the fetched data into a file.
import requests

headers = {
    'host': 'www.bcb.gov.br'
}

url = 'https://www.bcb.gov.br/content/estatisticas/Documents/Tabelas_especiais/BalPagM.xlsx'

response = requests.get(url, headers=headers)
with open('BalPagM.xlsx', 'wb') as f:
    f.write(response.content)

Here, I am writing the response that is received from the request. I also updated the headers, since all of them weren't needed.
Answer: worked for me without headers.
import requests
from pathlib import Path

url = 'https://www.bcb.gov.br/content/estatisticas/Documents/Tabelas_especiais/BalPagM.xlsx'
filename = Path(url).name

response = requests.get(url)
print(response)
if response.ok:
    Path(filename).write_bytes(response.content)
else:
    print(response.reason)


How many convexly independent vectors there are in $\mathbb{R}^n$

Question: I know there are n linearly independent and n + 1 affinely independent vectors in $\mathbb{R}^n$. But how many convexly independent there are?
I think there are infinity number of them because if I have a convex polytope I can always add another point that is "outside" of said polytope.
But I'm not sure if my reasoning is correct.
Comment: What do you mean by convexly independent?
Comment: @gerw: https://en.wikipedia.org/wiki/Convex_position.
Answer: Your reasoning is almost but not quite correct. It's not enough that you can always add another point that's outside of said polytope – the resulting polytope also has to remain convex, i.e. each of the other points also has to be outside the polytope formed by the others. You can prove that, too, but it's a bit more involved – an easier proof would be to exhibit the corners of a regular $k$-gon for arbitrary $k$ as an example. This of course only works for $n\ge2$, and indeed for $n=1$ there are at most $2$ convexly independent points.
Comment: Or a sphere, to show uncountably many convexly independent vectors.
Comment: @jgon: Your name should be $\mathfrak c$gon :-)
Answer: No, your reasoning is not correct. If you add a new point outside the polytope, some of the vertices may become interior points of your new polytope. You have to ensure that all vertices remain vertices.
Answer: Consider the unit sphere in $\Bbb{R}^n$, $S^{n-1}=\{x : \|x\|=1\}$. I claim that the vectors in the unit sphere are convexly independent. To see this, it suffices to show that any vector is outside the convex hull of the others by symmetry. Choose the first basis vector, $e_1$. Suppose $e_1=\sum_{i=1}^r t_i v_i$ for $\sum t_i = 1$, and $v_i\in S^{n-1}$, $v_i\ne e_1$. We then look at the projection of this equation on the first coordinate. This gives $1=\sum_{i=1}^r t_i v_{i1}$. $v_{i1}< 1$ for all $i$ since $v_{i}\ne e_1$, and $\|v_{i}\|=1$. Then $1 < \sum_{i=1}^r t_i \cdot 1 =\sum_{i=1}^r t_i=1$. Contradiction.


What's the model representation for the first difference of a local level model?

Question: This is my first exercise for space state models and I've a few questions I'd need to resolve before I actually start doing the exercise. Unfortunately, I'm self teaching (I have no professor to ask) and I'm afraid there's no solution companion for Durbin and Koopman (2012)!

Exercise 2.13.1 from Time Series Analysis by State Space Methods Second Edition
Consider the local level model (2.3).
(a) Give the model representation for $x_t = y_t - y_{t-1}$, for $t = 2, ..., n$.
(b) Show that the model for $x_t$ in (a) can have the same statistical properties as the model given by $x_t = \epsilon_t + \theta \epsilon_{t-1}$ where $\epsilon \sim N(0, \sigma_{\epsilon}^2)$ are independent disturbances with variance $\sigma_{\epsilon}^2 > 0$ and for some value $\theta$.
(c) For what value of $\theta$, in terms of $\sigma_{\epsilon}^2$ and $\sigma_{\eta}^2$, are the model representations for $x_t$ in (a) and (b) equivalent? Comment.

For the record, the local level model (2.3) is given by:

$y_t = \alpha_t + \epsilon_t \quad\quad \epsilon_t \sim N(0, \sigma_{\epsilon}^2)$
$\alpha_{t+1} = \alpha_t + \eta_t \quad\quad \eta_t \sim N(0, \sigma_{\eta}^2)$

Doubts about (a)
First of all, the model proposed in (a) looks like noise (which makes perfect sense since it's the first difference of a random walk). Is the following representation correct?
$$ x_t = y_t - y_{t-1} = \alpha_t + \epsilon_t - \alpha_{t-1} - \epsilon_{t-1} $$
$$ x_t = \alpha_{t-1} + \eta_{t-1} + \epsilon_t - \alpha_{t-1} - \epsilon_{t-1} $$
$$ x_t = \eta_{t-1} + \epsilon_{t} - \epsilon_{t-1}  $$
This makes me doubt. First, state disturbance $\eta_{t-1}$ is now part of the observation equation. Second, what does the state equation mean now that the observation equation doesn't relate to the unobserved states $\alpha_t$? Third, and somehow related, what's the mean unobserved state now that $\alpha_t$ isn't anymore on the formula? Zero?
Doubts about (b)
Additionally, I wonder how to show that models have the same statistical properties. What do you have to prove to say they're the same? Same expected value and variance of observation $x_t$, unobserved state $\alpha_t$, prediction error $v_t = x_t - a_t $, filtered unobserved state, updated unobserved state, etc.? Since all random variables are Normal, I guess showing the first two moments match is enough, but a) what distribution (marginal, conditionals, conditionals on what?) of b) what variables (observed, hidden state, prediction error, etc.) should be equal?
Any comment is much appreciated!
Update
This is where I got after the hints provided by @Glen_b and @javlacalle.
(a)
$$ x_t = \eta_{t-1} + \epsilon_t - \epsilon_{t-1}$$
(b)
Respect to model $x_t$ given in (a)
$$ E[x_t | x_{t-1}] = 0 $$
$$ \gamma(0) = Var(x_t | x_{t-1}) = \sigma_{\eta}^2 + 2\sigma_{\epsilon}^2 $$
$$ \gamma(1) = Cov(x_t, x_{t-1}) = -\sigma_{\epsilon}^2 $$
$$ \gamma(2) = Cov(x_t, x_{t-2}) = 0 $$
$$ \rho(1) = \frac{-\sigma_{\epsilon}^2}{\sigma_{\eta}^2 + 2\sigma_{\epsilon}^2} $$
$$ \rho(2) = 0 $$
Respect to model $x_t$ proposed in (b), which I renamed to $z_t$ to avoid confusion
$$ E[z_t | z_{t-1}] = 0 $$
$$ \gamma(0) = Var(z_t | z_{t-1}) = \sigma_{\epsilon}^2 (1 + \theta^2) $$
$$ \gamma(1) = Cov(z_t, z_{t-1}) = \theta \sigma_{\epsilon}^2 $$
$$ \gamma(2) = Cov(z_t, z_{t-2}) = 0 $$
$$ \rho(1) = \frac{\theta}{1 + \theta^2} $$
$$ \rho(2) = 0 $$
(c)
$$ E[x_t | x_{t-1}] = E[z_t | z_{t-1}] = 0 \quad \qquad (c.1) $$
$$ \gamma_{x_t}(0) = \gamma_{z_t}(0) \leftrightarrow \sigma_{\eta}^2 + 2\sigma_{\epsilon}^2 = \sigma_{\epsilon}^2 (1 + \theta^2) \quad \quad (c.2) $$
$$ \gamma_{x_t}(1) = \gamma_{z_t}(1) \leftrightarrow -\sigma_{\epsilon}^2 = \theta \sigma_{\epsilon}^2 \rightarrow \theta = -1 \quad \quad (c.3) $$
$$ \gamma_{x_t}(2) = \gamma_{z_t}(2) = 0 \quad \quad (c.4) $$
$$ \rho_{x_t}(1) = \rho_{z_t}(1) \leftrightarrow \frac{-\sigma_{\epsilon}^2}{\sigma_{\eta}^2 + 2\sigma_{\epsilon}^2} = \frac{\theta}{1 + \theta^2} \quad \quad (c.5) $$
$$ \rho_{x_t}(2) = \rho_{z_t}(2) = 0 \quad \quad (c.6) $$
Equations c.1, c.4 and c.6 imply no restrictions for $\theta$, but equations c.2, c.3 and c.5 are clearly not consistent.
Comment: @Glen_b Thank you for pointing out the omission, I edited the question.
Comment: Your equation (c.2), (c.3) and (c.5) seem to be consistent, but implying that $\sigma^2_\eta=0$ and $\theta=-1$. But this, in terms of $q$ as in the answer by @javlacalle, means $q=0$ and not $q>0$...
Answer: Some explicit guidance and hints:
Your answer in (a) looks okay to me.
In (b) you would either need to go on and show the properties of the series $x_t$ (what's its ACF, say? What are the properties you need?) or to explicitly rewrite it in the form of an MA (which is easier, I think - you might just recast it as a transform to an MA in $\zeta$ say, $x_t=\theta(B)\,\zeta_t$, where $\zeta_t=...$).
Also I don't think you really need a state equation, so don't worry too much. You can always write a null one.
Comment: First of all, thanks for your time. 1) Since my state equation is null, should I remove too the state noise $\eta_{t-1}$? This noise comes from the state equation of the original model, and I don't see how I'd remove it. 2) Model (a) is MA(1) if I could remove state disturbance from the original model $\eta_{t-1}$ and I realise the model given in (b) is a plain MA(1), does this mean all I'd need is to cast model (a) as a MA(1) process and show they share the same variance $\sigma_{\epsilon}^2?
Comment: No, $\eta$ is still in the process, but you moved it to the observation equation. You can't eliminate it from both, and you don't need to.
Comment: ok, thank you for your input. I'll try to give it a try again tonight, when I get home. $\eta_{t-1}$ is the state disturbance for the original process $y_t$ and ended naturally in the observation equation for the new process $x_t$, I'll try to work this out from this observation equation $x_t = \eta_{t-1} + \epsilon_t - \epsilon_{t-1}$, having a null state equation $\alpha_t = 0$ (without noise) for the process.
Comment: Following your advice, I left the state noise from the original process $y_t$ in the observation equation from the new process $x_t$. Also, I computed expectation, autocovariance and autocorrelation for both processes to show they're statistically the same. Finally, I tried to find the conditions for equivalence, but constraints seem to be inconsistent. Looks like I have to improve something in the last part finish it.
Answer: You have arrived to the stationary form of the local level model:
$$
\Delta y_t \equiv x_t = \underbrace{\Delta \alpha_t}_{\eta_{t-1}} + \Delta \epsilon_t \,,
$$
where $\Delta$ is the difference operator such that $\Delta y_t = y_t - y_{t-1}$.
Now, I think it is easier to first check the statistical properties (mean, covariances, autocorrelations) of this stationary form.
For example, the mean of this process is given by:
$$
\hbox{E}[x_t] = \hbox{E}[\eta_{t-1}] + \hbox{E}[\epsilon_t] - \hbox{E}[\epsilon_{t-1}] = 0 + 0 - 0 = 0 \,.
$$
You can do the same to obtain the covariances of order $k$, $\gamma(k)$:
\begin{eqnarray}
\begin{array}{ll}
\gamma(0) &=& E\left[(\eta_{t-1} + \epsilon_t - \epsilon_{t-1})^2\right] = \dots \\
\gamma(1) &=& E\left[(\eta_{t-1} + \epsilon_t - \epsilon_{t-1})(\eta_{t-2} + \epsilon_{t-1} - \epsilon_{t-2})\right] &=& \dots \\
\gamma(2) &=& \cdots \\
\gamma(>2) &=& \cdots
\end{array}
\end{eqnarray}
You just need to take the expectation of the cross-products of all terms bearing in mind that $\eta_t$ and $\epsilon_t$ are independently distributed, they are independent of each other and the variance of each one are respectively $\sigma^2_\eta$ and $\sigma^2_\epsilon$.
Then, it will be straightforward to get the expression of the autocorrelations of order $k>0$, $\rho(k) = \frac{\gamma(k)}{\gamma(0)}$. This will have a form that is characteristic of a moving-average of order 1, MA(1) (the autocorrelations are zero for $k>1$) and, hence, $x_t$ can be represented as a MA(1) process and $y_t$ as an ARIMA(0,1,1) process.
In order to find out the relationship between the parameters of the local level model and the MA coefficient, you can equate the expression of the first order autocorrelation obtained before with the expression of the first order autocorrelation of a MA(1). Following the same strategy as above, you can find that $\rho(1)$ for a MA(1) with coefficient $\theta$ is given by $\rho(1) = \theta/(1 + \theta^2)$. The expression that you get by doing this will also reveal that the local level model is a restricted ARIMA(0,1,1) model where the MA coefficient $\theta$ can take only negative values.
Edit
Equation (c.5) is okay. You can get the relationship between the parameters of the local level model and the MA coefficient solving the equation (c.5) for $\theta$. You can rewrite it as a quadratic equation to be solved for $\theta$. One of the solutions can be discarded because it implies a non-invertible MA, $|\theta|>1$.
When solving this equation, it will be helpful to define $q=\sigma^2_\eta/\sigma^2_\epsilon$. Also, check that $\frac{\sqrt{\sigma^4_\eta + 4\sigma^2_\eta\sigma^2_\epsilon}}{2\sigma^2_\epsilon} = \frac{\sqrt{q^2 + 4q}}{2}$. This way you will get a more neat expression. Then, given that $0 < q < \infty$, you can check that the range of possible values for $\theta$ are zero or negative values.
Comment: Thanks for your help, I could get a better idea of what I should been doing after reading your hints a couple times. I edited the question with more details, and now I only need to compute the restrictions for $\theta$, which are inconsistent so far.
Comment: Thanks for your new comments, they look clear so far. I'll try to finish it tonight, hope this time I can finally tackle the exercise!


Convert pandas dataframe rows to list

Question: I have a data frame with records as below, for all the rows succeeding id until there is a not null value for id, the value should get appended as a list.
[{'id': 'a', 'value': 1},
 {'id': nan, 'value': 2},
 {'id': nan, 'value': 3},
 {'id': 'b', 'value': 4},
 {'id': nan, 'value': 5},
 {'id': nan, 'value': 6},
 {'id': 'c', 'value': 7},
 {'id': nan, 'value': 8},
 {'id': nan, 'value': 9}]

I wan the output as,
id value
a  [1,2,3]
b  [4,5,6]
c  [7,8,9]

Tried method:
df.groupby('id')['value'].agg(list)
Comment: So what have you done so far to get this result? Where do you think the error is? What is the [mre] that you can provide that will help us start to help you fix it?
Answer: First forward filling missing values and then aggregate lists:
df = df.groupby(df['id'].ffill())['value'].agg(list).reset_index()
print (df)
  id      value
0  a  [1, 2, 3]
1  b  [4, 5, 6]
2  c  [7, 8, 9]

Convert pandas dataframe rows to list


Prove that $\ln x \leq x^{\alpha}$ for large x and that there exists a constant $c$ such that $\ln x \leq c x^{\alpha}$ $\forall x\in [1,\infty)$

Question: Question: Assume $(\ln x)' = \frac1x$, $(x^\alpha)' = \alpha x^{\alpha-1}$ for all $x>0$, $\ln(e^x)=x$ and that $\alpha>0$.

Prove that $\ln x \leq x^\alpha$ for large x.
Prove that there exists a constant $c_\alpha$ such that:
(a) $\ln x \leq c_\alpha x^\alpha$ for all $x \in [1,\infty)$
(b) $c_\alpha \rightarrow \infty$ as $\alpha \rightarrow 0^+$
(c) $c_\alpha \rightarrow 0$ as $\alpha \rightarrow \infty$

Attempt:

Consider $f(x) = \frac{\ln x}{x^\alpha}$. Then $$\lim\limits_{x\to\infty}f(x) \stackrel{\text{L'H}}{=} \lim\limits_{x\to\infty}\frac{1}{\alpha x^\alpha}=0.$$ This implies that $x^\alpha$ grows at a faster rate than $\ln x$. Therefore, $\ln x \leq x^\alpha$ for large x.
I'm thinking that if a function is greater than another, then the derivative of the larger function should be greater than (or equal to) the derivative of the smaller function as x gets large. Therefore, taking the derivatives and solving for x we get: $$\frac1x = \alpha x^{\alpha-1} \Rightarrow x = \left( \frac1\alpha \right)^{\frac1\alpha}.$$
So I thought I should let $c_\alpha = \left( \frac1\alpha \right)^{\frac1\alpha} - 1$ so that it satisfies conditions b and c, but it does not satisfy condition a. I need a hint.
Comment: Your statement (2) is not correct.  For example if $f(x)=x+x^{-1}$ and $g(x)=x$ then $f(x)>g(x)$ for all $x>0$, but $f'(x)<g'(x)$.  Draw graphs of $f$ and $g$ on the same axes and you will understand what is happening here.
Comment: @David: Thanks. I am looking at a graph of both functions. $f'(x) \rightarrow g'(x)$ as $x \rightarrow \infty$. This was the kind of idea I thought would be useful.
Answer:
PRIMER:
In THIS ANSWER, I showed using only the limit definition of the exponential function and Bernoulli's Inequality that
$$\bbox[5px,border:2px solid #C0A000]{\frac{x-1}{x}\le \log(x)\le x-1 }\tag 1$$
for $x>0$.
Aside, I showed in THIS ANSWER, using elementary (pre-calculus) tools, that for all positive integers, $\log(n) \le \sqrt{n}$.  In fact, $\log(x)\le \sqrt{x}$ for all $x>0$.

Note that $\log(x)\le x-1<x$ for $x>0$.  Then, $\alpha \log(x)=\log(x^\alpha)\le x^\alpha$.  If $\alpha >0$, then we have
$$\log(x)\le \frac{x^\alpha}{\alpha}$$
And we are done!
Comment: Yes, if $f>0$, then $\log(f)\le f-10$.
Answer: Hint.  Use differentiation to show that
$$f(x)=\frac{\ln x}{x^a}$$
has a maximum value of $\dfrac1{ae}$.


How to make view to group by only one field?

Question: I have a view with multiple fields and the fields have multiple values, so I get many duplicates in results.
When I try to use distinct, nothing happens, because select distinct does not affect on multiple values. I have predictable, but non desired result.
When aggregation is disabled I don't have any "groupby" directives in resulting SQL.
When I enable aggregation, I see in resulting SQL the following:
GROUP BY field_data_field_tour_short_name_node_entity_type,
field_data_field_tour_short_name_field_tour_short_name_value, node_title,
nid_1, field_data_field_arr_dates_node_entity_type,
field_data_field_arr_dates_field_arr_dates_value,
field_data_field_tour_duration_node_entity_type,
field_data_field_tour_duration_field_tour_duration_tid,
field_data_field_tour_minimal_price_node_entity_type,
field_data_field_tour_minimal_price_field_tour_minimal_price

So, as you can see, I have ALL the fields in my view.
When I disable aggregation and try to use hook_views_query alter
$query->add_field('node', 'nid', 'nid', array('function' => 'groupby'));
$query->add_groupby('node.nid');

I get the following:
GROUP BY node.nid, field_data_field_tour_short_name_node_entity_type,
field_data_field_arr_dates_node_entity_type,
field_data_field_tour_duration_node_entity_type,
field_data_field_tour_minimal_price_node_entity_type

As you can see, I get less fields, but not one.
But I need simply:
GROUP BY node.nid

How can I get grouping by only on field instead of many?
UPDATE: I found the following strings in views_plugin_query_default.inc
$groupby = array_unique(array_merge($this->groupby, $non_aggregates));
  foreach ($groupby as $field) {
    $query->groupBy($field);
  }

So views for some reason add other fields to groupby if groupby is present.
How to avoid this adding? I could change the file, but this is not proper way.
Comment: You are using aggregation incorrectly. To collapse seemingly similar rows into 1 row you need to group on a common field value unique to that group and set it to group on COUNT (or SUM/MIN/MAX) and then hide that from display. For the rest of the fields you just leave the aggregation at default. And remove all sorting at first and only when you are happy with aggregation you add the sorting in.
Answer: I had the same problem.
Try to implement the group by in hook_views_pre_execute, it's work for me.
function MYMODULE_views_pre_execute(&$view){
  if ($view->name == 'YOUR_VIEWS' &&  $view->current_display == 'SOME_DISPLAY') {
    $view->build_info['query']->groupBy('node.nid');
  }
}

If you are using a pager, updating $view->build_info['count_query'] with the same changes should keep the pager consistent with the query results.
Comment: Perfect, but views pager is not correct!
Answer: You can unset the fields that you are not interested in. This code works for me, in hook_query_alter:
    if ($query->hasTag('views_' . $view_name)) {
        $fields =& $query->getGroupBy();
        unset($fields['item_id']);
        unset($fields['field_data_field_field_rf_product_node_entity_type']);
        $query->groupBy('field_oem_ubication_field_collection_item__field_data_field_');
        $query->groupBY('taxonomy_term_data_field_data_field_brand_name');
    } // if

As you can see, I add some fields ( $query->groupBy ) and unset others.
Comment: I need all fields in results but I want to group by only one field. If I unset some fields, they will be not selected
Comment: I am not sure, but I think that only the fields inside groub by are affected, not those which are selected. I will try to check it up further.
Comment: I am also facing the exact same issue. Any updates? @SergeyKravchenko If you have found a solution, please update here so we can be benefitted.
Comment: I think that you can set the "group by" field in the Admin panel. See image in my (edited) reply. If you uncheck, you will not group by the field. There is no need to do unset in the hook.
Answer: A screenshot would be really beneficial here as I'm getting it hard to visualise the problem. But generally, hiding the field you want to group by and then grouping by it is the general way to go.
https://www.drupal.org/project/views_merge_rows is also a bit of an alternative to aggregate.
Anyways, just throwing out ideas cause no one else has answered.


@media entrando em conflito

Question: Olá, gostaria de saber o motivo do por quê alguns comandos que pertencem a um @media específico, estarem influenciando e alterando o mesmo comando em um @media diferente. Por exemplo, quando coloco um "width: 30%" em alguma foto no @media (min-width: 1200px), ele altera o tamanho dessa mesma foto também no @media (min-width: 1500px). Descobri que em alguns casos, o problema é resolvido caso eu coloque um !important no elemento do @media afetado, mas isto nem sempre resolve. Estou organizando o CSS da seguinte forma:

Desktops-1 (min-width: 1500px);
Desktops-2 (min-width: 1200px); e
Tablets-1 (min-width: 1000px).

Pretendo continuar colocando mais resoluções específicas para responsivisar, mas este bug está atrapalhando.
Comment: Vai depender dos seletores que usa e da ordem que aplica, sem ver o seu CSS e os seletores que esta usando não temos como responder, você deveria fornecer um exemplo PRONTO que possamos testar para podermos lhe ajudar.
Comment: Seu problema está explicado nessa resposta https://pt.stackoverflow.com/questions/351972/media-queries-n%C3%A3o-funciona-medidas-informadas/351977#351977 na sua folha de CSS primeiro deve vir o 1000px, depois os estilos do 1200 e no final os do 1500 e assim por diante, no link tem mais detalhes
Comment: @hugocsl pode ser também, ou pode ser somente a ordem ou prioridade de seletores, não tem como afirmar nada, não tem código na pergunta.
Answer: Você está usando min-width: por exemplo um aparelho com resolução de 1500px entrará em todas as validações anteriores, exemplo min-width: 700px, min-width: 1200px,etc.
Você pode arrumar isso de duas maneiras usar o max-width: 700px, e ir limitando por aparelho que contém a resolução até a resolução determinada.(Eu uso assim e dispenso o min-width).
Ou combinar as duas opções exemplo: (min-width: 768px) and (max-width: 979px) aí você garante aparelhos de resolução entre 768px a 979px(substitua pelos valores que melhor lhe atender)
Comment: obrigado, tentei aqui e deu certo

@media entrando em conflito


Adding items to another Modules Admin form

Question: I have a module that I need to add a few items to, I was told that using hook_form_alter was
the best way to do this, but have been completely unable to get anything to work. Maybe some
one could help me out on it a bit....
The PURPOSE of this enhancement is to add text and links to a login modal, but that's unimportant
at the minute.
The code that I have in my module atm is just to show the form I'm trying to alter
<?php
/**
 * Implements hook_menu_alter().
 */

function [modulename]_enhancements_menu_alter(&$items) {
  $form['modal_window'] = array(
    '#type' => 'fieldset',
    '#title' => t('Modal text and links'),
    '#collapsible' => TRUE,
    '#collapsed' => 0,
    '#weight' => -399,
  );

    $form['modal_window']['login'] = array(
      '#type' => 'text_format',
      '#format' => 'plain_text',
      '#title' => t('Login text'),
      '#default_value' => variable_get('[modulename]_login_text', '[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis a arcu et sem pharetra consectetur. Proin eget lectus neque, quis suscipit lectus. Nullam dictum, massa at sodales porttitor, mi nisi fermentum magna, eu suscipit dui. ]'),
    );

    $form['modal_window']['registration'] = array(
      '#type' => 'text_format',
      '#format' => 'plain_text',
      '#title' => t('Registration text'),
      '#default_value' => variable_get('[modulename]_registration_text', '[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis a arcu et sem pharetra consectetur. Proin eget lectus neque, quis suscipit lectus. Nullam dictum, massa at sodales porttitor, mi nisi fermentum magna, eu suscipit dui.]'),
    );
}
?>

The module has something like this going on with it
<?php
/**
 * Implements hook_menu().
 */
function [modulename]_menu() {
  $items['admin/config/services/[modulename]'] = array(
    'type' => MENU_NORMAL_ITEM,
    'title' => '[modulename] Settings',
    'access arguments' => array('administer [modulename]'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('[modulename]_admin_form'),
    'description' => '[modulename] Configuration.',
    'file' => '[modulename].admin.inc',
  );
?>

and here's the [modulename].admin.inc
<?php
/**
 * Form builder for the [modulename] administration form.
 */
function [modulename]_admin_form($form, &$form_state) {
  global $user, $base_path;
  include_once DRUPAL_ROOT . '/' . 'modules/user/user.pages.inc';
  module_load_include('inc', '[modulename]');
  $capabilities = [modulename]_get_capabilities();
  $form = array();

   $form['[modulename]_debug'] = array(
    '#type' => 'checkbox',
    '#title' => t('[modulename] debuging'),
    '#description' => t('Write errors to watchdog'),
    '#default_value'=> variable_get('[modulename]_debug', 0),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#weight' => -401,
  );
?>

Comment: Can you tell us what you've tried? Hook form alter should work fine. Is this D7 or D6? If you really just want to add some text, you can always just theme it, or you want the user to be able to customize the text?
Answer: For the sake of clarity, let's say that your custom module is named CUSTOMMODULE, and the one you want to alter is ALTERTHIS.
You can use hook_form_FORM_ID_alter() like this:
/**
 * Implements hook_form_FORM_ID_alter() for ALTERTHIS_admin_form().
 */
function CUSTOMMODULE_form_ALTERTHIS_admin_form_alter(&$form, &$form_state, $form_id) {
  // Alter the $form here.
}

Comment: If you don't know the form id, you can use `hook_form_alter()` to easily get a list of all the form id's on a given page too. From there it's usually pretty easy to guess which one is the one you want.
Comment: I ended up with function [modulename]_enhancements_form_[modulename]_admin_form_alter(&$form, &$form_state) { /* data */