Sum the grouped results in the template

Question: I have an aggregated view result grouped by taxonomy terms and shown like the following.

TaxonomyTerm1
1
1
TaxonomyTerm2
1
TaxonomyTerm3
1
1
1

I want the result to be added and shown like the following.

TaxonomyTerm1
2
TaxonomyTerm2
1
TaxonomyTerm3
3

I tried to calculate the result in views-view-fields--reports.html.twig file with the following code.
<code>{% set total = 0 %}
{% for field in fields -%}
  {% set total = total + 1 %}
{%- endfor %}
{{ total }}
</code>
Instead of the expected result, I get the original values again.
Answer: I have solved the problem with using View Aggregator Plus module. These are the settings I used on Views > View Aggregator Plus Module > Style > Settings.

For the taxonomy column

In Apply group functions for the taxonomy column the result must be grouped by, select the Group and compress option
In the Render column section, select the taxonomy column you want to shown as label

For the total number column

In Apply column function, select Count (having regexp) *
In the Render column section, select the title, for example as a field, because any field that repeats will be counted as total number with these options

To make it clearer, these are my fields.

TaxonomyColumn (which is being grouped by)
Title (the titles for the nodes with  the taxonomy column)

Most importantly, make sure the default aggregation is disabled. It is by default, since the View Aggregator Plus module provides many aggregation options.

Sum the grouped results in the template


Multiple RewriteRules for single RewriteCond

Question: i have this code
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_HOST} ^domain\.com:8080
RewriteRule ^ http://www.domain.com:8080%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^(www\.)?domain\.com:8080$ [NC]
RewriteCond %{HTTP_HOST} ([a-zA-Z0-9-]+)\.domain\.com:8080$ [NC]
RewriteRule ^([A-Za-z0-9-]+)/([0-9-]+)/?(.*)?\.html$ view.php?prefix=%1&cat=$1&id=$2&title=$3 [L,QSA]

RewriteCond %{HTTP_HOST} !^(www\.)?domain\.com:8080$ [NC]
RewriteCond %{HTTP_HOST} ([a-zA-Z0-9-]+)\.domain\.com:8080$ [NC]
RewriteRule ^([A-Za-z0-9-]+)/?((index|news|photos|videos|articles)\.html)?$ categories.php?prefix=%1&cat=$1 [L,QSA]

RewriteCond %{HTTP_HOST} !^(www\.)?domain\.com:8080$ [NC]
RewriteCond %{HTTP_HOST} ([a-zA-Z0-9-]+)\.domain\.com:8080$ [NC]
RewriteRule ^(index\.html)/?$ category_index.php?prefix=%1 [L,QSA]

RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com:8080 [NC]
RewriteRule  .?  -  [S=3]
RewriteRule ^(tube|login|register|facebook|logout)\.html$ $1.php [L,QSA]
RewriteRule ^page/([A-Za-z0-9-]+).html$ page.php?prefix=$1
RewriteRule ^sitemap\.xml sitemap.php [QSA,L]

</IfModule>

i want login.html and all sisters open only on www.domain.com/login.html and give 404 error if opened on games.domain.com/login.html
and also RewriteRule  .?  -  [S=3] not work for me, i'm tried to do
RewriteCond %{HTTP_HOST} !^(www\.)?domain\.com:8080$ [NC]
RewriteCond %{HTTP_HOST} ([a-zA-Z0-9-]+)\.domain\.com:8080$ [NC]
RewriteRule  .?  -  [S=3]
RewriteRule ^([A-Za-z0-9-]+)/([0-9-]+)/?(.*)?\.html$ view.php?prefix=%1&cat=$1&id=$2&title=$3 [L,QSA]
RewriteRule ^([A-Za-z0-9-]+)/?((index|news|photos|videos|articles)\.html)?$ categories.php?prefix=%1&cat=$1 [L,QSA]
RewriteRule ^(index\.html)/?$ category_index.php?prefix=%1 [L,QSA]

its not working here and here
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com:8080 [NC]
RewriteRule  .?  -  [S=3]
RewriteRule ^(tube|login|register|facebook|logout)\.html$ $1.php [L,QSA]

Answer: This condition is wrong:
RewriteCond %{HTTP_HOST} !^(www\.)?domain\.com:8080 [NC]

As you can only match host name using HTTP_HOST variable without port. To make it work use this compound condition:
RewriteCond %{HTTP_HOST}:%{SERVER_PORT} !^(www\.)?domain\.com:8080$ [NC]


Automatically create Timer in Netbeans

Question: I am creating a school web application that gets information from a MySQL database. I want the back-end to regularly delete entries with time stamps that have already expired in the database.
From what I researched, I created a TimerSessionBean with the Schedule annotation for every hour to delete entries from the database. For testing sake, right now I am simply trying to get the bean to print something ever 5 minutes. This is what I have so far:
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import java.util.Date;

@Stateless
public class TimerSessionBean {

    @Schedule(minute = "*/5")
    public void PrintTime() {
        System.out.println("Current: " + new Date());
    }
}

However, nothing happens when I deploy my application. Is it not enough to just create the TimerSessionBean and include the Schedule annotation?
Answer: TimerSessionBean is a singleton session bean that shows how to set both an automatic timer and a programmatic timer.
In the source code listing of TimerSessionBean that follows, the setTimer and @Timeout methods are used to set a programmatic timer.
A TimerService instance is injected by the container when the bean is created. Because it's a business method, setTimer is exposed to the local, no-interface view of TimerSessionBean and can be invoked by the client.
In this example, the client invokes setTimer with an interval duration of 30,000 milliseconds.
The setTimer method creates a new timer by invoking the createTimer method of TimerService.
Now that the timer is set, the EJB container will invoke the programmaticTimeout method of TimerSessionBean when the timer expires, in about 30 seconds.
Using the timer service
package timersession.ejb;

import java.util.Date;
import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;

@Singleton
public class TimerSessionBean {
    @Resource
    TimerService timerService;

    private Date lastProgrammaticTimeout;
    private Date lastAutomaticTimeout;

    public void setTimer(long intervalDuration) {
        System.out.println("Setting a programmatic timeout for "
                + intervalDuration + " milliseconds from now.");
        Timer timer = timerService.createTimer(intervalDuration,
                "Created new programmatic timer");
    }

    @Timeout
    public void programmaticTimeout(Timer timer) {
        this.setLastProgrammaticTimeout(new Date());
        System.out.println("Programmatic timeout occurred.");
    }

    @Schedule(minute="*/5", hour="*")
    public void automaticTimeout() {
        this.setLastAutomaticTimeout(new Date());
        System.out.println("Automatic timeout occured");
    }

    public void setLastProgrammaticTimeout(Date lastTimeout) {
    this.lastProgrammaticTimeout = lastTimeout;
    }

    public void setLastAutomaticTimeout(Date lastAutomaticTimeout) {
    this.lastAutomaticTimeout = lastAutomaticTimeout;
    }
 [...]

To see the output JAVA Console must be open.
Comment: Thank you for the info, but is there a way to to get it to print without having the client invoke the timer? I need to have the back-end regularly remove stuff from the database regardless of anyone using the web application.
Comment: Do it outside of netbeans. Deploy it with the admin console (4848)  and start the server with auto start when booting the computer.
Comment: I see, so there is no way for the timer to automatically start. But what about your automaticTimeout method? My understanding is if you give the Schedule annotation, it should immediately start the timer when you deploy the project.

Automatically create Timer in Netbeans


Couldn't work ccxt package

Question: I'm a beginner.
I have a problem in google Cloud Functions service. I want to use ccxt python package but from this week it couldn't deploy my python program. In cloud Functions log page

Traceback (most recent call last): File "/layers/google.python.pip/pip/bin/functions-framework", line 8, in  sys.exit(_cli()) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/click/core.py", line 829, in call return self.main(*args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/click/core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/functions_framework/_cli.py", line 37, in _cli app = create_app(target, source, signature_type) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/functions_framework/init.py", line 172, in create_app spec.loader.exec_module(source_module) File "", line 783, in exec_module File "", line 219, in _call_with_frames_removed File "/workspace/main.py", line 2, in  import ccxt File "/layers/google.python.pip/pip/lib/python3.8/site-packages/ccxt/init.py", line 29, in  from ccxt.base.exchange import Exchange # noqa: F401 File "/layers/google.python.pip/pip/lib/python3.8/site-packages/ccxt/base/init.py", line 24, in  from ccxt.base import exchange File "/layers/google.python.pip/pip/lib/python3.8/site-packages/ccxt/base/exchange.py", line 40, in  from ccxt.static_dependencies import ecdsa File "/layers/google.python.pip/pip/lib/python3.8/site-packages/ccxt/static_dependencies/ecdsa/init.py", line 1, in  from .keys import SigningKey, VerifyingKey, BadSignatureError, BadDigestError File "/layers/google.python.pip/pip/lib/python3.8/site-packages/ccxt/static_dependencies/ecdsa/keys.py", line 3, in  from . import ecdsa File "/layers/google.python.pip/pip/lib/python3.8/site-packages/ccxt/static_dependencies/ecdsa/ecdsa.py", line 56, in  from six import int2byte, b ModuleNotFoundError: No module named 'six'

so I wonder this problem from ccxt but couldn't solve it...
Comment: Do you have package `six` in `pip list`?
Answer: Have you tried to install six?
<code>pip3 install six
</code>

Couldn't work ccxt package


How can I highlight library classes differently in Intellij Idea?

Question: I'm trying to configure IntelliJ Idea to highlight classes from the current project and classes from libraries/JDK differently. That would help to easily understand origin of all these classes like Transaction, Request, Query, Column. Also, during debugging, it would allow to step only into lines with code from project (it is usually much more buggy and suspicious).
Yes, I know about Ctrl+hover on symbol/ Ctrl+Q / Smart step into. But visual indication may be much easier to recognize.
Is there a way to get that (maybe with some plugin)?
Answer: It might not be exactly what you're asking but it's very similar and could help with differentiating library and project files.

Project Files - that's your source code, etc
Non-Project Files - files that are from Jar files
Comment: Yes, that is close. Thanks. Maybe somebody will post some workaround for in-text highlighting.


Tem alguma forma de Pegar o caminho completo para importar um Arquivo csv?

Question: Como descrito no título da minha dúvida, gostaria de saber se tem alguma forma de pegar como parametro o caminho ate um arquivo csv, no caso eu preciso desse caminho para importar automaticamente o arquivo.
Minha tentativa de fazer isso é essa.
form
<%= form.file_field :file %>

Esse input que estou usando para pegar o arquivo e o simbolo :file como parametro para retornar o caminho.
users_controller
def create
@user = User.new(user_params)
binding.pry

require 'csv'

CSV.foreach(@user.file, col_sep: ',').with_index do |l, i|
  unless (indice == 0)
    User.create!(name: l[0], email: l[1], address: l[2])
  end
end

respond_to do |format|
  if @user.save
    format.html { redirect_to @user, notice: 'User was successfully created.' }
    format.json { render :show, status: :created, location: @user }
  else
    format.html { render :new }
    format.json { render json: @user.errors, status: :unprocessable_entity }
  end
end

end
Usei o Binding.pry para mostrar o resultado que esta me retornando, e também o motivo da minha pergunta. Quando vou verificar os parametros que veio para o user_params é mostrado esse tipo de informação:
<ActionController::Parameters {"file"=>#<ActionDispatch::Http::UploadedFile:0xb454db98 @tempfile=#<Tempfile:/tmp/RackMultipart20190710-3063-2ah7nt.csv>, @original_filename="users.csv", @content_type="text/csv", @headers="Content-Disposition: form-data; name=\"user[file]\"; filename=\"users.csv\"\r\nContent-Type: text/csv\r\n">} permitted: true>

OK. Agora vou mostrar o o que tem dentro do parametro file quando eu executo @user.file no console do pry.
"#<ActionDispatch::Http::UploadedFile:0xb454db98>"

Muito bem, eu gostaria de saber se tem uma forma de retornar o caminho até o arquivo ou converter esse "#<ActionDispatch::Http::UploadedFile:0xb454db98>" no caminho ate o arquivo.
Answer: Vc chegou perto, usando o proprio pry, vc consegue "entrar" nos objetos, como se fossem diretórios.
Vc poderia ter feito cd @user.file e lá ter dado um ls.
Vc veria os métodos que o objeto tem, entre eles o path que faz o que vc quer:
https://api.rubyonrails.org/classes/ActionDispatch/Http/UploadedFile.html#method-i-path


Other forms does not work after redirect from Servlet

Question: So, I'm currently trying to learn some JSP, and I can't figure out how to get around this problem I'm having.
Currently, I have an index.jsp page with several forms. For one form, it has two text fields that it sends to a servlet, test.java, in order to build a string. After building the string, the servlet then redirects back to index.jsp
Original index.jsp address:
     http://localhost:8080/TestJSPConversion/
After the redirect, the address is
     http://localhost:8080/TestJSPConversion/test
The problem comes up when I try to use another form on index.jsp, it then takes me to a blank page at the address,
     http://localhost:8080/TestJSPConversion/test?author=Peter+Johnson
I believe it's due to the method I'm using to redirect from the servlet (request.getRequestDispatcher("/index.jsp").forward(request, response);
but, I'm not too sure how to fix this issue. I would like to get the form to work even after the servlet redirects back to index.jsp.
Servlet Code:
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    // Get parameters from the request.
    String name = request.getParameter("name");
    String email = request.getParameter("email");

    String message = null;
    GregorianCalendar calendar = new GregorianCalendar();
    if (calendar.get(Calendar.AM_PM) == Calendar.AM) {
        message = "Good Morning, ";
    } else {
        message = "Good Afternoon, ";
    }
    message += name + " with the email, " + email;

    request.setAttribute("message", message);
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

Index.jsp Code:

Choose authors:

<form method="get">
    <input type="checkbox" name="author" value="Tan Ah Teck">Tan
    <input type="checkbox" name="author" value="Mohd Ali">Ali
    <input type="checkbox" name="author" value="Kumar">Kumar
    <input type="checkbox" name="author" value="Peter Johnson">Peter
    <input type="submit" value="Query">
</form>

<c:set var="authorName" value="${param.author}" />

<c:if test="${not empty authorName}">
    <c:out value="${authorName}" />
</c:if>

<form  action="test" method="POST">
    First Name: <input type="text" name="name" size="20">

    Surname: <input type="text" name="email" size="20">

    <input type="submit" value="Submit">
</form>
<c:out value="${message}" />

Comment: when you submit other form , do they have action="someServlet" where someServlet is an existing servlet ??
Comment: The other form just grabs the author name from the checkboxes and displays it, so it does not.
Answer: try response.sendRedirect("index.jsp?message=hello"); and display it using ${param.message} (EL). If you are using method as post in <form  action="test" method="POST">, then you have to write the code in the doPost method.
Comment: Visruth, you are a hero.
Answer: set action="test" for other <form> also.
if this leads you to some url like domain/TestJspConnection/test/test... then try action="/TestJSPConnection/test" as your <form> attribute
Oh yes, didn't notice this at all!...You didn't implement doGet() in your sevlet...so <form method="get" > is landing you on blank page
so..two solutions:
1) implement doGet() in servlet
or
2) set method="post" for first form
Comment: Implementing this still leads me to a blank page though. For example, clicking on Kumar gives me the address                         http://localhost:8080/TestJSPConversion/test?author=Kumar
Answer: First : you only implement the doPost so your first Form with method=Get will prob. fail.
Second : you should use sendRedirect instead of forward.  this way if yo hit refresh on the browser, you will not get the warning about reposting data!  Always better to sendRedirect when the server process is done and you want to display the result in a JSP.
regards


Proving a topological space is separable

Question: I am trying to prove the following statement:
Prove that if (X,d) is a compact metric space, then X must be separable.
Where separable means the following: We say a topological space is separable if it has a countable dense subset.
I think the strategy behind this would be to use the fact that a compact metric space is sequentially compact, meaning that every sequence in X has a convergent sub sequence in X (use this to prove the limit point p to which such sub sequence converges to is also in X. This making X dense).
I am uncertain of how to prove the countability of such set. I was thinking about using the set:
{{B(x,d) | x is an element of X}}
Extracting a finite subcover and constructing a subset contained in X by removing a particular open ball Bi(x,d). I am not sure as to whether or not the balls are countable sets themselves.
I really appreciate you taking the time to read through and help :)
Answer: Looking at covers by open balls is a good idea, but not in quite the manner that you seem to have in mind. For $n\in\Bbb Z^+$ let
$$\mathscr{U}_n=\left\{B\left(x,\frac1n\right):x\in X\right\}\;;$$
this is an open cover of $X$, so it has a finite subcover $\mathscr{V}_n$. This means that there is a finite $F_n\subseteq X$ such that
$$\mathscr{V}_n=\left\{B\left(x,\frac1n\right):x\in F_n\right\}\;;$$
Now see what you can do with the set $D=\bigcup_{n\in\Bbb Z^+}F_n$.


How to load databases with linked tables using Microsoft DAO 3.6 object library (dao360)

Question: We've reached the 2Gb limit with our current MS Access database (see general section of https://support.office.com/en-us/article/access-specifications-0cf3c66f-9cf2-4e32-9568-98c1025bb47c). This page suggests "linking to tables in other Access databases. You can link to tables in multiple database files, each of which can be as large as 2GB."
We've set this up in MS Access and the linked table opens fine in MS Access. However, the linked table is not happy to open in our software, which is using Microsoft DAO 3.6 object library (dao360).
Is there anything special that is required to open a linked table in this way? I've tried adding both databases to the workspace (along the lines of https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/workspace-opendatabase-method-dao), but this doesn't seem to help (or at least I'm not doing it right). The error I get back when opening the linked table (using the Database.OpenRecordset method is simply "invalid operation".
Apologies for my ignorance, this database code has been here many years before I joined and I've never had to go near it until now!
UPDATE
I can make some progress by specifying dbOpenDynaset as the parameter of Database.OpenRecordset method (https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/database-openrecordset-method-dao) as per this SOF post. However, it then fails later when calling RecordSet.put_Index with the error "Operation is not supported for this type of object" (presumably referring to the dynaset)
Comment: First: AFAIK Access, it is not recommended to have more than 2GB of data opened using a single _front end_ file. Moving data to some archive is better practice.
Comment: Second: this is a coding site, you should post here what you have tried, what was the result, and how does it differ from what you desired. Try posting this question in an Access forum, like [this](https://www.access-programmers.co.uk/forums/forumdisplay.php?f=6), or [this](https://www.utteraccess.com/forum/).
Comment: post your code please.
Comment: I would suggest [Migrate an Access database to SQL Server](https://support.office.com/en-us/article/migrate-an-access-database-to-sql-server-7bac0438-498a-4f53-b17b-cc22fc42c979)
Answer: A few things:
If you are using the accDB format, then you do NOT want, nor need a reference to the DAO object library. It is a depreciated library, and the new ACE library which replaces the DAO library is now what you use. It is in general 100% compatible. So, no reference to DAO is required if you using the accDB format.
The DAO library is NOW built into Access. You don't use or want the external DAO library.
So just make sure you use the "default" references in Access.
Microsoft Access 14.0  Object Library
Microsoft Office 14.0 Access database engine object.
(of course 14.0 is for access 2010 – you  have different numbers for later versions). So, 15.0 for access 2013. (but, these references will in general be set for you).
If you are not using the mdb format, then REMOVE the DAO referance - it is not required anymore.
At that point, then you should be good to go.
For a linked table?
If you use this code for a NON linked table then it will work:
Dim rst     As DAO.Recordset

Set rst = CurrentDb.OpenRecordset("tblNames1",dbOpenTable)

NOTE in above the use of dbOpenTable. You REALLY do not need or wanted to have used dbOpenTable anyway.
In fact, you REALLY should use this:
Dim rst     As DAO.Recordset

Set rst = CurrentDb.OpenRecordset("tblNames1")

However,if the table NOW linked?
Well then this will work:
Dim rst     As DAO.Recordset

Set rst = CurrentDb.OpenRecordset("tblNames1")

However, this will FAIL!!!
Dim rst     As DAO.Recordset

Set rst = CurrentDb.OpenRecordset("tblNames1",dbOpenTable)

So you can't FORCE or use dbOpenTable for linked tables.
And I suppose (but not necessary), to convey 100% you the developer intentions, you could use this for a linked table:
Set rst = CurrentDb.OpenRecordset("tblNames1", dbOpenDynaset)

RecordSet.put_Index

That could and would have NEVER worked. There is no such thing as put_index for DAO recordsets. So that issue is 100% separate from that of linked tables.
There is no put_Index method or property of the DAO reocrdset object, and thus no matter what you are attempting to do, that syntax is wrong, and was never supported.


Why do significance levels in the Shapiro test for normality fluctuate with the number of observations?

Question: When simulating the Shapiro test for normal distributed data in R I encountered that the p-values for rejecting the Null-Hypothesis often increase in the range of ~30 to ~200 observations, than decrease again and than somehow fluctuate. How can I explain this behavior? Intuitively I thought that with a larger number of observations, the p-values would increase as well and that I would get low p-values especially if I have a small number of observations.
test <- vector(length = length(10:5000))
for(i in 10:5000){
  set.seed(500)
  test[i] <- shapiro.test(rnorm(i))[[2]]}
plot(test)

If you change the seed the results look different, however the general pattern is often similar.
Comment: No, the p-value is *defined* in such a way that when it is correctly and accurately calculated, when the distribution of the test statistic is continuous, and the null hypothesis holds, it will be randomly and uniformly distributed between $0$ and $1$.  All of those circumstances apply to your experiment.
Comment: This isn't telling you anything useful about the Shapiro test or anything else.
 *Remove* the seed setting.  If you don't, you induce extremely strong relationships among successive results and all you get is a variation of a random walk.
Comment: If I remove the seed setting than there is no pattern at all any more with p-values between 0-1 for any level of observations... shouldn't be the general pattern an increase in robustness and hence higher p-values? Is this a specific problem of the `rnorm` function?
Answer: This question is resolved by applying software engineering principles.

The plot is a very roundabout and computationally expensive way to construct a random walk.
To see what this means, let's redo the code to make it faster and clearer:
set.seed(500)
x <- rnorm(5000)
test <- c(rep(0, 9), sapply(10:5000, \(n) shapiro.test(x[1:n])$p.value))

You can plot test to verify the results are identical.  Notice that the data vector x never changes.  The sapply function loops over the indices $n = 10, 11, \ldots, 5000$ and applies the function shapiro.test to the first $n$ entries in the constant vector x.
The same qualitative behavior arises with most other functions.  Consider this variant where shapiro.test is replaced by a t test:
test <- c(rep(0, 9), sapply(10:5000, \(n) t.test(x[1:n])$p.value))
plot(test, type = "l")

When applied to the very same vector x, the plot is qualitatively like that in the question:

Abstractly, let $f$ represent the function shapiro.test or t.test or whatever.  Its values are p-values in the range $[0,1].$  The plot maps each $n$ to $f(x_1,x_2,\ldots, x_n).$
This abstract description helps clarify how the points on the plot evolve from left to right: $f(x_1,\ldots, x_n)$ is followed by an updated version $f(x_1,\ldots, x_n, x_{n+1}),$ where $x_{n+1}$ is a random value independent of the first $n$ values in $x.$
Let's express this conventionally.  The vector x is the computer's realization of the mathematical sequence $X_1, X_2,\ldots, X_n,\ldots$ of independent random variables (all with standard Normal distributions in this example).  The sequence being plotted is
$$S = f(X_1), f(X_1,X_2), \ldots, f(X_1,X_2,\ldots,X_n), \ldots$$
It generalizes the archetypical random walk where $S_n = X_1 + X_2 + \cdots + X_n.$  Unless $f$ doesn't depend at all on $x_1,\ldots, x_n,$ the updated value must be related to the previous value: successive points on the plot are not independent.  That's what makes the plot wander around rather than producing a bunch of scattered points.

The intention behind this code might have been to study what happens to the distributions of the Shapiro-Wilk p-values as they might depend on the sample size.  If so, the code is erroneous.
A good approach to implementing the intention is to encapsulate the problem by putting the data generation and testing into a function.  Below, the function simulate generates n.sim samples of size n using a common random number generator distribution, applies the function $f$ (passed as statistic), and returns n p-values.  By wrapping all this in a call to sapply it allows the caller to pass a vector of various sample sizes in n, returning an array whose columns correspond to those sample sizes. All this can be done in one line.
simulate <- function(n, statistic, distribution, n.sim = 5000, ...)
  sapply(n, \(n) apply(matrix(distribution(n * n.sim, ...), n), 2, statistic))

(The ellipsis ... permits the caller to pass named arguments to distribution to vary its parameters if desired.)
Let's use this function to study the Shapiro-Wilk p-values for iid Normal samples (the null distribution).  This one uses sample sizes of $10,$ $20,$ $50,$ and $100.$  Because the main computation was encapsulated, this requires only one line, making it easy to verify the correctness of the implementation (subject to verifying that simulate works as intended).
n <- c(10, 20, 50, 100) # Sample sizes
set.seed(17)
Sim <- simulate(n, function(x) shapiro.test(x)$p.value, rnorm)

Here is what plots of the columns look like.
for (i in seq_along(n))
  plot(Sim[, i], col = "#00000020", ylab = "p value", main = bquote(n==.(n[i])))

The p-values are (literally) all over the place, exactly as one would hope when the data are generated from the null distribution for the test.
Maybe it's better to examine histograms of these p-values, now that we have seen there's no sequential pattern to them.
for (i in seq_along(n)) {
  hist(Sim[, i], freq = FALSE, xlim = 0:1, xlab = "p value", main = bquote(n==.(n[i])))

They look just like samples of a uniform distribution.  Everything works as it should, regardless of the sample size.
The extreme abstraction of simulate pays off here.  By making one tiny change we can study how well the Shapiro-Wilk test performs under a specific alternative hypothesis.  Consider, for instance, what happens when the data are drawn from a Gamma$(5)$ distribution:
Sim <- simulate(n, function(x) shapiro.test(x)$p.value, rgamma, shape = 5)

The p-value distributions now look like these:

As the sample size grows, a small p-value becomes more and more likely.  The test grows more powerful with increasing sample size.


Unity: Scene overlapping on real device

Question: I have a 2D game where I use the following code on my Start button in my Menu scene and for the Restart button once my player dies in the Game scene. The problem is occurring only when I play the game on my real device with the Build & Run Unity setting. I have two buttons that move my player, after pressing them a few times the movement would lag and the Menu scene would overlap over my Game scene while playing. It occurs every time the game starts. More directly put. I am playing and suddenly a black background and two big START and SETTINGS buttons flash during my playing and lag my controls and then they go away. Does anyone have ideas where this issue might arise from?
 public void LoadScene(string sceneName)
    {
        SceneManager.LoadScene(sceneName);
    }

Answer: It is strange, it shouldn't happen.
However, try using the LoadSceneAsync with this code and see if the bug still happens:
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class ScenesManager : MonoBehaviour {

    IEnumerator loadScene;
    public float loadingProgress;

    public void LoadScene(string levelName) {
        loadScene = AsyncLoad(levelName);
        StartCoroutine(loadScene);
    }

    private IEnumerator AsyncLoad(string levelName) {
        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(levelName, LoadSceneMode.Single);
        asyncLoad.allowSceneActivation = false;

        while (!asyncLoad.isDone) {
            loadingProgress = Mathf.Clamp01(asyncLoad.progress);
            asyncLoad.allowSceneActivation = false;
            if (asyncLoad.progress == 0.9f) {
                asyncLoad.allowSceneActivation = true;
            }
            yield return null;
        }
    }
}

Comment: Thanks for the answer. Sorry for the maybe stupid question. It says loadScene  and loadingProgress do not exist. Do I need to add them as something? I haven't encountered LoadSceneAsync before.
Comment: I'm sorry, I forgot to write the declaration of those two variables: `loadScene` is an `IEnumerator`, as coroutines are in Unity, while `loadingProgress` is simply a `float` that you can use to keep track of the loading progress, in order to use it for example with a loading bar.
I've corrected the code.

Unity: Scene overlapping on real device


How to add 1 HOUR in last activity date and time

Question: here's my SQL data  .. How to add 1 Hour on the last activity. That after updating it will be 2015-05-01  20:24:42 ? Thank you
 lastActivity
 2015-05-01 19:24:42

Comment: Have you tried anything?  Here's a [SO](http://stackoverflow.com/questions/589652/add-2-hours-to-current-time-in-mysql) article showing how it's done... assuming that is an actual date time data type
Answer: U can use the SQL function DATEADD
DATEADD(hh, 1, last_activity)

Example query:
SELECT user_id, DATEADD(hh, 1,last_activity) AS new_activity_date FROM users

Comment: can i ask question if how to query lastActivity that exactly 1hr from now..  for example i have in my database 2015-05-01 19:46:59    and 2015-05-01 21:42:21   so the output must be 1 only, which is 2015-05-01 19:46:59 because its in the range if you add 1 hour from now..
Comment: I'm not sure if i get you question right but if i do the answer is: DATEADD(hh, 1, now()) AS new_activity_date. This will add 1 hour to the current time.
Comment: yes I already add 1 hr from lastActivty..  So my question now if u know how to query users that active 1hour exact from the current time.. for my example..  i have two users which is  2015-05-01 19:46:59    and 2015-05-01 21:42:21   the difference is 2hrs   so i how can i query user for example the time is 2015-05-01 19:47:59  so 1hr from the 2015-05-01 21:42:21 is not in the range so it will not be query.. only the 2015-05-01 19:46:59


Comparing TreeMap contents gives incorrect answer

Question: I use a TreeMap as a 'key' inside another TreeMap
ie
TreeMap<TreeMap<String, String>, Object>

In my code 'object' is a personal construct, but for this intance I have used a string.
I have created a pair of TreeMaps to test the TreeMap.CompareTo() and TreeMap.HashCode() methods. this starts with the following...
public class TreeMapTest

public void testTreeMap()
{
TreeMap<String, String> first = new TreeMap<String, String>();
TreeMap<String, String> second = new TreeMap<String, String>();

first.put("one", "une");
first.put("two", "deux");
first.put("three", "trois");
second.put("une", "one");
second.put("deux", "two");
second.put("trois", "three");

TreeMap<TreeMap<String, String>, String> english = new TreeMap<TreeMap<String, String>, String>();
TreeMap<TreeMap<String, String>, String> french = new TreeMap<TreeMap<String, String>, String>();

english.put(first, "english");
french.put(second, "french");

From here I now call the  the english item to see if it contains the key
if (english.containsKey(second))
{
System.out.println("english contains the key");
//throws error of ClassCastException: Java.util.TreeMap cannot be cast to
//Java.Lang.Comparable, reading the docs suggests this is the feature if the key is
//not of a supported type.
//this error does not occur if I use a HashMap structure for all maps, why is
//this key type supported for one map structure but not another?
}

However I should note that both HashMap and TreeMap point to the same HashCode() method in the AbstractMap parent.
My first thought was to convert my TreeMap to a HashMap, but this seemed a bit soppy! So I decided to apply the hashCode() method to the 2 treemap objects.
int hc1 = first.hashCode();
int hc2 = second.hashCode();

if(hc1 == hc2)
{
systom.out.printline("values are equal " + hc1 + " " + hc2);
}

prints the following
values are equal 3877431 & 3877431

For me the hashcode should be different as the key values are different, I can't find details on the implementation difference of the hashCode() method between HashMap and TreeMap.
Please not the following.
changing the Keys only to HashMap  doesn't stop the ClassCastException error. Changing all the maps to a HashMap does. so there is something  with the containsKey() method in TreeMap that isn't working properly, or I have missunderstood - can anyone explain what?
The section where I get the hashCode of the first and second map objects always produces the same output (no matter if I use a Hash or Tree map here) However the if(english.ContainsKey(second)) doesn't print any message when HashMaps are used, so there is obviously something in the HashMap implementation that is different for the compareTo() method.
My principle questions are.
Where can I find details of the types of keys for use in TreeMap objects (to prevent future 'ClassCastException' errors).
If I can't use a certain type of object as a key, why am I allowed to insert it as a key into the TreeMap in the first place? (surely if I can insert it I should be able to check if the key exists?)
Can anyone suggest another construct that has ordered inster / retrieval to replace my TreeMap key objects?
Or have I potentially found strange behaviour. From my understanding I should be able to do a drop in replacement of TreeMap for HashMap, or have I stumbled upon a fringe scenario?
Thanks in advance for your comments.
David.
ps. the problem isn't a problem in my code as I use a personal utility to create a hash that becomes dependent on the Key and Value pairs (ie I calculate key hash values differently to value hash values... sorry that if is a confusing sentence!) I assume that the hashCode method just sums all the values together without considering if a item is a key or a value.
pps. I'm not sure if this is a good question or not, any pointers on how to improve it?
Edit.
from the responses people seem to think I'm doing some sort of fancy language dictionary stuff, not a surprise from my example, so sorry for that. I used this as an example as it came easily to my brain, was quick to write and demonstrated my question.
The real problem is as follows.
I'm accessing a legacy DB structure, and it doesn't talk nicely to anything (result sets aren't forward and reverse readable etc). So I grab the data and create objects from them.
The smallest object represents a single row in a table (this is the object that in the above example I have used a string value 'english' or 'french' for.
I have a collection of these rowObjects, each row has an obvious key (this is the TreeMap that points to the related rowObject).
i don't know if that makes things any clearer!
Edit 2.
I feel I need to elaborate a little further as to my choice of originaly using
hashMap<HashMap<String,string>, dataObject>

for my data structure, then converting to TreeMap to gain an ordered view.
In edit 1 I said that the legacy DB doesn't play nicely (this is an issue with the JDBC.ODBC I suspect, and I'm not about to acquire a JDBC to communicate with the DB). The truth is I apply some modifications to the data as as I create my java 'dataObject'. This means that although the DB may spit out the results in ascending or descending order, I have no way of knowing what order they are inserted into my dataObject. Using a likedHashMap seems like a nice solution (see duffymo's suggestion) but I later need to extract the data in an ordered fashion, not just consecutively (LinkedHashMap only preserves insertion order), and I'm not inclined to mess around with ordering everything and making copies when I need to insert a new item in between 2 others, TreMap would do this for me... but if I create a specific object for the key it will simply contain a TreeMap as a member, and obviously I will then need to supply a compareTo and hashCode method. So why not just extent TreeMap (allthough Duffymo has a point about throwing that solution out)!
Comment: You should read the TreeMap documentation. A TreeMap is not a HashMap. It doesn't use `hashCode()`. Its keys are supposed to be comparable, because the whole point a a TreeMap is to use a tree of comparable objects internally. http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html
Comment: `TreeMap` keys must either be themselves `Comparable`, or you must provide a `Comparator` that can compare their keys.
Comment: The TreeMap doesn't call hashCode() on its *keys*. The fact that the hashCode() method of TreeMap is inherited has nothing to do with my comment. Your post keeps talking about hashCode(), but hashCode() is completely irrelevant for TreeMap. TreeMap doesn't care about the hashCode of its keys.
Comment: @JBNizet I have read the docs http://docs.oracle.com/javase/7/docs/api/index.html?java/util/TreeMap.html (note I'm using java 7 not 6). and it states that hashcode is inherited from abstractMap, just like the hashcode of HashMap
Comment: @JBNizet The doc states that TreMap.put(k,v) Throws: ClassCastException - if the specified key cannot be compared with the keys currently in the map. So if TreeMap doesn't implement both comparable and hashcode somewhere in its inheritence I wouldn't be able to use one as a key without throwing an error (which doesn't happen). That is probably a better description of my question. TreeMap is apparently not comparable, so I shouldn't be able to use one as a key in my TreeMap.
Comment: There is no current key in the map, so inserting the first key works. And `hashCode()` isn't used to compare two Comparable objects. It has nothing to do with your problem.
Comment: @JBNizet OK I just tested it. My actual code is obviously printing out info before it gets put into the TreeMap, so it looks like the treeMap is getting the data when in fact it isn't. Back to using unordered HashMaps, or subClassing TreeMap.
Comment: A TreeMap is not an ordered map. It's a sorted map. If what you want is to keep order of insertions into the map, you should use a LinkedHashMap. If you really want sorted keys, you obviously need to provide a comparator which will be used to sort your keys, since they don't have any natural order.
Comment: @JBNizet I must appologise I was getting very upset at you. My code seemed to be happily adding in TreeMap objects as keys, so I didn't believe you! So I modified my above code, ran the test... and I can o announce my code was seriously flawed somewhere down the line. I now need a better 'sorting' solution to my legacy DB data mining. I need to offer you a big thankyou, otherwise I may have been chasing this for a long time and it wouldn't have caused me problems untill later on. So back to using hashMaps for some stuff and sending the data into an SQLite / DerbyDB before playing with it!
Answer: This is not a good idea.  Map keys must be immutable to work properly, and yours are not.
What are you really trying to do?  When I see people doing things like this with data structures, it makes me think that they really need an object but have forgotten that Java's an object-oriented language.
Looks like you want a crude dictionary to translate between languages.   I'd create a LanguageLookup class that embedded those Maps and provide some methods to make it easier for users to interact with it.  Better abstraction and encapsulation, more information hiding. Those should be your design objectives.  Think about how to add other languages besides English and French so you can use it in other contexts.
public class LanguageLookup {
    private Map<String, String> dictionary;

    public LanguageLookup(Map<String, String> words) {
        this.dictionary = ((words == null) ? new HashMap<String, String>() : new HashMap<String, String>(words));
    }

    public String lookup(String from) {
        return this.dictionary.get(from);
    }

    public boolean hasWord(String word) {
        return this.dictionary.containsKey(word);
    }
}

In your case, it looks like you want to translate an English word to French and then see if the French dictionary contains that word:
Map<String, String> englishToFrenchWords = new HashMap<String, String>();
englishToFrenchWords.put("one", "une");
Map<String, String> frenchToEnglishWords = new HashMap<String, String>();
frenchToEnglishWords.put("une", "one");
LanguageLookup englishToFrench = new LanguageLookup(englishToFrenchWords);
LanguageLookup frenchToEnglish = new LanguageLookup(frenchToEnglishWords);
String french = englishToFrench.lookup("one");
boolean hasUne = frenchToEnglish.hasWord(french);

Comment: I have thought about creating my own little 'keyClass' but it would have to either be a collection of them to link to a single item, or it would have to have a colection of key value pairs within it. So why re-create the wheel when java has collections that work, and then I just create my custom. I guess I could write my own TreeMap class, that inherits from treemap and then overide both hashCode() and compareTo() methods.
Comment: That's not a good enough reason to write your own TreeMap.  If I were reviewing your code, I'd make you rip that out.
Comment: @duffmo I've added in a couple of edits in the hope of clarifying my situation. I'm coming around to using another better behaved DB (derby is going to be my choice, as I intend to use if again later for something else so I can use the same communication code) to convert my original legacy one into on a temp basis.
Answer: Your TreeMap is not Comparable so you can't add it to a SortedMap and its not immutable so you can't add it to a HashMap. What you could use an IdentityMap but suspect an EnumMap is a better choice.
enum Language { ENGLISH, FRENCH }

Map<Language, Map<Language, Map<String, String>>> dictionaries =
                                                    new EnumMap<>(Language.class);

Map<Language, Map<String, String>> fromEnglishMap = new EnumMap<>(Language.class);
dictionaries.put(Language.ENGLISH, fromEnglishMap);
fromEnglishMap.put(Language.FRENCH, first);

Map<Language, Map<String, String>> fromFrenchMap = new EnumMap<>(Language.class);
dictionaries.put(Language.FRENCH, fromFrenchMap);
fromEnglishMap.put(Language.ENGLISH, second);

Map<String, String> fromEnglishToFrench= dictionaries.get(Language.ENGLISH)
                                             .get(Language.FRENCH);

Comment: I see what you are doing here (took a while for my brain to put it together), nice idea, unfortunately I don't know what the values of my enum are before I start, I get them programatically from a legacy DB, see my edit to my original question. So I'm not sure how I could handle the auto creation of code to build my enums etc etc etc. +1 as it sounds like an otherwise excelent solution.
Comment: You can create instances of a non-enum `Language` class instead.
Answer: To the problem why Hashmap works and Treemap does not:
A Treemap is a "sorted map", meaning that the entries are sorted according to the key. This means that the key must be comparable, by implementing the Comparable interface. Maps usually do NOT implement this, and I would highly suggest you do not create a custom type to add this feature. As duffymo mentions, using maps as keys is a BAD idea.
Comment: I've edited my question, do you have any further comments? I've also responded to duffymo above, and said I'm going to use Derby as my temp data store, rather than maps as keys.


How Should I Properly Return True/False From a Meteor Template Helper?

Question: its there a simple way to accomplish this.
Template.example.helpers({
 showElement : function(){
 var number = Session.get('number')
 if(number === 1){
     console.log(number)
    return true;
   } else {
    console.log(number)
    return false;
   }
  }
})

For example lets say i have this 2 events setting to 1 and to 0
//Setting to 1
Template.example.events({
'click #setToOne' : function(e,t){
   Session.set('number',1)
  }
})
 //Setting to 0
Template.example.events({
'click #setToZero' : function(e,t){
   Session.set('number',0)
  }
})

So this is actually working because the  console.log inside the helper are showing 0 and 1
But how to call that helper on the template?
Already try this
<template name="example">
{{#if showElement.true}}

show this header if Truee

{{else}}

show this header if False

{{/if}}
</template>

So what this is a best practice? or should i use UI.registerHelper?(i don't really know how to works with UI.registerHelpers)
Thanks for the help in advice
Answer: <template name="example">
{{#if showElement}}

show this header if Truee

{{else}}

show this header if False

{{/if}}
</template>

Comment: Btw in your helper you can simply return Session.get('number');, 0 is treated as false
Answer: Let's take your problem and make a generic session variable equality checker helper:
Template.registerHelper('checkSession',function(sessionVarName,compareTo){
  return ( Session.get(sessionVarName) === compareTo );
});

With your specific variable name and comparison you could use this from any template with:
{{#if checkSession 'number' 1}}

which translates to if the session variable labeled 'number' is === 1
Comment: Thanks @Michel Floy for the answer, kinda old question haha my first steps with Meteor =p
Comment: I know! It just showed up in my list of related questions and I thought it deserved an up-to-date and more generally useful answer.


Multiple ehcache.xml in classpath

Question: What will happen if there are multiple ehcache.xml files in the classpath? Which one will be picked up?
Answer: That will depend on CLASSLOADING. Whichever is found first in CLASSPATH will be loaded and will be in effect for rest of your code.
It is same as keeping same JAR file in multiple paths of your CLASSPATH.

Multiple ehcache.xml in classpath


Why is huffman encoded text bigger than actual text?

Question: I am trying to understand how Huffman coding works and it is supposed to compress data to take less memory than actual text but when I encode for example
"Text to be encoded"

which has 18 characters the result I get is
"100100110100101110101011111000001110011011110010101100011"

Am I supposed to divide those result bits by 8 since character has 8 bits?
Comment: Actual result is `10010011 01001011 10101011 11100000 11100110 11110010 10110001 00000001` - **8** ASCII characters (technically, you should not *divide* by 8, but *group* by 8 bit chunks). More accurate is `"Text to be encoded" == 18 * 8 = 144 bits` before and `57` bits after the compression
Comment: "Text to be encoded" is a string. Each character in the uncompressed string is represented by an 8-bit ASCII character making the total uncompressed string 18*8=144 bits. The Huffman code is 57 bits.
Answer: You should compare the same units (bits as in the after the compession or characters as in the text before), e.g.
before: "Text to be encoded" == 18 * 8 bits = 144 bits
                             == 18 * 7 bits = 126 bits (in case of 7-bit characters)
after:  100100110100101110101011111000001110011011110010101100011 = 57 bits

so you have 144 (or 126) bits before and 57 bits after the compression. Or
before: "Text to be encoded" == 18 characters
after:   10010011
         01001011
         10101011
         11100000
         11100110
         11110010
         10110001
         00000001 /* the last chunk is padded */ == 8 characters

so you have 18 ascii characters before and only 8 one byte characters after the compression. If characters are supposed to be 7-bit (0..127 range Ascii table) we have 9 characters after the compression:
after:  1001001 'I'
        1010010 'R'
        1110101 'u'
        0111110 '>'
        0000111 '\0x07'
        0011011 '\0x1B'
        1100101 'e'
        0110001 'l'
        0000001 '\0x01'

Comment: "only 8 ascii characters after"  --> More like 8 _bytes_ as [ASCII](https://en.wikipedia.org/wiki/ASCII) is only defined for values 0-127.
Comment: This is the answer I was looking for. Thank you.


CAKEPHP: conditions com AND

Question: Estou com uma dúvida ao efetuar uma busca.
O item conditions na minha atual consulta está dessa maneira:
'conditions'=>array(
    'Produto.publicado'=>1,
    'Produto.titulo LIKE'=>"%$kw%",
    'TagsProduto.tag_id'=>$tags
),

Porém, $tags é um array e ele vai interpretar e implicitar o IN na busca. Eu preciso que ele busque incrementando, ou seja, com AND.
Alguém sabe como proceder?
Comment: poderia postar um exemplo do array $tags? Fica mais fácil entender.
Answer: Meu caro coleta,
Da maneira que você está relacioando as TAGs não é viável, fazer.
Pense que trazer produtos com obrigatoriamente as TAGs A, B e C, teriam que ter subquerys:
<?php
$criterios = array(
    'Produto.publicado'=>1,
    'Produto.titulo LIKE'=>"%$kw%",
    'AND' => array(),
);
foreach ($tags as $tag){
    $criterios['AND'][] = array('TagsProduto.tag_id'=>$tag);
}
?>

Veja acima uma forma de fazer o que você quer, porém não tem sentido, pois TagsProduto.id tem apenas 1 valor na linha, ou 1 ID da TagsProduto por linha.
Para trazer produtos com as TAGs A, B e C, você tem que fazer algo como:
<?php
$prodTag = array();
foreach ($tags as $tag){
    $prodTag[] = "Produto.id = (SELECT produto_id FROM tags_produto WHERE id={$tag} AND produto_id=Produto.id)";
}
$tags = implode(' AND ', $prodTags);

$this->Produto->find('all', array('conditions'=>array(
    $tags,
)));
?>

Comment: Obrigado, Newton! =)
Answer: Tente esses exemplos de AND/OR
         $conditons = array(
            'conditions'=>array(
                'AND' => array(
                    array('Produto.publicado'=>1,),
                    array('Produto.titulo LIKE'=>"%$kw%",),
                    array('TagsProduto.tag_id'=>$tags),
                )
            ),
        );

        $conditons = array(
            'conditions'=>array(
                'OR' => array(
                    array('Produto.publicado'=>1,),
                    array('Produto.titulo LIKE'=>"%$kw%",),
                    array('TagsProduto.tag_id'=>$tags),
                )
            ),
        );

CAKEPHP: conditions com AND


Positive integer solution from a positive real solution in a linear system

Question: Maybe I'm confused with something I learned on a Linear Programming course, but:

Is it true that a linear homogeneous system of equations with integer coefficients and at least one positive real solution also has an integer positive solution?

If true, do you know about a reference for this result?
Answer: A basis of the vector space that represents the solution of a linear homogeneous system of equations (with $n$ variables) can be found by using elementary arithmetic. If the system has integer coefficients, it is therefore possible to find a basis with vectors in $\mathbb{Q}^n$. You can now express the known positive real solution as a linear combination of the rational basis vectors. This linear combination is a continuous function of the coefficients of the basis vectors, therefore it is possible to change the coefficients to rational numbers without violating the positiveness of the solution vector. And if there is a positive rational solution, there is also a positive integer solution - simply multiply the solution vector with the LCD of its elements.
Comment: I was doing this same sort of continuity argument, not formalized yet though. You gave me new insights into this.


Should I Unset PHP variables in Drupal?

Question: We all know php's variables(array, integer,string) would be taking large memory. So PHP recommend to unset the variables to optimize the memory.
Should I do that in Drupal too ? or Is Drupal internally handling such a things ?
Comment: `So PHP recommend to unset the variables` where have you found this recommendation?
Answer: No, Drupal is not doing anything to handle this; the very fact you're asking might suggest you're not totally sure how this works, as Drupal has no power over the efficiency of the code you write.
GC runs every time a function finishes, so unless you've identified an actual problem in one specific function, clearing up every single variable after you've used it, even though you theoretically can, would surely be considered premature optimisation.
Bottom line: Drupal cannot help you to write efficient code, you need to apply what you know from PHP. Whether you want or need to free the memory for every single variable manually depends on your requirements and specific code.
I would personally say you're over-thinking this a bit, as in an ideal world your functions should be small and modularised enough for this not to be an issue anyway. React to real problems, not perceived or potential ones, when it comes to optimisation.

Should I Unset PHP variables in Drupal?


adding the same thing in tablerow causes fc

Question: i am doing exactly what this page says: http://en.androidwiki.com/wiki/Dynamically_adding_rows_to_TableLayout
main code:

this.setContentView(R.layout.main);
      /* Find Tablelayout defined in main.xml */
      TableLayout tl = (TableLayout)findViewById(R.id.myTableLayout);
           /* Create a new row to be added. */
           TableRow tr = new TableRow(this);
           tr.setLayoutParams(new LayoutParams(
                          LayoutParams.FILL_PARENT,
                          LayoutParams.WRAP_CONTENT));
                /* Create a Button to be the row-content. */
                Button b = new Button(this);
                b.setText("Dynamic Button");
                b.setLayoutParams(new LayoutParams(
                          LayoutParams.FILL_PARENT,
                          LayoutParams.WRAP_CONTENT));
                /* Add Button to row. */
                tr.addView(b);
      /* Add row to TableLayout. */
      tl.addView(tr,new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myTableLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
     <TableRow
          android:layout_width="fill_parent"
          android:layout_height="wrap_content">

          <Button android:text="Static Button"/>
     </TableRow>
</TableLayout>

but when i duplicate the line
tr.addView(b);
it gives me fc.
Any idea where is the error?
Answer: That's because you are adding the same button. Try:
            .....
            /* Create a Button to be the row-content. */
            Button b = new Button(this);
            b.setText("Dynamic Button");
            b.setLayoutParams(new LayoutParams(
                      LayoutParams.WRAP_CONTENT,
                      LayoutParams.WRAP_CONTENT));
            /* Add Button to row. */
            tr.addView(b);

            b = new Button(this);
            b.setText("Another Dynamic Button");
            b.setLayoutParams(new LayoutParams(
                      LayoutParams.WRAP_CONTENT,
                      LayoutParams.WRAP_CONTENT));
            /* Add Button to row. */
            tr.addView(b);

            ......

Comment: you can add different buttons but not the same.


How to prove: $\sum_{k=0}^{n}~(-1)^k{n \choose k} {2n-2k \choose n+m-1}=2^{n-m+1} {n \choose m-1}$

Question: The sum $$S_{n,m} =\sum_{k=0}^{n}~ (-1)^k{n \choose k} {2n-2k\choose n+m-1}$$  can be evaluated by Mathematica for $m=0,1,2,3$ in simple closed forms. But in general $$ S_{n,m}=2^{n-m+1}{n \choose m-1}~~~(*).$$ The question is how to prove (*) by hand?
Answer: We have
$$\sum_{k=0}^n (-1)^k {n\choose k} {2n-2k\choose n+m-1}
= [z^{n+m-1}] (1+z)^{2n}
\sum_{k=0}^n (-1)^k {n\choose k} (1+z)^{-2k}
\\ = [z^{n+m-1}] (1+z)^{2n}
\left(1-\frac{1}{(1+z)^2}\right)^n
\\ = [z^{n+m-1}] ((1+z)^2-1)^{n}
= [z^{n+m+1}] (2z+z^2)^{n}
\\= [z^{n+m-1}] z^{n} (z+2)^{n}
= [z^{m-1}] (z+2)^n
= {n\choose m-1} \times 2^{n-m+1}.$$
The last coefficient extractor returns zero when $m-1\lt 0,$ as does  the
binomial coefficient.
Comment: Very nice and concise.
Comment: Thank you, I hope it helps.
Answer: The answer is simple (but my solution below is not...). Suppose $n\geqslant m-1$ (otherwise the sum is trivially zero). Then $S_{n,m}$ is equal to the coefficient of $x^{2n}$ in the power series $A(x)B(x)$, where \begin{align}A(x)&:=\sum_{k=0}^{n}(-1)^k\binom{n}{k}x^{2k}=(1-x^2)^n,\\B(x)&:=\sum_{k=0}^{\infty}\binom{2k}{n+m-1}x^{2k}=\frac12\big(C(x)+C(-x)\big),\\C(x)&:=\sum_{k=0}^{\infty}\binom{k}{n+m-1}x^k=\frac{x^{n+m-1}}{(1-x)^{n+m}},\end{align} thus \begin{align}S_{n,m}&=\frac12[x^{2n}](1-x^2)^n\left(\frac{x^{n+m-1}}{(1-x)^{n+m}}+\frac{(-x)^{n+m-1}}{(1+x)^{n+m}}\right)\\&=\frac12[x^{n-m+1}]\frac{(x+1)^{n+m}-(x-1)^{n+m}}{(1-x^2)^m}.\end{align} Using Cauchy's integral formula, we have $$S_{n,m}=\frac{1}{4\pi i}\oint_{|z|=\epsilon}\frac{(z+1)^{n+m}-(z-1)^{n+m}}{z^{n-m+2}(1-z^2)^m}\,dz$$ where $0<\epsilon<1$; substituting $z=1/w$, we get $$S_{n,m}=\frac{1}{4\pi i}\oint_{|w|=1/\epsilon}\frac{(1+w)^{n+m}-(1-w)^{n+m}}{(w^2-1)^m}\,dw,$$ which is easily computed using residues (at $w=\pm 1$, turn out to be equal). The result is $$\color{blue}{S_{n,m}=2^{n-m+1}\binom{n}{m-1}}.$$
Comment: You did it elegantly!
Answer: To sum
$$S_{n.m}=\sum_{k=0}^{n} (-1)^k  {n \choose k} {2n-2k\choose n+m-1}, m=0,1,2 ~~~~(1)$$
$$(1-x^2)^n= \sum_{k=0}^{n} (-1)^k {n \choose k} (x)^{2k}~~~~~~~(2)$$
$$(1-x)^{-n-m} =\sum_{j=0}^{\infty} {j+n+m-1, \choose n+m-1} x^j~~~~(3)$$
Multiply (1) and (2) to write
$$\frac{(1+x)^n}{(1-x)^m}=\sum_{j=0}^n \sum_{k=0}^{n} (-1)^k {n \choose k}{j+n+m-1 \choose n+m-1} x^{j+2k}~~~~(4)$$
In oder that (4) resembles with (1) , we set  $j+n+m-1=2n-2k \implies j=n-2k-m+1\implies j+2k=n-m+1$. Thus $$S_{n.m}=[x^{n-m+1}] \frac{1+x)^n}{(1-x)^m}$$. It then follows that
$$S_{n.0}=[x^{n+1}] ~(1+x)^n=0$$
$$S_{n,1}=[x^n] ~ \frac{(1+x)^n}{(1-x)}=[x^n]~ (1+x)^n (1-x)^{-1}={n \choose n}+{n \choose ,n-1}+{n \choose n-2}+...+{n \choose 0}=2^n.$$
$$S_{n,2}=[x^{n-1}] ~ \frac{(1+x)^{n-1}}{(1-x)^2}=[x^{n-1}]~ (1+x)^n (1-x)^{-2}=0{n \choose n}+1{n \choose ,n-1}+2{n \choose n-2}+...+n{n \choose 0}=n2^{n-1}.$$
In (4), we use $$(1-x)^{-m}=\sum_{k=0}^{\infty} {-m \choose k} x^k=\sum_{k=0}^{\infty} (-1)^k {m+k-1 \choose k} x^k$$
The generalization is that the sum $$S_{n,m}=\sum_{k=0}^n (-1)^k {-m \choose k} {n \choose n-k-m+1}=\sum_{k=0}^{n} {m+k-1 \choose k}{n \choose m+k-1}=
\sum_{k=0}^{n} {n \choose k} {n-k \choose m-1}=\sum_{k=0}^{n} {n \choose n-k} {n-k \choose m-1}={n \choose m-1} \sum_{k=0}^n {n-m+1 \choose k}={n \choose m-1}2^{n-m+1} $$


How do i prove that any subgroup of $A_5$ has order at most 12?

Question: I know this question has been answered Other proofs that subgroups of $A_5$ have order at most 12
But i have difficulty in understanding that proof.The book says we can assume that $A_5$ has no normal subgroup.How to find the proof using this property ?
EDIT-
(I solved the previous question ( $A_5$ has no normal subgroup ) but i am not able to solve this problem ).
I have already mentioned that my question similar to Other proofs that subgroups of $A_5$ have order at most 12  so please don't mark it as duplicate.
The book which i am talking about is  - Topics In Algerbra by Herstein. (2.10.15)
I am thankful if some can explain the same proof ( provided in link ).I have difficulty in understanding the homomorphic part of that answer.
Comment: The homomorphic map, both in the lin and in my answer, refers to a homomorphism from the *group* $\;A_5\;$ to the group of permutation on $\;l\;$ elements, whith $\;l=\,$ the number of cosets of the subgroup. This is **not** a subgroup of $\;A_5\;$, only a set upon which $\;A_5\;$ acts...
Comment: @JoséCarlosSantos I have mentioned it in my question .I have difficulty in understanding that proof.I want to prove it using the fact that $A_5$ has no normal subgroup .
Comment: Then you comment that answer. Or you reproduce the answer within your question explaining *where* did you get stuck.
Comment: @JoséCarlosSantos Any hint or suggestion from your side ?
Comment: @JoséCarlosSantos The user of that answer is probably not on stack exchange .Also i think that answer does not proves by using the property that $A_5$ has no normal subgroup
Comment: The answer linked by José Carlos is, in my opinion, as simple as one can expect, and I'm not sure there's another one simpler. To understand it, and understand other many important things as well, you need to know *action of a group on a set*, how such an action determines a homomorphism to a permutation group and etc. If you know this, you'll be able to understand why *the simple group* $\;A_5\;$ cannot have a subgroup of index $\;<5\;$ ...!
Comment: @DonAntonio Thanks for your comment.All the things you have mentioned i know.The part that i did not understood is  - the homomorphic map .A map is defined from one group to another .But how $S$ is a group ? can you explain the same answer in simple words in comments or in as a new answer.
Comment: @JoséCarlosSantos Since you asked where i am stucked , i repeat a comment - The part that i did not understood is - the homomorphic map .A map is defined from one group to another .But how S is a group ? can you explain the same answer in simple words in comments or as a new answer. Can you explain me the homomorphic map ? Thanks.
Answer: Let $\;H\;$ be a subgroup of $\;A_5\;$ of order $\;>12\implies\;$ its index is $\;l<5\;$ . Then $\;A_5\;$ acts on the set of left cosets of $\;H\;$ in $\;G\;$ , and this determines a homomorphism $\;\phi:A_5\to S_l\;$ . Since $\;A_5\;$ is simple this homomorphis is acutaly a monomorphism (i.e., $\;1-1$) , and thus it is an injection, which of course is impossible as  $\;|A_5|=60>S_l\;$
Comment: This is a very beautiful proof and it can be extended to show that for every $n\ge 5$, $A_n$ has no subgroups of order larger than $\frac{(n-1)!}{2}$.
Comment: A simple group $G$ has only two normal subgroups$\text{---}$$\{e\}$ and the whole $G$.  Since the kernel of any homomorphism of groups $\psi:G\to K$ is a normal subgroup of $G$, we have $\ker \psi=\{e\}$ or $=G$.  So, either $\phi$ is injective or trivial.  In the case at hand, $H$ is assumed to be a **proper** subgroup of $A_5$ (I forgot to add the word "proper").  So, $A_5$ cannot act on $A_5/H$ trivially.  That is, $\phi:A_5\to S_l$ can't be the trivial homomorphism, so it's injective.
Comment: Thanks @DonAntonio  .Even after being duplicate question you took out time and cleared my doubt.Math SE people should understand that there can be slow learner's .
Comment: Index can be equal to 4 .Suppose subgroup is of order 15
Comment: @Amit Of course, that was just a typo. Edited now, thanks.
Comment: Observe the above argument proves that a simple group *cannot* have a subgroup of any index $\;n\;$ such that the group's order is smaller than $\;n!\;$ ...In particular, infinite simple groups cannot have simple index subgroups
Comment: @Zvi Few doubt's - 1.How A5 will map to Sl . 2.I didn't knew that homomorphism from simple group is injection. can you explain that ? Thanks
Comment: Thanks @Zvi You also cleared my important doubt through comment.
Comment: @zvi How to prove that $ϕ$ is homomorphism
Comment: @DonAntonio How to prove that $ϕ$ is homomorphism
Comment: @Hansie That $\;\phi\;$ is a homomorphism  *determined by the action* of $\;A_5\;$ on the left cosets of $\;H\;$ ... This is standard stuff in Actions of Groups on sets and etc., as I wrote in the comments below your question and you said you know all these things...
Answer: $A_5$ has order 60. Thus, any proper subgroup $H$ of order larger than 12 must have order 15, 20, or 30. Any subgroup of order 30 would have index 2, so would be normal, contradicting your previous result. Thus, $H$ must have order 15 or 20.
Now, both 15 and 20 are multiples of 5, so $H$ must contain an element of order 5. Up to conjugation, that element is $(1,2,3,4,5)$. If $H$ has order 15, then it also contains an element of order $3$, which must be a 3-cycle. But running through each possible 3-cycle:
$(1,2,3)(1,2,3,4,5)^2 = (1,4)(2,5)$, which has order 2, so $H$ has even order, a contradiction.
$(1,2,4)(1,2,3,4,5)^4 = (2,3)(4,5)$, so again, $H$ has even order.
$(1,3,5)(1,2,3,4,5)^4 = (1,2)(3,4)$, so again, $H$ has even order.
And all others are conjugate (as a whole) to those, so symmetrically, have the same orders. Thus, there is no subgroup of order 15.
Thus, $H$, if it exists, must have order 20, so must contain an element of order 2, which must be a product of two disjoint 2-cycles. Again, running through the possibilities:
$(1,2)(3,4)(1,2,3,4,5) = (1,3,5)$, so $H$ has order 60.
$(1,3)(2,4)(1,2,3,4,5)^2 = (1,5,2)$, so $H$ has order 60.
$(1,3)(2,5)(1,2,3,4,5)^2 = (1,5,4)$, so $H$ has order 60.
$(1,4)(2,5)(1,2,3,4,5) = (3,5,4)$, so $H$ has order 60.
$(1,5)(2,3)(1,2,3,4,5) = (2,4,5)$, so $H$ has order 60.
$(1,5)(3,4)(1,2,3,4,5) = (2,3,5)$, so $H$ has order 60.
$(2,3)(4,5)(1,2,3,4,5) = (1,2,4)$, so $H$ has order 60.
$(2,4)(3,5)(1,2,3,4,5)^2 = (1,3,2)$, so $H$ has order 60.
Now, you'll notice that I've missed a few permutations, namely:
$(1,2)(3,5)$
$(1,3)(4,5)$
$(1,4)(2,3)$
$(1,5)(2,4)$
$(2,5)(3,4)$
With these, we have:
$(1,2)(3,5)(1,2,3,4,5) = (1,3)(4,5)$,
$(1,3)(4,5)(1,2,3,4,5) = (1,4)(2,3)$,
$(1,4)(2,3)(1,2,3,4,5) = (1,5)(2,4)$,
$(1,5)(2,4)(1,2,3,4,5) = (2,5)(3,4)$, and
$(2,5)(3,4)(1,2,3,4,5) = (1,2)(3,5)$,
so if any one of these lies in $H$, all of them do. Further, these five elements, along with the powers of $(1,2,3,4,5)$ form a subgroup, of order 10. But if $H$ contains any other element, it must be one of order 2 or 5 (else $H$ would have order a multiple of 3): the order 2 cases have been covered above, and all give $H = A_5$. Checking the elements of order 5 that aren't already in there:
$(1,2,3,4,5)(1,2,3,5,4) = (1,3)(2,5)$,
$(1,2,3,4,5)(1,2,4,3,5) = (1,4)(2,5)$,
$(1,2,3,4,5)(1,2,4,5,3)^2 = (1,5,4)$,
$(1,2,3,4,5)(1,2,5,3,4)^2 = (1,3,2)$,
$(1,2,3,4,5)(1,2,5,4,3) = (1,5,2)$,
$(1,2,3,4,5)(1,3,2,4,5) = (1,4)(3,5)$,
$(1,2,3,4,5)(1,3,2,5,4) = (1,5,3)$,
$(1,2,3,4,5)(1,3,4,2,5)^2 = (3,5,4)$,
$(1,2,3,4,5)(1,3,4,5,2) = (2,4)(3,5)$,
$(1,2,3,4,5)(1,3,5,4,2) = (2,5,3)$,
$(1,2,3,4,5)(1,4,2,3,5)^2 = (1,5,2)$,
$(1,2,3,4,5)(1,4,3,2,5) = (1,5,4)$,
$(1,2,3,4,5)(1,4,3,5,2) = (2,5,4)$,
$(1,2,3,4,5)(1,4,5,2,3)^2 = (2,4,3)$,
$(1,2,3,4,5)(1,4,5,3,2) = (3,5,4)$,
$(1,2,3,4,5)(1,5,2,3,4) = (1,3)(2,4)$,
$(1,2,3,4,5)(1,5,2,4,3) = (1,4,2)$,
$(1,2,3,4,5)(1,5,3,2,4) = (1,4,3)$,
$(1,2,3,4,5)(1,5,3,4,2) = (2,4,3)$,
$(1,2,3,4,5)(1,5,4,2,3) = (1,3,2)$.
So if $H$ contains any of these, it is all of $A_5$. Thus, there is no subgroup of $A_5$ of order 20, and hence no proper subgroup of order more than 12.
[NB: there are some pretty massive time-saving options available here: I went for keeping things as elementary as possible]
Comment: It might help if you use the fact that any group of order $15$ is cyclic.  But there is no element of $A_5$ of order $15$.
Comment: Indeed, that's one of the time-saving options that I mentioned.


Choosing variable transformations in non-linear relationships

Question: I am confused about how to apply a transformation to my predictor/response variables to test curvilinear relationships. I read about log transformations, polynomials, quadratic functions. But I am not a statistician. How do I choose which to apply in my regression formula?
My hypothesis relevant in my industry (advertising) is :
(i) at low volume of predictor, the impact on my response variable exists but is limited. There's not enough critical mass of predictor.
(ii) at optimal volume, the impact on my response variable is increasing at an increasing rate.
(iii) Beyond a point, the predictor's impact on response variable becomes limited.
Comment: Unless there is reasoning based on findings in your field, usually the analyst can only guess what relationships may exist. However, **plotting the data** can be extremely useful here. You can control for other variables by running a regression without your non-linear transformation and plot the residuals from these models against the non-linear transformation to see if you get a strong trend.
Comment: However, it is worth noting that that is NOT a statistically valid model selection procedure... purely an exploratory tool.
Comment: An illustrated worked example of one possible method to identify effective nonlinear re-expressions of regression variables is provided at http://stats.stackexchange.com/a/35717.
Comment: Thanks Matthew, Are you suggesting that I plot the residuals from regression with non-linear transformations against residuals from regression without any transformations? If yes, how do I analyze the plot?
Comment: Not quite. Say you have some other predictors (possibly including a linear version of your variable) and you want to evaluate a non-linear transformation of a particular variable. Run a regression on all the parameters without that non-linear transform, and then plot the residuals of that model against the nonlinear transformation. [Here](http://i.imgur.com/PRCqag3.png)'s an example of what I mean. The y-axis are the residuals from a model without $\log(X_3)$ and the x-axis is the actual variable $\log(X_3)$. This can help you see if there exists a trend while controlling for other variables.
Comment: @matthew so I can check whether some portion of the residuals can be accounted for by the transformed variable or not. I just saw the example. The plot tells us that at higher values of log(x3) the residual value keep increasing. Basically there is a relationship between the two and hence the log transformation could be a useful addition to the regression. Am I getting it?
Comment: I'm going to submit an answer with a better explanation
Answer: Going to preface my answer with this: the procedure I describe below is NOT a valid model selection procedure... It is an exploratory tool.

How do I choose which to apply in my regression formula?

Unless there is reasoning based on findings in your field, usually the analyst can only guess what relationships may exist. One way to do this is to throw all sorts of non-linear transformations into the regression model to see how well they do in explaining the output variable.
However, plotting the data can be extremely useful here. Consider a model given precisely by
$$
Y \sim \mathcal{N}(\mu, \sigma^2),\\
\mu = \beta_0 + \beta_1X_1 + \beta_2 X_2 + \beta_3\log(X_3).
$$
If we suspect there is a nonlinear transform for $X_3$ that will help us model $Y$, then we can run a regression on $Y$ against just $X_1, X_2$ and look at the residuals. The residuals are the errors of the model (i.e., $y - \hat y$), so they represent how far off just using $X_1, X_2$ is. In this case, we would expect $y - \hat y \propto \log(X_3)$ because of the formula for $\mu$:
$$
\mu = \beta_0 + \beta_1X_1 + \beta_2 X_2 + \beta_3\log(X_3) \implies \mu - (\beta_0 + \beta_1X_1 + \beta_2 X_2) = \beta_3\log(X_3)
$$
Plotting the residuals, we observe a log trend in $X_3$.

So we plot $\log(X_3)$ against the residuals and get a clearly linear trend.

Just plotting $X_3$ against $Y$ might not be that useful, since we wouldn't necessarily be able to uncover this trend without controlling for $X_1, X_2$. This approach allows you a better chance to uncover $X_3$'s involvement in predicting $Y$.
Comment: well, I don't know what to do. After trying log transformations, 2nd & 3rd degree polynomials and quadratic functions, I find the simple non-transformed values explain the relationship best. Except now I have two highly collinear variables interacting with each other and I need both of them since I want to compare them relatively.


Carregar páginas sem duplicar conteúdo através do AJAX

Question: Possuo um sistema de navegação por ajax + pushState em meu site.
Se o usuário clicar em um link interno, será feito um $.post e eu verifico no PHP se $_SERVER["REQUEST_METHOD"] === "POST" então eu carrego uma página, por exmplo: indexPost.html,
 e, se o usuário acessar diretamente o link eu faço um $_SERVER["REQUEST_METHOD"] === "GET" então, carrego indexGet.html.
Segue abaixo o exemplo dos indexe's:
indexPost.html:

Olá, esse é o conteudo!

indexGet.html:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>indexGet.html</title>
        <link rel="stylesheet" href="/style.css">

Olá, esse é o conteudo!

Tive que recorrer a desenvolver dessa maneira pois se carregasse, por exemplo, o indexGet.html através do $.post o arquivo HTML inteiro seria duplicado.
A minha pergunta é: existe alguma maneira mais simples de fazer isso sem ter que sempre ficar criando 2 arquivos para cada ação? Lembrando que, terei que fazer isso com vários arquivos, ou seja, seria um processo muito cansativo.
Acredito que há uma maneira mais simples, porém não consegui pensar em nada melhor que isso e além do mais, pesquisei e não encontrei exemplos alternativos.
EDITADO
Bem, segue um exemplo do que eu uso em meu sistema:
index.php (que é requisitada pelo $.post através do meu script):
if($_SERVER["REQUEST_METHOD"] === "POST") {
    $html = new Template("caminho/views/post/index.html");
    //aqui vão outras variáveis do template...
    $html -> show();
} else if($_SERVER["REQUEST_METHOD"] === "GET") {
    $html = new Template("caminho/views/get/index.html");
    //aqui vão outras variáveis do template...
    $html -> show();
}

Estou utilizando um sistema de templates, e, como pode perceber, estou salvando o mesmo arquivo, porém em pastas diferentes, uma para cada caso.
No caso de ser POST, o index.html salvo em caminho/views/post/index.html possui apenas o conteúdo.
No caso de ser GET, o index.html salvo em caminho/views/get/index.html possui scripts e css's além do conteúdo.
Obrigado!
Answer: A maioria dos sistema de template que conheço trabalham com o conceito de view e layout.
A view seria esse seu indexPost.html e o layout indexGet.html, com a impressão de uma variavel $content no lugar do conteúdo.
Normalmente esse layout é um html mais generico, com os menus do site, rodapé e coisas do tipo, e é usado por todas as outras views.
Normalmente, se tem a opção de imprimir só a view, desabilitando o layout, que acredito ser o conteúdo que você quer quando recebe um "post".
No seu caso, você poderia verificar se a requisição é um ajax, e desabilitar o layout.
Uma implementação bem simplista poderia ser essa.
layout.html
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>indexGet.html</title>
        <link rel="stylesheet" href="/style.css">

        {CONTEUDO}

example-view-hello-world.html
Olá mundo

example-view-stack.html
Olá Stack

Função que faria o trabalho de renderizar as views com e sem layout.
function renderView($name, $layout = 'layout') {

    $viewHtml = file_get_contents("caminho/para/views/$name.html");

    if($_SERVER["REQUEST_METHOD"] === 'GET') {
        $layoutHtml = file_get_contents("caminho/para/views/$layout.html");
        $output = str_replace('{CONTEUDO}', $viewHtml, $layoutHtml);
    }
    else{
       $output = $viewHtml;
    }

   return $output;
}

Nesse sistema de template que você usa, esse conceito não é tão claro, mas esta previsto, ele é chamado de "usando vários arquivos html".
Basicamente, se você quer mostrar só a view, o código seria o seguinte:
$tpl = new Template('caminho/views/example-view-hello-world.html');
//aqui vão outras variáveis do template...
$tpl->show();

Caso você queria usar o layout, isso:
$tpl = new Template('caminho/views/post/layout.html');
$tpl->addFile('CONTEUDO', 'caminho/para/views/example-view-hello-world.html');
//aqui vão outras variáveis do template...
$html->show();

Com disse, o conceito de layout não é bem claro nesse sistema de template, mas deve funcionar.
Comment: Primeiramente, obrigado por responder. Bem, você citou vários exemplos, e acho que isso me confundiu um pouco... No primeiro exemplo da função que faria o trabalho de renderizar as views, eu não entendi o que vc fez, pq, pelo meu entendimento, vc carregou 2 arquivos diferentes, assim como eu já faço, pois você carrega o *$nome.html* e o *$layout.html*, então ficou meio confuso para mim... Poderia explicar melhor?
Comment: Eu aproveitei e editei a pergunta, colocando mais dados, para que fique mais claro e de amplo entendimento.
Comment: Esse sistema de template que você esta usando não usa layouts?
Comment: Qual o sistema de template que você esta usando?
Comment: Utilizo esse: https://github.com/raelgc/template
Comment: editei a resposta, veja se ajuda.
Comment: Muito obrigado, através da sua resposta pude abrir minha mente para poder adaptar ao meu código. Eu já conhecia e utilizava o addFile() porém nem havia pensado em utilizar ele nesse caso, vai economizar muito espaço e linhas de código! Hehe. As vezes a resposta está na nossa frente e a gente não vê. Muito obrigado!


Cron Job Throwing error 500 internal server error

Question: Cron job fails with Error 500 Internal Server Error
   I receive the following error
Status: 500 Internal Server Error
X-Powered-By: PHP/5.6.31
Set-Cookie: PHPSESSID=xxxxxxxx(I replaced the value); path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-
check=0
Pragma: no-cache
Content-type: text/html; charset=UTF-8

I have tried changing the cron.php file permissions to 744, 755, and 644 respectively but still does not work. I set up the cron with the command
/usr/bin/php /home/my_username/public_html/cron.php

Does anyone know how I can fix this?
Comment: This error message is response of the HTTP request, but `/usr/bin/php /home/my_username/public_html/cron.php` it is CLI command :|
Comment: The absolute first thing you do on a 500 Internal Server Error, is you _go check the server log files_ ...
Comment: @CBroe, the server log files are empty, I should have mentioned that in my question.
Comment: @Neodan, ur suggestion was very handy in solving the problem, thanks to you I changed my command to wget -O - my_domain.com/cron.php and everythihg now works very well.
Please answer the question so I can accept your answer. Thanks once again
Answer: This error message is a response of the HTTP request, but /usr/bin/php /home/my_username/public_html/cron.php is the CLI command.
The problem can be in that your cron.php is not designed to work via CLI (try to run it via wget).
Comment: superb! turns out that wget solves the problem. Here's the command that now works
_wget -O - my_domain.com/cron.php_
I hope this helps someone else
Answer: Just add up your openssl.conf path to end of your command like this:
-config G:\wamp64\bin\apache\apache2.4.35\conf\openssl.cnf

This will help to generate your own certificate without errors. For linux the directory should be:
/usr/bin/apache{Version}/conf/openssl.cfg


How is Db major functioning here? Subdominant Prolongation? Some kind of Dominant?

Question: While improvising for a piece in Eb major, I came across an interesting progression. Eb -> Ab -> Db -> Eb But something that I couldn't figure out was the function of the Db. Here is the progression:

I at first thought that since the rest of the chords were in a cycle of Tonic -> Subdominant -> Dominant -> Tonic, that Db was some kind of Dominant. But the dominant of what, Gb? And how does that explain its resolution to Eb? So then I thought "Well, maybe it's prolonging the subdominant, giving me a plagal cadence" but the cycle of the rest of the chords and the fact that it fits neatly into the progression seems to contradict that. Neither Secondary Dominant, nor Secondary Subdominant seem to fit the bill. Neopolitan doesn't fit the bill either because C minor doesn't occur until the next chord cycle.
So, what is the function of this Db chord? Prolonging the Subdominant? Some kind of Deceptive resolution? A dominant of some sort? Simply being there for the sake of Chromaticism?
Answer: The ♭VII chord is a very common dominant substitute, especially in popular music. It's relatively uncommon in the 18th century, but starting around the time of Dvorak or so we start to encounter it more often. (Perhaps it's not completely unrelated that Dvorak liked incorporating popular music of the day into his compositions.)
As such, your progression is still a clear tonic–predominant–dominant–tonic, just with a chord other than V substituting for the dominant.
As for why this "works," there are a few explanations. As just one, imagine we're in G♭. We have a V (built on D♭), but it resolves deceptively to vi (built on E♭). So we can just view, your ♭VII–I as a transplanted version of the deceptive cadence that resolves to E♭.
Answer: I hear the Db chord as part of a modulation, the IV chord of Ab major. Going back two bars, to the Eb chord, that functions as a pivot chord: I in the original key of Eb and V in the modulation key of Ab. The subsequent Ab then is I, Db is IV, and Eb is now established in my ear as V. You then reestablish the key of Eb with the subsequent chord progression.
I agree with @Richard that analytically the Db can be interpreted as serving a dominant function, as indeed the bVII chord sometimes does. But if that's the effect you want, rather than a modulatory one, then for my ear, it would be better to put the Db chord in root position. That way I can more clearly hear the 7 -> 1 voice-leading. That is, the note Db more clearly functions as a replacement for the leading tone.
Answer: Ever since the Beatles ♭VII has been a frequent visitor in popular music.   Sometimes it's acting as IV of IV (Get Back).  But very often it just exists on its own terms.  It's become an Honorary Diatonic Chord.   Accept this and move on.  Not everything is tonic, subdominant or dominant.  Not everything is Cycle of Fifths.   Insisting on forcing ♭VII into those terms is as silly as looking for parallel 5ths in guitar voicings (unless you're playing Bach).
Answer: Your intuition analyzed the chord as a IV of IV. That is actually a very good way of understanding the Db chord. Sub dominant and Dominant can be thought of as regions in tonal space. You can visualize it thus:
Sub-Dominant Region       Tonic      Dominant Region
Db --------- Ab --------- (Eb) --------- Bb ---------- F
Eb is the centre; the tonic.  Then one step to the left of the tonic you have the Sub-Dominant (Ab), then one more step to the left you have the SS (double subdominant), in this case Db. The Sub-dominant and Dominant sides of the graph can thus be extended outwards as far as you like. Seeing it this way I would caution against conceptualizing the chord as dominant; rather it is actually further into the sub-dominant region. Thus your idea of the IV of IV is very similar except in Functional Theory it would properly be named an SS (sub-dominant of sub-dominant). The notes would be same as a so-called bVII but IV of IV would be a much more reasonable analysis.
One person mentioned they hear it as a modulation and certainly the SS is out of key and can lead to modulation.


My difficulty with accepting the proof that C[a,b] is a complete metric space

Question: So, I have been studying mathematics seriously for 15+ years.  Every now and then, I run across a proof that I just have reservations about its validity.
Recently, I have been studying the proof that C[a,b], the metric space of continuous functions from R to C on the compact set [a,b] is a complete metric space with the sup norm.
I have read many texts and websites.  The proof given in Kenneth A. Ross " Elementary
Analysis" on page 186 is by far the clearest to me.
However, I am still having trouble convincing myself through rigorous mathematical reasoning that a Cauchy sequence of functions in C[a,b] actually does converge to its pointwise limit.
As Charles Pugh says, the proof is subtle.  " The uniform inequality d(fn,f) < epsilon
is derived by non-uniform means: for each x we make a separate estimate using an m(x) depending non-uniformly on x"
Can anyone of Math Stack explain to me ( an amateur ) in exquisite detail -- more detail
about the limiting process than any previous answers to this question--how the proof that a Cauchy sequence in C[a,b] actually does converge to its pointwise limit.
Comment: Try: https://math.stackexchange.com/questions/1224918/show-that-the-metric-space-ca-b-is-complete, https://math.stackexchange.com/questions/97356/is-the-space-c0-1-complete. If you still have questions, copy and paste one of the proofs into your question and mark where you get lost/are confused. EDIT: nevermind, I guess you've already looked at them? I'll put them here to establish some link bridges from the similar questions.
Comment: See  Theorem A.1 in https://kconrad.math.uconn.edu/blurbs/analysis/metricspaces.pdf, which breaks up the argument  into three steps: build the candidate limit function, prove that candidate is continuous, and then prove the sequence converges to it.  (You call $C[a,b]$ the continuous functions "from R to C on $[a,b]$".  That is not what the notation means: $C[a,b]$ is the continuous functions from $[a,b]$ to $\mathbf R$ or to $\mathbf C$.)
Comment: Sounds to me like the compactness is the magic step for you, does Heine-Borel cause any similar difficulties?
Comment: D.R. Yes, I have read all the proofs/explanations.
Answer: So we want to prove that $C[a,b]$ is a complete metric space under the metric $d(f,g) = ||f-g||_\infty = \sup_{x\in [a,b]}|f(x)-g(x)|$. To do this, we need to prove that for any Cauchy sequence $\{f_n\}$, where all the $f_n \in C[a,b]$, they converge to some $f\in C[a,b]$; putting this in math notation, we want to show that if for all $\epsilon>0$, there is $N \in \mathbb N$ such that $m,n\geq N \implies d(f_m,f_n)<\epsilon$, then there is some $f\in C[a,b]$ such that for all $\epsilon>0$, there is $N \in \mathbb N$ such that $n\geq N \implies d(f_n,f)<\epsilon$.
We can show the existence of such an $f$ by directly constructing such an $f$: take $f$ to be the pointwise limit of the $f_n$.
Step 1: We have to show that we can actually take the pointwise limit of the $f_n$. Ok; take any $x_0\in [a,b]$. Then, for any $n,m$, $|f_n(x_0)-f_m(x_0)| \leq d(f_n,f_m)$ which is $<\epsilon$ for $n,m$ sufficiently large. That means that $\{f_n(x_0)\}$ is a Cauchy sequence (of real numbers), and hence converges to some value (see: http://mathonline.wikidot.com/the-cauchy-convergence-criterion), which we'll call $f(x_0)$.
Step 2: We need to verify that $f$ is actually in  $C[a,b]$; this is true because the $f_n$ converge uniformly to $f$ (a fact we will prove in Step 3) and the $f_n$ are continuous. Details are in step (iii) of Is the space $C[0,1]$ complete?.
Step 3: Now that we have this candidate function $f$, let us prove that for all $\epsilon>0$, there is $N \in \mathbb N$ such that $n\geq N \implies d(f_n,f)<\epsilon$. So we've fixed some $\epsilon>0$ and found the corresponding $N\in \mathbb N$ s.t. $m,n\geq N \implies d(f_m,f_n)<\frac \epsilon3$; then
$$d(f_n,f) \leq d(f_n,f_N) + d(f_N, f) < \frac \epsilon 3 + d(f_N,f) \qquad (0)$$
We now have to develop a bound for $d(f_N,f)$. We do this pointwise. For any $x_0\in [a,b]$, we have for any $m\geq N$:
$$|f_N(x_0) - f(x_0)| \leq |f_N(x_0)-f_m(x_0)| + |f_m(x_0) - f(x_0)| \qquad (1)$$
Well we know that for any $m\geq N$, $|f_N(x_0)-f_m(x_0)|\leq d(f_N, f_m) < \frac \epsilon 3$ (so the first part of this bound comes from the uniform bound). But we also know that since $\lim_{m\to\infty} f_m(x_0) = f(x_0)$, we can make $|f_m(x_0) - f(x_0)|$ as small as we want by choosing sufficiently large $m$. We can in fact choose $m$ as big as we want because recall the above inequality $(1)$ holds "for any $m\geq N$", and so we can definitely choose $m$ large enough to force $|f_m(x_0) - f(x_0)| <\frac \epsilon 3$. Thus, we can rewrite $(1)$ to be
$$|f_N(x_0) - f(x_0)| \leq |f_N(x_0)-f_m(x_0)| + |f_m(x_0) - f(x_0)| < \frac \epsilon 3 + \frac \epsilon 3 \qquad (1')$$
The magic of this part of the proof is that we split $|f_N(x_0) - f(x_0)|$ into two pieces involving the parameter $m$, where $m$ was chosen cleverly to get a bound on those two pieces NOT involving $m$!
To summarize, in this step, we proved that for all $x_0\in [a,b]$, $|f_N(x_0) - f(x_0)| < \frac {2\epsilon}{3}$. That means that we can take the supremum over ALL $x_0 \in [a,b]$ and keep a weak version of the bound:
$$d(f_N, f) = \sup_{x_0 \in [a,b]} |f_N(x_0) - f(x_0)| \leq \frac {2\epsilon}{3}$$
Putting this with $(0)$, we get that
$$d(f_n,f) \leq d(f_n,f_N) + d(f_N, f) < \frac \epsilon 3 + d(f_N,f) < \frac \epsilon 3 + \frac {2\epsilon}{3} = \epsilon$$

Thoughts: it seems the confusion in your question comes in Step 3 -- I hope I have made clear to you which bounds come from the uniform $d(f,g)$ type bounds and which bounds must be argued pointwise.
Comment: D.R.  Members like you are why I absolutely adore MathStack!   You are correct, my hurdle is step 3.  I will spend some quality time this morning with your detailed explanation of how to create the bounds on the point wise convergent sequence.


Implement VAR model in R with HAC corrected standard errors

Question: I have fitted a VAR model in R (with function VAR) and would like to use HAC corrected standard errors. How is that possible?
Answer: Given that VARs are simply estimated via equation-by-equation OLS, you could fit each equation by lm and then obtain HAC standard errors from the sandwich package.
Example:
library(sandwich)

n <- 100
y1 <- arima.sim(list(ar=0.5), n)
y2 <- arima.sim(list(ar=0.7), n) # so, not really a VAR but two independent AR(1) processes, just for simplicity

eq1 <- lm(y1[2:n]~y1[1:(n-1)]+y2[1:(n-1)])
eq1 <- lm(y2[2:n]~y1[1:(n-1)]+y2[1:(n-1)])

vcovHAC(eq1)

It may also be worth contemplating why you aim to use HAC standard errors. If your goal is to capture serial correlation in the errors, a more natural strategy would seem to include higher lags in the VAR model.
Comment: Many Thanks Christoph. What about the impulse response function? I can only present it via a VAR-object and this workaround would not provide me with such an object. Do you think robust standard errors are more suitable than HAC-errors?
Comment: Two questions here: for the point estimates of the IRF, you can still use the standard var package as these are not related to the s.e.s. For error bands, I would suggest a bootstrap that also deals with heteroskedasticity (as I mentioned, if you still encounter serial correlation I suggest adding more lags to the VAR).
Comment: 2nd: "Do you think robust standard errors are more suitable than HAC-errors?" HAC s.e.s *are* a type of robust s.e.s, also being robust to serial correlation and not just heteroskedasticity. But as I said, s.e.s only robust to heteroskedasticity seem more sensible in a VAR, as remaining serial correlation should, in my view, be captured through extra lags in the VAR.


Allow non-admin users to view an EntityForm submission

Question: I've created an EntityForm wich authenticated users can submit.
Then I've created a view wich list every entityForm submissions and everyone can see this view.
Now I want to add a field to this view. This field will contain a link to this specific EntityForm submission.
2 solutions:
-Display the direct link "Entityform Submission: Link"
-Display an URL "Entityform Submission: URL"
As an admin:

Those solutions both work, but only as an administrator!
The link is invisible for non-admin persons.
The URL leads to a "Access denied - You are not authorized to access this page."
As a non-admin:

Question : How can I allow non-admin users to access entityForm submission pages?
Thanks!
Answer: By creating a new permission maybe ? Then create the access page via an menu item with the new permssion you created
Give this permission to non authenticated users then.
Comment: You're right! I totally forgot the permission panel.


Estimate the best ARMAX model with one lagged independent variable (time series)?

Question: I have two time series to work with, let's say $X_1$ and $X_2$.
First I have to estimate the best pure ARMA model for $X_1$; which is no problem. For that I perform the following steps:

Stationarize (if needed) the time series by differencing
Determine whether AR/MA terms are needed to correct any
autocorrelation in the differenced series -> tentatively identify the maximum number of AR and/or MA terms using ACF and PACF plots
Then estimate different models, store BIC values, construct a matrix of BIC values, and select the ARMA model with the lowest BIC value.

Now comes the part that confuses me. I have to estimate an ARMAX model for $X_1$, where I need to put $X_2$ as a lagged explanatory variable in the ARMAX model.

I don't think that including the exogenous variable will change the number of AR and MA terms for the best model relative to model estimated before. If e.g. ARMA(2,1) has the lowest BIC relative to the other ARMA models, ARMAX(2,1) will also have the lowest BIC relative to the other ARMAX models. Is that true?
What is meant by including the 'lagged' explanatory variable? Does that mean the one-period lagged values of $X_2$? Or do I have to find the optimum number of lags for $X_2$ using a statistical technique?
Answer:
I don't think that including the exogenous variable will change the number of AR and MA terms for the best model relative to model estimated before.

I highly doubt that. I do not remember any result regarding under which conditions this would hold. This would be a special case.

What is meant by including the 'lagged' explanatory variable? Does that mean the one-period lagged values of X2? Or do I have to find the optimum number of lags for X2 using a statistical technique?

It is difficult to know what someone meant without seeing the context, but generally you would either rely on subject-matter knowledge or use statistics (or both).
For a reference, you may find Rob J. Hyndman's blog post about ARIMAX and related models useful. It highlights the differences between the different versions of the model (or should I say, the different but related models), mentions software implementations and has a take on their interpretations, too.
Answer: Hi: An ARIMAX can be viewed as a transfer response model so you could look that up. If there are no MA terms in the model,  then it can also be viewed as an ARDL(p,1) so I would look up how to estimate ARDL's also. This material is involved so I wouldn't try to give an estimation algorithm here. Hendry's approach is somewhat popular for ARDL's but you already know that q = 1. Generally speaking, if you are going to limit yourself to q=1, then the latest lag that's available should be used. But you should check if it helps ( does the regressor help explain the response ) using say a granger causality type of test.
As far as your claim about the ARIMA part staying the same when one adds the regressor, that is not the case.
The text by Pankratz contains a lot of examples of dynamic regression models and yours is a special case of those so you might want to check that book out. It's not amazing and it's pretty old but there are a lot of examples and he gives steps on the estimation approach. All the best.
Answer: You can start by reviewing a very basic tutorial here.
Also How to include control variables in an Intervention analysis with ARIMA? might be of help.