when clicked on dropdown list item call a same list item name function in javascript?

Question: dropdown list contain 3 item namely emp name, prod info, sales status, when i clicked list item, it should call function same list item name. here i am doing when i clicked list item, item name space removing and and calling to function but it not calling. how can i do. bellow is i tried code.
html
----

emp name

prod info

sale status

javascript
----------
jQuery("ul .item").click(function(){
   var x = $(this).text();
   var y = x.replace(/\s+/g, '');
        y+();
});
function empname(){
  console.log("emp");
}
function prodinfo(){
   console.log("prodinfo");
}
function salestatus(){
  console.log("salesstaus");
}

Comment: call like this window[y]();
Comment: i tryied but it not calling
Answer: You should use the eval().

jQuery("ul .item").click(function() {
  var x = $(this).text();
  var y = x.replace(/\s+/g, '') +"()";
  eval(y)
});

function empname() {
  console.log("emp");
}

function prodinfo() {
  console.log("prodinfo");
}

function salestatus() {
  console.log("salesstaus");
}

emp name

prod info

sale status

Answer: You can try this
jQuery("ul .item").click(function(){
   var x = $(this).text();
   var y = x.replace(/\s+/g, '');
    //console.log(y);
    eval(y +'()');
});
function empname(){
  console.log("emp");
}
function prodinfo(){
   console.log("prodinfo");
}
function salestatus(){
 console.log("salestatus");
}

Comment: Dhaval, did you check the previous answer before you made yours?  there is not much point in making identical answers
Comment: No when my answer place and after refresh page and i am see ans will be already given
Comment: **From review queue**: May I request you to please add some context around your source-code. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post.
Comment: Ok next time i am do as per you say
Answer: Why should you depend on some dynamic way of calling function by processing string between html tags. The text using between the html tags are for reading purpose only. you should not process it, because incase, if you are changing the text value to somehow it will affect your coding and the code needs to be changed according to the text. and if the predefined functions are already known, you can do it in the below way.

emp name

prod info

sale status


Forecasting: Is correct to say "If the time series is non-stationary" don't use ARIMA models?

Question: In case I dont want to "pre-process" the time series. I do a unit root test, and if it gives that is a non-stationary time series, then I will stay away from ARIMA models.
Is this correct?
Answer: You probably are talking about stationarity of the mean. In this case the statement is incorrect because ARIMA handles so called integrated models, such as those with unit roots. Integrated means that it's on differences like $\Delta y_t$. ARIMA(0,1,0) is your standard random walk model.
So, the statement is too generic to be true. However, in some special cases it holds. For instance, if your process is nonstationary in variance, i.e. the error variance is not conditionally stationary. An example is exponential random walk. In this case a simple log-transform would make it ARIMA(0,1,0) but you indicated that no pre-processing is allowed, so your statement would be correct.
Summarizing, depending on circumstances your statement could be true, but it is not true always.
Comment: Thank you @Aksakal. What test can i do to know that a process is or is not conditionally stationary? Because as i can understand from your great answer. It would be the test that will make this statement correct.
Comment: @donpresente To see whether the error variance is stationary, you can look at the series of squared differences. If they're growing, then the error must be increasing. I don't use any formal tests for this.
Comment: so you mean (R_t - R_{t-1})^2, where R is the value that takes the time series at time t. Or you mean the errors? Thanks!
Comment: Yes, that's what I meant. You can regress this over time to see if there is significant trend
Answer: No. For instance, a random-Walk has a unit root, and it's an ARIMA(0,1,0).
Comment: (+1) But you might expand on what the "I" in "ARIMA" means.
Comment: The I means integrated, so in fact, you should typically expect ARIMA processes to have unit roots.


How can I serialize a redundant object to the serializer?

Question: I have a model name CloudServer, which has a openstackserverid field, through it I can get a object:
class CloudServer(models.Model):
    openstackserverid = models.CharField(max_length=128)
    buytime = models.ForeignKey(to=BuyTime)
    expiration_time = models.DateTimeField()
    availablearea = models.ForeignKey(to=AvailableArea)
    profile = models.TextField()

In the serializer:
class CloudServerListSerializer(ModelSerializer):
    class Meta:
        model = CloudServer
        fields = "__all__"

In the views:
class CloudServerListAPIView(ListAPIView):
    serializer_class = CloudServerListSerializer

I can use the bellow function to get the openstackserver object.
def getOpenstackServer(openstackserverid):

    ...
    return openstackserver

The openstackserver object is like bellow:
openstack.compute.v2.server.ServerDetail(OS-EXT-STS:task_state=None,
addresses={u'private': [{u'OS-EXT-IPS-MAC:mac_addr': u'fa:16:3e:23:75:7b', u'version': 4, u'addr': u'192.168.1.8', u'OS-EXT-IPS:type': u'fixed'}]},
links=[{u'href': u'http://controller:8774/v2.1/99a50773b170406b8902227118bb72bf/servers/0672107f-e580-4a24-9d0a-867831d6b7d2', u'rel': u'self'}, {u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/servers/0672107f-e580-4a24-9d0a-867831d6b7d2', u'rel': u'bookmark'}],
image={u'id': u'ecbd1ef0-7dcf-41ff-8618-4501aa4e3945',
u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/images/ecbd1ef0-7dcf-41ff-8618-4501aa4e3945', u'rel': u'bookmark'}]},
OS-EXT-STS:vm_state=active, OS-EXT-SRV-ATTR:instance_name=instance-00000047, OS-SRV-USG:launched_at=2017-11-10T12:52:09.000000, flavor={u'id': u'a27c55bc-ef20-4dcf-a924-a02a4361fc01',
u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/flavors/a27c55bc-ef20-4dcf-a924-a02a4361fc01', u'rel': u'bookmark'}]}, id=0672107f-e580-4a24-9d0a-867831d6b7d2,
security_groups=[{u'name': u'default'}], user_id=fb52853bde3d4d3e8e831749781f8671, OS-DCF:diskConfig=MANUAL, accessIPv4=, accessIPv6=, progress=0, OS-EXT-STS:power_state=1, OS-EXT-AZ:availability_zone=nova, metadata={}, status=ACTIVE, updated=2017-11-10T12:52:09Z, hostId=76f61a58cf6d411a30e3e34da4dd252a03aa0093d9dd19c653b234b3, OS-SRV-USG:terminated_at=None, key_name=None, OS-EXT-SRV-ATTR:hypervisor_hostname=controller, name=vm-00000, created=2017-11-10T12:51:44Z, tenant_id=99a50773b170406b8902227118bb72bf, os-extended-volumes:volumes_attached=[], config_drive=)

So far, as all I know, I only can serialize the CloudServer model's fields.
Where I can serialize the object, is in the serializers or views ? and how to do with that?
Comment: The `openstackserver` object is a django Model ?
Answer: If I understand correctly, the openstackserver is not a Django Model.
You could add a method field in your serializer:
Firstly, you will need to define a serializer for your openstackserver objects:
class OpenStackServerSerializer(serializers.Serializer):
    """Serializer for the `openstackserver` object"""

    addresses = serializers.DictField()
    # Other fields of your `openstackserver` object

    class Meta:
        fields = (
            'adresses',
            # Other fields of your `openstackserver` object
        )

class CloudServerListSerializer(serializers.ModelSerializer):
     """Serializer for the `CloudServer` object"""

     openstackserver = serializers.SerializerMethodField()

     class Meta:
          fields = (
              'openstackserver',
              # Other fields...
          )

     def get_openstackserver(self, cloud_server):
         """Get the openstack from the current `CloudServer` instance and serialize it"""

         openstackserver = getOpenstackServer(cloud_server.openstackserverid)
         return OpenStackServerSerializer(openstackserver).data

Like this, you should have a representation of each openstackserver associated with your cloud server.
Comment: whats the `instance` of ` def get_openstackserver(self, instance)`  means?
Comment: The `instance` of the `get_openstackserver` method is populated using the current `CloudServer` instance of the serializer. So `instance` = an instance of your Django `CloudServer` model. You can rename this argument whatever you think best.
Comment: @qg_java Renaned the `instance` param to `cloud_server` be more clear.


Why doesn't this script run like it should?

Question: I tried to write a script which reads the cells in a .xlsx file (result is the name of an .eml) and check if the .eml is in the directory /vagrant/E-Mails.
It executes a shell script which puts all .eml files in the directory into the eml.txt file.
If I do:
>> python optest.py

it still says:

E-Mail not found

...but there are those .eml files in the directory.
Can you help me to solve this please?
from openpyxl import load_workbook
import subprocess

testcases = load_workbook('/vagrant/Excel/testcases.xlsx')
testcases_ws = testcases.active
profil = testcases_ws['A2']
print profil.value

testmails = load_workbook('/vagrant/Excel/testmails.xlsx')
testmails_ws = testmails.active
eml = testmails_ws['A2']
eml = eml.value
print eml
path = "/vagrant/E-Mails/"

subprocess.Popen(['sh', "/vagrant/test.sh"])

if eml in open("eml.txt", "r"):
        print "E-Mail ´found"
else:
        print "E-Mail not found."

Answer: if eml in open("eml.txt", "r"):

Here, you're using the in operator on the file object returned by open. This will only succeed if eml exactly matches a complete line in the file, including a terminating newline. For a more lenient matching approach, try using in on the string contents of the file instead.
if eml in open("eml.txt", "r").read():


Serviço permanente em background

Question: Como correr um serviço permanente em background. Por exemplo eu quero que a minha app esteja sempre a correr este método :
           public void addToCalendar(){

    myDB = CustomApplication.getDatabaseHelper();
    ColorDrawable blue = new ColorDrawable(Color.BLUE);
    for(int i=1;i <= myDB.getLastId();i++){
        String dt = myDB.getDates(i);
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy");
        Date teste = null;
        try {
            teste = sdf.parse(dt);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        caldroidFragment.setBackgroundDrawableForDate(blue,teste);
    }
}

Answer: Se você quer rodar em background, você vai precisar utilizar uma AsyncTask.
Dentro da AsyncTask tu coloca essa sua implementação.
E para rodar ela de tempo em tempo, tu pode utilizar um timer.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
     @Override
     public void run() {
       handler.post(new Runnable() {
          public void run() {
             new MinhaTask().execute(); //Dentro da Task tu coloca seu código
          }
        });
      }
};
timer.schedule(task, 0, 1000); //1000ms
Espero ter ajudado!
Comment: Me ajudou mas como estar sempre a rodar em background deve ser dispendioso tenho uma duvida . Sabe como executar uma acção quando se muda de tab ? Ja pesquisei por isso mas aparece la um tal de TabHost que não sei o que é .
Comment: Não entendo a forma como está a fazer isso. Por que usar uma AsyncTask quando o Timer já executa o TimerTask em outra Thread?
Comment: @ramaral **Te aconselho a tentar por um código que execute bastante coisa, desta forma que tu pensou.** Mas pense o seguinte, a cada 1 segundo o TimerTask vai executar o run(), o que vai acontecer se sua tarefa não terminou de executar os comandos do run() que foram chamados anteriormente?
Comment: @PedroGouveia Se você está utilizando tabs no seu APP, acredito que tu tenha um "PageViewerAdapter", e como você quer executar uma ação ao mudar a tab, use ViewPager.onPageChangeListener no seu adapter.

Vou te deixar um link de um vídeo para ver se ajuda (criação de tabs):
https://www.youtube.com/watch?v=00LLd7qr9sA,
Comment: @TiagoAlmeida Você tem razão é por isso que um Timer só deve ser usado para executar tarefas curtas. No entanto o AsyncTask sofre do mesmo problema quando se usa o método `execute()`. Ambos, Timer e `AsyncTask.execute()` usam apenas uma thread, assim a tarefa seguinte só é iniciada quando a anterior terminar. O seu código só resolveria esse problema se usasse `AsyncTask.executeOnExecutor()`, mas continuaria a ser uma "gambiarra".
Comment: @ramaral, mas se a cada chamada do run(), você chamar um "new AsyncTask().execute" , por exemplo, você tá criando uma outra thread, e não executando a anterior. Ou seja você vai criando várias threads independentes, e cada uma vai executar o seu "serviço". Mas aí tem que tomar cuidado, pra não executar muitas threads pesada, porque pode deixar o dispositivo lento ao rodar tantas threads pesadas em background. Tem que ser jogo rápido.
Comment: Está enganado, as AsyncTask, quando iniciadas por `execute()`, são todas executadas numa mesma Thread, veja a nota na [documentação](https://developer.android.com/reference/android/os/AsyncTask.html#execute%28Params...%29), ou veja a minha [resposta](https://pt.stackoverflow.com/a/83856/2541) a [Sequência de execuções para AsyncTask](https://pt.stackoverflow.com/q/83831/2541).
Comment: @ramaral, entendi o que você quiz dizer, e tu está correto no seu ponto de vista. Mas, eu **estou me refirindo à interrupção da AsyncTask**, que pode ocorrer caso não tenha uma AsyncTask no método run() do timer, entende? (Que foi isso que você me perguntou, o porque de uma AsyncTask dentro de uma Thread) Com a AsyncTask no método run(), isso vai garantir que o código, que está dentro da AsyncTask, seja executado do início ao fim, sem interrupção. Independentemente de quantas AsyncTasks estiverem ali dentro do método run(), todas vão ser executar o que tiver que executar.
Comment: Não entendi o que quer dizer. A única razão que eu vejo para ter o código assim é para que a mesma tarefa seja iniciada, no tempo estipulado, mesmo que a anterior não tenha terminado. Se a ideia é essa eu substituía a AsyncTask por um Executor e usaria um Handler em vez do Timer. De qualquer forma é estranho querer executar **uma mesma** tarefa antes de terminar a anterior.

Serviço permanente em background


circle ci module is not installed

Question: I have a container on circle ci that goes through all tests and does a npm install to install all packages in the package.json. But it seems some packages is not installed causing circle ci to fail
error
 22:24  error  Unable to resolve path to module 'react-helmet'  import/no-unresolved

Even dough I can see the package is in package.json
"react-helmet": "^5.1.3",

what could be the problem?
Comment: Can you provide more information? Like the package.json file and the circle.yml file
Answer: Adding npm install -g to circle.yml fixed it

circle ci module is not installed


Create Publish Profile to Azure App Service, throw "The file Exists"

Question: I'm trying to create publish profile to Azure App Service using Visual Studio 2022.
When I created App Service from vs publish dialog (clicking on plus sign button). It threw an error The file exists.
The same error happened when I had created App Service from portal.azure.com.

I've also tried to create publish profile from App Service overview page and import it when creating publish profile in visual studio. But the screen just stops at browse settings file page.

I'm not sure if this is useful, but my project are:

ASP net Core MVC
.net6

let me know if you need more information.
Answer: After some time with Microsoft technical support we have solved the problem.
In our case we need to publish the project using FTPS.
This was our settings to get successfully publish this project.

Server: ftps://[some site name].ftp.azurewebsites.windows.net:990
FTP site path: /site/wwwroot
FTP passive mode: True
Get user name and password from App Service Deployment center (FTPS credentials)
Destination URL: https://xxxx.azurewebsites.net (from URL in overview page App Service)

That port number (990) was needed for successfully deploy. If you didn't include that port, you will get error

Could not find a web server at [server url you input]


Redimensionar imagens com Print.Window

Question: Eu tenho uma function que tira print de um imagem para poder imprimir a mesma.
Porém eu gostaria de saber se tem como mudar a posição desta imagem na hora que entra no método.
No momento a function abre assim a imagem

Gostaria de redimensionar a imagem em 90º à direita para poder pegar a folha (formato A4), isso é possível ?
Segue código:
function printPartOfPage(elementId) {
           var printContent = document.getElementById(elementId);
            var printWindow = window.open('', '', 'left=10,top=10,width=740,height=600');

            printWindow.document.write(printContent.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();
        }

Answer: Igor no CSS da sua página vc pode fazer um estilo para mudar a orientação da folha apenas na hora da impressão dessa forma.
@page {
  size: A4 landscape;
}

Talvez vc tenha que adaptar seu JS para chamar esse css caso vc não use css no projeto.
Veja um exemplo prático:

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
div {
    width: 90%;
}
@page {
  size: landscape;
}

Com esse exemplo acima obtive esses resultados
COM @page size: landscape

SEM @page size

Aqui tem uma documentação da Mozilla sobre o @page https://developer.mozilla.org/en-US/docs/Web/CSS/@page/size

Redimensionar imagens com Print.Window


What does the "a" in the html  tag stand for?

Question: As  most of you know, the  tag is (mostly) used in html to make a hyperlink like
Click me

But I've always wondered what the "a" in the  tag actually stands for.
Comment: @MrLister I got to this page from google. This question and answers were useful to me.
Comment: Yup, IMO, this page adds value to the Internet because when searching for "html what does a stand for", this page comes to the top, answering simply and specifically, while others do not--at least not on the first page.
Comment: You would have gotten your answer far quicker if you had just typed your question into Google.
Comment: This was called an anchor because it doubles as a fixed location on a page. When used with the hash symbol, the anchor tag allows one to link to that fixed location. The browser will scroll down and everything.
Answer: a stands for anchor. As easy as that!
Comment: Note that `a` tags are (or used to be) used to to define the anchor (where the link lands, via the `name` attribute) as well as the outgoing link (via the `href` attribute).
Comment: Right, and I think the word `anchor` makes a lot more sense with the other use (to anchor an incoming link), so I thought I would point that out, especially since many people don't know that use (and it is sort of deprecated now that you can use `id` tags on anything).
Comment: @Thilo BTW OP isn't asking about how to use `` but what is `a` *as is*
Answer: According to HTML Documentation part 4.5.1 the  tag refers to a HTMLAnchorElement
Answer:  Stands for anchor tag.
The  tag defines a hyperlink, which is used to link from one page to another.
The most important attribute of the  element is the href attribute, which indicates the link's destination.


Showing symmetry involving a matrix and its transposed matrix

Question: I'd appreciate if someone could find a better title for this question, for I'm short of ideas right now.
Given a matrix $A \in R^{n,n}$, show that
$$
\frac{1}{2}(A + A^t)
$$
is symmetric.
I see that it's symmetric and it seems obvious, but I don't really know how to show that in particular.
Answer: $(B+B^t)^t=B^t+(B^t)^t=B^t+B$
So $B+B^t$ is symmetric $\forall B\in R^{n\times n}$.
Take $B=A/2$ and you get the desired result.
Answer: You should apply the known properties of transposition:

$(cX)^t=cX^t$ (where $c$ is a scalar and $X$ is any matrix);
$(X+Y)^t=X^t + Y^t$ (where $X$ and $Y$ are matrices and the sum is defined).

Moreover, recall that $X+Y=Y+X$. That's all you need: set
$$
C=\frac{1}{2}(A+A^t)
$$
and apply the properties to show that $C^t=C$.
Answer: Are you familiar with 'entry notation' to represent arbitrary elements in a matrix?  I am omitting the scalar, but the idea is to show $ent_{ij}(A+A^T) = ent_{ij}(A+A^T)^T$, where
$$ent_{ij}(A^T) = ent_{ji}(A).$$


SVM: Does C increase variance or stability (bias)?

Question: I was learning about SVM using 2 sources: Andrew Ng Machine Learning course from Coursera and Stanford 'Statistical Learning' (from Trevor Hastie and Robert Tibshirani). And I encountered the following contradiction:
Andrew Ng provides this formula for SVM cost function:
$$C\sum_{i=1}^m[y^{(i)}cost_1(\theta^Tx^{(i)})+(1 - y^{(i)})cost_0(\theta^Tx^{(i)})] + \frac{1}{2}\sum_{i=1}^n\theta_j^2$$
(He doesn't dive into details about $cost_1$ and $cost_0$, but says they are more or less like log-likelihood loss in logistic regression, but linear.)
Then he says that increasing $C$ leads to increased variance - and it is completely okay with my intuition from the aforementioned formula - for higher $C$ algorithm cares less about regularization, so it fits training data better. That implies higher bias, lower variance, worse stability.
But then Trevor Hastie and Robert Tibshirani say, quote:

And that means that $C$ gets bigger the more stable the margin becomes.

Also they show the following picture - the larger margins correspond to larger $C$, they say.

Stability implies higher bias, right? So they say the opposite to Andrew Ng.
So the question is who is right?
Answer: I'm not sure but I think contradictory definitions are in effect in the literature.
Introduction to Statistical Learning basically formulates C as the total "budget" for errors (i.e. violations of margins). So higher C means more errors are allowed (which will lead to lower variance).
However, in other implementations, for example this one cited by sklearn's SVM docs --
https://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf
-- C is a multiplier of the sum of the errors in the cost function, so higher C means that errors are encouraged to be smaller (which will lead to higher variance).
Answer: The effect of the SVM C-Parameter
While the first textbook description of an SVM always speaks of "maximizing the margin", but this is only the first step. If your data is not perfectly separable there will points on the wrong side of the separating hyperplane.
To allow for such points slack variables were introduced (= soft-margin SVM). They include the problematic points into the equation and weight them using the C-Parameter.
This parameter is a tradeoff between maximizing the margin and minimizing the error.
Why this?
Imagine (or draw on a paper) a perfectly separable 2D dataset with a plot similar to the above. Imagine a suitable hyperplane. Image you have a hard margin svm which does not allow for such misclassified points.
Now imagine you will break the rules and place a document intentionally on the other side of the hyperplane. The hyperplane will probably change a lot and will be worse than before. If you had used a soft-margin SVM instead the old solution would still be a better one.
Your example
Increasing the value of the C-Parameter
$\iff$ Weight of misclassified points is increased
$\iff$ Margin gets smaller
And i think that is what Hastie and Tibshirani meant in terms of stable: In other words closer to the hard-margin SVM.
Comment: Then I believe Hastie and Tibshirani used a really unintuitive word here. For large C, as you mentioned, a single additional observation on the wrong side of the margin/decision boundary may dramatically shift/turn it. That situation is the opposite to the stability.
Comment: Stable as in "the number is misclassified points is reduced (less mix-ups between both sides of the hyperplane)". However this is only my interpretation of your quotes from the above post. (I have experience with SVMs and know the coursera course, but i have not had a look yet at the stanford course.).


Skip a media timeout in NCAA basketball?

Question: In NCAA basketball, there are media timeouts at the first whistle after the 16:00, 12:00, 8:00 and 4:00 minute marks of each half.
What happens if there is no whistle from the four minute mark until the half-time or final buzzer? It almost happened in this game here:
<code>MISSED 3 PTR by Jones, Johnathon                00:09
REBOUND (OFF) by (TEAM)                         00:09
TIMEOUT MEDIA                                   00:08
GOOD! JUMPER by Waterstradt, Dan                00:06  34-42  V 8
ASSIST by Cushingberry, Blake                   00:06
</code>
http://www.ougrizzlies.com/sports/m-baskbl/stats/2008-2009/mich1220.html
What would have happened if there was no whistle at 0:08?
Comment: The TV stations would go bankrupt! :)
Comment: @Jae This is a rules question, as the media timeouts are written into the NCAA rules, whether or not the game is on TV or radio.
Comment: I think this question is more about the broadcast then the sport.
Comment: @Jae there are other qualifying criteria, but the most straightforward is that because media timeouts are part of the official rules of the NBA, it qualifies as an on topic question.
Comment: Did I say NBA? I meant NCAA. I think they're written into NBA too.
Answer: I am unaware of any game in which this actually happened, but this is my interpretation of the rules:

By rule 5, section 13, the media timeouts take place "at the first dead ball" after the 16, 12, 8, and 4-minute marks (or 15, 10, and 5-minute marks, depending on the agreement, but this is rare).
By rule 6, section 5:

The ball shall become dead or remain dead when:
  [...]
  e. Time expires for a half or extra period.

Therefore, if there were no stoppages of play in the last four minutes, there would be a media timeout immediately preceding halftime.
This would be consistent with other timeout rules; it is, in fact, legal to call a timeout during halftime or between the second half and overtime (though two successive timeouts cannot be called during such break periods; see Approved Ruling 161 in the 2012 Case Book).
As a side note, if there were no stoppages in play between the 9:00 and 3:30 mark and a player is fouled in the act of shooting, the 8 minute timeout would occur before the first free throw and the 4 minute timeout would occur at the next dead ball, which is before the second free throw (AR 159).


Partial fractions- Equating coefficients

Question: This is a partial fraction question. Kindly could you assist me with finding the values for A, B and C as I'm not very clear on how to go about it. The question is as follows;
$$\frac{3-x}{(x^2+3)(x+3)}$$
And we want A, B, C so that  $$\frac{3-x}{(x^2+3)(x+3)} = \frac{Ax+B}{x^2 + 3} + \frac C{x+3}$$
I know that $A+B= 3$, $3B+C= -1$ and $3A+3C= 0$
The problem I'm facing here is with equating coefficients. I also know that after equating coefficients, the final values you get for A,B and C are as follows;
\begin{align}
A&= -1/2\\
B&= 1/2\\
C&= 1/2
\end{align}
But how do you solve with equating coefficients? Can you provide me step-by-step working for this please. I'm not facing any difficulty with partial fractions but just equating coefficients part in this case. Please help.
Many thanks.
Comment: First, your expression isn't clear. Use more parentheses, or much better: write mathematics with LaTeX . Second, if you already know that $\,A+B=3\;$, then it can't be $\,A=-\frac12=-B\;$ ...
Answer: It looks like you already have equated coefficients:
$$\frac{3-x}{(x^2+3)(x+3)}=\frac{Ax+B}{x^2+3}+\frac C{x+3}$$
$$\iff \frac{\color{blue}{(Ax+B)(x+3)+C(x^2+3)}}{(x^2+3)(x+3)}= \frac{\color{blue}{3-x}}{(x^2+3)(x+3)}$$
Equating the numerators:
$$(Ax+B)(x+3)+C(x^2+3) = 0\cdot x^2 -x + 3\tag{1}$$
Expanding the LHS of equation $(1)$, gathering like terms:
$$Ax^2 + (B + 3A)x + 3B + Cx^2 + 3C = 0x^2 - x + 3$$
$$\iff \color{blue}{\bf (A + C)}x^2 +\color{red}{\bf (3A + B)}x + \color{green}{\bf (3B + 3C)} = \color{blue}{\bf 0}x^2 + \color{red}{\bf (-1)}x + \color{green}{\bf 3}\tag{2}$$
Match up (color coded above) coefficients on LHS with those on RHS of $(2)$:
$$\iff \color{blue }{\bf A + C = 0}, \quad \color{red}{\bf 3A + B = -1}, \quad \color{green}{\bf 3(B + C) = 3 \iff B+C = 1}$$
Indeed, this gives us a system of $\bf 3$ equations in $\bf 3$ unknowns, from which we can solve for the "unknowns" $A, B, \;\text{and}\; C$.
$$\begin{align} A + C & = 0 \tag{i}\\  3A + B & = -1 \tag{ii}\\ B+ C & = 1\tag{iii}\end{align}$$
Subtract $(iii)$ from $(i)$: $A - B = -1\tag{iv}$
Adding $(iv)$ to $(ii)$ gives us $4A = -2 \iff A = -\dfrac 12\tag{A}$
From $(i)$: $A = -\dfrac 12 \implies C = \dfrac 12\tag{C}$
From $(iii)$: $C = \dfrac 12 \implies B = \dfrac 12\tag{B}$
Therefore, we have the following function, replacing coefficients A, B, C with their found values:
$$\frac{3-x}{(x^2+3)(x+3)}=\frac{Ax+B}{x^2+3}+\frac C{x+3} $$ $$= \frac{-\frac12\cdot x+\frac 12}{x^2+3}+\frac {\frac 12}{x+3}=\dfrac 12\left(\frac{1-x}{x^2 + 3}\right) + \dfrac 12\left(\frac 1{x+3}\right)$$
Comment: Thank you so much @amWhy! This really helped.
Comment: You're welcome! Thank you ;-)
Answer: Here I give an alternative method:
Let denote the partial fraction by
$$F(x)=\frac{3-x}{(x^2+3)(x+3)}$$
I guess from your question that you want a decompostion of $F$ over $\mathbb R$ so we have:
$$F(x)=\frac{C}{x+3}+\frac{Ax+B}{x^2+3}$$
We find $C$ by:
$$C=(x+3)F(x)\big|_{x=-3}=\frac{1}{2}$$
and for $A$ and $B$ we have
$$F(x)(x^2+3)\big|_{x=i\sqrt{3}}=\frac{3-i\sqrt{3}}{i\sqrt{3}+3}=\frac{1}{12}(6-i6\sqrt{3})=Ai\sqrt{3}+B$$
so we find
$$A=-\frac{1}{2}\quad,\quad B=\frac{1}{2}$$
Answer: Step 1: Write $$\frac{3-x}{(x^2+3)(x+3)}=\frac{Ax+B}{x^2+3}+\frac{C}{x+3}$$
Step 2: Expand the RHS to get
$$\frac{Ax+B}{x^2+3}+\frac{C}{x+3}=\frac{(Ax+B)(x+3)+C(x^2+3)}{(x^2+3)(x+3)}=\frac{(A+C)x^2+(3A+B)x+3(B+C)}{(x^2+3)(x+3)}$$
Step 3: Compare the coefficients.
$$x^2:A+C=0,\quad x:(3A+B)=-1,\quad\text{constant}: 3(B+C)=3$$
Step 4: Solve simultaneous equations.


Formula for the sequence -1/2, 0, 1/10, 0, -1/26, 0, 1/50, 0, -1/82

Question: I came up with the formula (1/2)*((-1)^n-1)/(n^2+1), however, this would result in the sequence -1/2, 0, -1/10, 0, -1/26, 0....
I know the expression (-1)^n-1 is making the sequence alternate from negative to positive, any ideas on how to make it change as -1, 1 1, 1, -1, 1, 1, 1, -1... or
-1, -1, 1, 1, -1, -1, 1, 1, -1, -1...
Comment: The question in the title and the question in the question are different!
Comment: What's wrong with saying $a_n = \frac {-1}{n^2 + 1}$ if $n\equiv 0 \pmod 4$ and $a_n = \frac 1{n^2+1}$ if $n$ is even and $a_n = 0$ if $n$ is odd?  There's no magic incantation that makes something described in a single expression more legitimate.
Comment: You can try your luck here: https://oeis.org/
Answer: How about
$$a_n=\frac{-\sin(n\pi/2)}{n^2+1}?$$
Answer: Hint: Look at every other term.
$$a_{n} = \begin{cases}
0 & \text{if } n \text{ is even} \\
(-1)^{n}\cdot1/(4n^2-4n+1) & \text{ otherwise}
\end{cases}$$
Answer: You may proceed as follows for $n \in \mathbb{N}$ starting with $n=1$:

To get $1\,0\,1\,0\,1\,0\,1\, \ldots$ you may use $\frac{1+(-1)^{n-1}}{2}$.
To get $(-1)\, x \, 1\, y\, (-1)\, \ldots $ (where $x,y$ can be any number as we multiply them with the $0$ from the upper sequence) you may use the imaginary unit $i$: $i^{n-\lfloor n/4\rfloor  + 1}$

Putting this together you get
$$a_n = i^{n-\lfloor n/4\rfloor  + 1}\frac{1+(-1)^{n-1}}{2(n^2+1)}$$
Answer: For the first one,$$(-1)^{n(n+1)(n+2)/2}$$ and for the second one $$(-1)^{n(n+1)/2}$$


Erro ao tentar submeter formulário com arquivo por AJAX

Question: Tenho o seguinte código que implementei de teste antes de colocar no meu projeto:
index.php
 <form method="post" id="formulario" enctype="multipart/form-data">
 <input name="nome" type="text"/>
 <input name="img" type="file"/>
 <button> Enviar</button>
 </form>

recebe.php
<?php
foreach($_POST as $value)
{
    echo $value." - ";
}

foreach($_FILES['img'] as $value)
{
    echo $value." + ";
}

if (move_uploaded_file($_FILES['img']['tmp_name'],  'teste.jpg')) {
    echo "Sucesso";
}

O objetivo é fazer o upload da imagem sem ter que recarregar a página. Tentei criando um FormData e enviando ele por ajax, mas o alert do retorno sequer é exibido. Não sei qual é o erro.
Answer: Consegui assim:
var dados = new FormData(this);

$.ajax(
{
    url: 'recebe.php',
    type: 'POST',
    data:  dados,
    mimeType:"multipart/form-data",
    contentType: false,
    cache: false,
    processData:false,
    success: function(data, textStatus, jqXHR)
    {
         alert(data);
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Em caso de erro
    }
});

Answer: O parâmetro é method, não type:
$.ajax(
        {
            url: "recebe.php",
            method: "POST",
            data: formData,
            success: function(result)
            {
                alert(result);
            }
        });

Comment: No AJAX usasse `type` par informar o tipo do formulário. Esse não é o erro.


Need intercept for plm (Fixed effects) in R

Question: I have a question of fixed effects in R. So I am trying to use plm function to find fixed effects like following:
> plm(PM25 ~ policy + 1, data=subset(part2, Delhi == 1), model="within",
>     index=c("station_id", "date")) %>% summary()

The results I get:
> Oneway (individual) effect Within Model
>
> Call: plm(formula = PM25 ~ policy + 1, data = subset(part2, Delhi ==
>           1), model = "within", index = c("station_id", "date"))
>
> Unbalanced Panel: n = 7, T = 73-159, N = 992
>
> Residuals:
>      Min.   1st Qu.    Median   3rd Qu.      Max.
> -193.7049  -54.6776   -9.6843   54.7431  318.4094
>
> Coefficients:
>        Estimate Std. Error t-value  Pr(>|t|)
> policy  76.8167     9.9787  7.6981 3.354e-14 ***
> ---
> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
>
> Total Sum of Squares:    6846900
> Residual Sum of Squares: 6458000
> R-Squared:      0.056803
> Adj. R-Squared: 0.050093
> F-statistic: 59.2603 on 1 and 984 DF, p-value: 3.3535e-14

I am wondering how can I find the intercept?
Answer: The within model you specify amounts to fitting a separate intercept for each unit in your panel data set, as in
$$
y_{it}=a_i+\beta x_{it}+u_{it}
$$
See, e.g., these posts for some context:
Difference between fixed effects dummies and fixed effects estimator?
How exactly does a "random effects model" in econometrics relate to mixed models outside of econometrics?
Hence, you cannot additionally fit an overall intercept $a$, as you would then have perfect collinearity between the $a_i$ and $a$, as the sum of the $a_i$ is identically one.
You can retrieve these estimates as follows:
data("Grunfeld", package = "plm")

wi <- plm(inv ~ value + capital,
          data = Grunfeld, model = "within", effect = "twoways")

fixef(wi)

One might of course leave out one of the intercepts. Something related to what you seek seems to be achieved by this command: https://rdrr.io/rforge/plm/man/within_intercept.html


Achar substring em mensagens de commits recentes

Question: Estou buscando uma substring nos commits mais recentes do meu repositório.
Utilizo o comando git log -n1 --grep='${subString}'.
Porém usando a flag -nsó vou conseguir o último commit, que tecnicamente é o mais recente.
Ex:
commit 1a1a
Author: Gabriel Hardoim
Date: 2018-08-20 13:30:40

       Esse commit tem a substring

Mas pode, e provavelmente vai, acontecer que exista mais de um commit feito recentemente, o que torna a flag -n ineficiente.
Ex:
commit 2b2b
Author: Gabriel Hardoim
Date: 2018-08-20 13:40:02

       Esse commit não tem

commit 1a1a                             //Nesse caso, esse é o commit que eu quero.
Author: Gabriel Hardoim
Date: 2018-08-20 13:30:40

       Esse commit tem a substring

Há ainda os casos mais comuns, ondem exitam vários commits com a substring que estou buscando.
Ex:
commit 2b2b
Author: Gabriel Hardoim
Date: 2018-08-20 13:40:02

       Esse commit não tem

commit 1a1a                             //Nesse caso, esse ainda é o commit que eu quero.
Author: Gabriel Hardoim
Date: 2018-08-20 13:30:40

       Esse commit tem a substring

commit 3c3c
Author: Gabriel Hardoim
Date: 2018-08-20 13:20:11

       Esse commit também tem a substring

commit 4d4d
Author: Gabriel Hardoim
Date: 2018-08-20 13:13:05

       Esse commit também não tem

Considerando que os commits foram para o repositório remoto pelo mesmo comando git push, o que posso fazer para achar uma substring na mensagem do commit mais recente??
Comment: `git log -1 -p ":/subString"`? Não sei se entendi muito bem, mas o git log te permite buscar o ultimo commit contendo a mensagem, nesse caso `subString`
Answer: Você pode usar o grep do terminal/shell/linux no lugar.
git log | grep --context=4 "TEXTO"

Um git log simples em conjunto com o grep do linux, pedindo para "agrupar" os resultados em 4 linhas para trás.
No meu teste local, exibiu três commits cujas mensagens descritivas possuíam a palavra procurada.


Is the Riemannian distance function Lipschitz on a hypersurface?

Question: Let $M$ be a compact hypersurface in $\mathbb{R}^{n+1}$ of dimenion $n$.
Is it true that there exists a constant $C$ such that
$$d(x,y) \leq C|x-y|$$
for all $x, y \in M$? Here $d$ is the Riemannian distance function and $|\cdot|$ is the usual norm on $\mathbb{R}^{n+1}$.
I think it is trivially true that $|x-y| \leq d(x,y)$ since the straight line minimises the distance between two points. But the reverse, I don't know.
Answer: Define the function
$$
f(x,y) := \begin{cases} \frac{d(x,y)}{|x-y|} & \text{ if } x \ne y \\
 1 & \text{ if } x=y
\end{cases}
$$
for $(x,y) \in M \times M$. Then $f$ is continuous on a compact set, so it has a maximum which works as $C$ in your question.
Comment: Thanks. So is the point that this works since $d$ is continuous? It has nothing to do with the Riemannian distance function.
Comment: Continuity and compactness plus the fact that it works locally, i.e., that the quotient has a limit as $x \to y$.


Changes to grub in ubuntu 10

Question: I've been running CentOS 5 for some years.  I've decided to upgrade to Ubuntu, and with 10.04 just out, this seemed like a good time.
I'm a tad paranoid, so I started off with a new set of drives - one to install on, one to backup to, and one as a spare.  I removed my existing CentOS 5 drives, and did an install, and had no problems.  I installed the server version, and used the default full-disk LVM installation.
Next, I copies my backup scripts over, edited them to work with the new configuration, and did a test backup.  That worked fine, as well.  Then comes the real test, could I do an install of the backup onto the spare drive?  (I won't put anything of importance on a system that doesn't have a reliable backup, and if I've never done a restore, it's not reliable.)
I booted from a System Rescue CD (ver 1.5.3), with the spare drive as /dev/sda, and the backup drive as /dev/sdb.  I had no trouble in partitioning, configuring LVM, formatting, making swap, or restoring the file systems.  But when I got to restoring grub to the MBR, I ran into problems.
My restore instructions from CentOS 5 said run grub, then enter two commands:
root (hd0,0)
   setup (hd0)
The first command exits with an error: "Checking if /boot/grub/stage1 exists ... no"
I did some googling around, and found that the Grub2 included in recent Ubuntus is very different than the Grub 0.97 included in CentOS 5.  One site suggested I use:
grub-install --root-dir=/mnt/restore /dev/sda
That appeared to work, but when I booted from the drive, I ended up at a grub prompt.
Any ideas as to what I need to do?  It seems like a simple problem, but my attempts at searching out answers on the web are being swamped by references to the old version of Grub.
Help would be appreciated.
Comment: sysrescuecd includes a grub2-install command.  You might want to try installing grub with that.
Answer: My restored drives had all of the proper grub installation and configuration on them, it was just a matter of getting things to where I could execute them.
I booted off the Ubuntu install CD, selected "rescue", and then set my new root directory as the root directory, and started a shell in that directory.
I then mounted /boot, and ran update-grub and grub-install, and everything worked fine.
Comment: Hmm... disappointed..would have preferred to see more details as what this fixed. Also with the previous grub prompt did you try booting by manually configuring from the grub shell?

Changes to grub in ubuntu 10


jq how to pass json keys from a shell variable

Question: I have a json file I am parsing with jq. This is a sample of the file
[{
"key1":{...},
"key2":{...}
}]
[{
"key1":{...},
"key2":{...}
}]
...

each line is a list containing a json (which I know is not technically a json format but jq still works on such a file)
The below jq command works:
cat file.json | jq -r '.[] | [.key1,.key2]'

The above correctly shows:
[
<value_of_key1>,<value_of_key2>
]
[
<value_of_key1>,<value_of_key2>
]

However, I want .key1,.key2 to be dynamic since these keys can change. So I want to pass a variable to jq. Something like:
$KEYS=.key1,.key2
cat file.json | jq -r --arg var "$KEYS" '.[] | [$var]'

But the above is returning the keys themselves:
[
".key1,.key2"
]
[
".key1,.key2"
]

why is this happening? what is the correct command to make this happen?
This answer does not help me. I am not getting any errors as the OP in that question.
Comment: Not irritated, but just insulting regardless being in an even-keeled emotional state? As an outside observer, I don't see how that's any better.
Comment: Oke, I was just confirming. But since you can't take a question without sounding irritated, I wish you the best of luck finding an answer.
Comment: Anyhow -- this is a case where what you claim you want is best implemented with `jq -r ".[] | [$keys]"` -- note double quotes instead of single quotes, so the shell is generating code for jq to execute. That's usually undesirable, but this is a special case.
Comment: Use bracket notation
Comment: @0stone0 this does not work. already seen it.
Comment: Just now seeing that you're trying to parse multiple keys with just 1 arg, Is that intended?
Comment: @0stone0 because as you can see the argument itself is multiple keys. `$KEYS=.key1,.key2`. I suggest you read carefully before closing a potentially helpful question.
Comment: yes it is as intended. `$KEYS=.key1,.key2`. Already outlined this above ^ 5 min ago
Comment: I'm absolutely not irritated. It was not my intention to sound like that if that is the case. I'm sorry that your wrongly interpreted emotional analysis from text will make you not share your knowledge with whoever stumbles on this question. (again not irritated).
Comment: @Charles Duffy, ouch. Building code from the shell... That never goes wrong.
Comment: @ikegami, ...sure, but the OP _wants_ the effect of `eval`; hence, it's expected for them to get its pitfalls.
Comment: @Charles Duffy, No, they want to select keys. The extent of what they need exactly is unclear, but saying they want/need `eval` is not a reasonable assumption
Comment: @ikegami I updated the question showing the correct output.
Comment: You didn't change it, but the error was mine. Sorry, comment deleted.
Comment: Tip: The `-r` makes no sense and ends up being ignored as a result.
Answer: Fetching the value of a jq variable doesn't cause it to be executed as jq code.
Furthermore, jq lacks the facility to take a string, compile it as jq code, and evaluate the result. (This is commonly known as eval.)
So, short of a writing a jq parser and evaluator in jq, you will need to impose limits and/or accept a different format.
For example,
keys='[ [ "key1", "childkey" ], [ "key2", "childkey2" ] ]'  # JSON
jq --argjson keys "$keys" '.[] | [ getpath( $keys[] ) ]' file.json

or
keys='key1.childkey,key2.childkey2'
jq --arg keys "$keys" '
   ( ( $keys / "," ) | map( . / "." ) ) as $keys |
   .[] | [ getpath( $keys[] ) ]
' file.json

Comment: Also, if needed, the value for the `keys` variable could be generated by using another invocation of jq. In the first example (JSON array) for instance like so: `keys="$(echo key1 key2 | jq -Rnc 'inputs/" "')"`.
Comment: @pmf, Maybe? The example is a bad one. You'd just use the second approach with a space instead of a comma rather than a second invocation of `jq`. And I can't think of case where it would make sense.
Comment: My use-case in mind was having a text file or another program's output providing the keys, which when fed into jq could produce a valid JSON to be then used as input. But never mind, it was just a suggestion...
Comment: @pmf, You could use `--arg keys "$( cat file )"`
Comment: @ikegami your first example is almost correct. I am getting `[null,null]` as output. and I know the keys I am using are correct because I tested just in case. Your second example I cannot get it to work
Comment: @bcsta The first works fine. The second was missing parens. [Demo](https://gist.github.com/ikegami/93f421f94e8c080d1c7565f08e892010)
Comment: @ikegami you are right the first one works for a flat json. what if I have nested keys. I was doing `keys='key1.childkey,key2.childkey2'` which is why i was getting `[null,null]`. Do you have any suggestions for nested keys?
Comment: The answer already suggested you could use `getpath` to do that. Updated examples.
Answer: Suppose you have:
cat file
[{
"key1":1,
"key2":2
}]
[{
"key1":1,
"key2":2
}]

You can use a jq command like so:
jq '.[] | [.key1,.key2]' file
[
  1,
  2
]
[
  1,
  2
]

You can use -f to execute a filter from a file and nothing keeps you from creating the file separately from the shell variables.
Example:
keys=".key1"
echo ".[] | [${keys}]" >jqf

jq -f jqf file
[
  1
]
[
  1
]

Or just build the string directly into jq:
# note double " causing string interpolation
jq ".[] | [${keys}]" file

Answer: You can use --argjson option and destructuring.
file.json
[{"key1":{"a":1},"key2":{"b":2}}]
[{"key1":{"c":1},"key2":{"d":2}}]

$ in='["key1","key2"]' jq -c --argjson keys "$in" '$keys as [$key1,$key2] | .[] | [.[$key1,$key2]]' file.json

output:
[{"a":1},{"b":2}]
[{"c":1},{"d":2}]

Answer: Elaborating on ikegami's answer.
To start with here's my version of the answer:
$ in='key1.a,key2.b'; jq -c --arg keys "$in" '($keys/","|map(./".")) as $paths | .[] | [getpath($paths[])]' <<<$'[{"key1":{"a":1},"key2":{"b":2}}] [{"key1":{"a":3},"key2":{"b":4}}]'

This gives output
[1,2]
[3,4]

Let's try it.
We have input
[{"key1":{"a":1},"key2":{"b":2}}]
[{"key1":{"a":3},"key2":{"b":4}}]

And we want to construct array
[["key1","a"],["key2","b"]]

then use it on getpath(PATHS) builtin to extract values out of our input.
To start with we are given in shell variable with string value key1.a,key2.b. Let's call this $keys.
Then $keys/"," gives
["key1.a","key2.b"]
["key1.a","key2.b"]

After that $keys/","|map(./".") gives what we want.
[["key1","a"],["key2","b"]]
[["key1","a"],["key2","b"]]

Let's call this $paths.
Now if we do .[]|[getpath($paths[])] we get the values from our input equivalent to
[.[] | .key1.a, .key2.b]

which is
[1,2]
[3,4]


Is there any relationship between two normalized gamma distributions?

Question: Consider two normalized gamma distribution functions $\frac{\Gamma(x,y)}{\Gamma(x)}$ and $\frac{\Gamma(nx,ny)}{\Gamma(nx)}$ where $n$ is a positive integer value. Is there any relationship between the two functions? I mean, can I write the second one as a function of the first one.
Thanks,
Comment: *" Is there any relationship between the two functions? I mean, can I write the second one as a function of the first one."* What do you mean by relationship? Are you looking for a specific type of relationship? You can always relate *any* two distributions via the quantile function and the cumulative distribution function (the inverse quantile function).
Answer: No, there is no known relationship. Take a simple case of just trying to compare ${\Gamma(\alpha,x)}$ and ${\Gamma(2\alpha,x)}$.
There is no known duplication formula for the upper incomplete gamma function, so neither of these can be easily related to the other. See here for a similar question: https://math.stackexchange.com/questions/1942494/relationship-between-the-incomplete-gamma-function-of-2a-and-a?rq=1


About restricting variables in an integrand, and also changing the look of an integrands.

Question: So, in the last step of, many, integrands, Wolfram chooses to restrict the $x$-values, even if I didn't specify which values $x$ can take on.
Take for example:
$$\int\frac{dx}{x(x^2-1)^{3/2}} = -\cot(\sec^{-1}(x))-\sec^{-1}(x)+C$$
Checking with Wolfram gives a different option, an option that, in accordance to their step-by-step solver comes from the fact that they restrict the $x$-values. I'm not sure how they restrict it, but it apparently becomes:
$$\tan^{-1}\left(\dfrac{1}{\sqrt{x^2-1}}\right) - \dfrac{1}{\sqrt{x^2-1}}$$
Why do they restrict $x$? Is this the usual thing to do? And if so, why?
I also want to ask how to change the expression from LHS to RHS by restricting the $x$-values. $$-\cot(\sec^{-1}(x))-\sec^{-1}(x) = \tan^{-1}\left(\dfrac{1}{\sqrt{x^2-1}}\right) - \dfrac{1}{\sqrt{x^2-1}}$$
Comment: Since the sign of $x^2 - 1$ can change along the real axis, it's germane to symbolic integration routines to restrict $x$ to subintervals where it does not change sign, in order to form expressions valid in those restricted intervals.
Comment: Actually, why not edit your Question (no Answers so far) to raise that issue?
Comment: Oh, I see. And a follow up question, how do I get from the first expression ($-\cot(\sec^{-1}(x))-\sec^{-1}(x)$) RHS to Wolfram's answer (2nd expression)? (If anyone cares to explain)
Answer:
If you are surprised to see that the same indefinite integral $\big($anti-derivative$\big)$ can be expressed in two or more apparently different ways, see for example Gudermannian function.
To show that the two functions are indeed identical, use $x=\sec t$, and $\sec^2t-1=\tan^2t$.


Saving data in a view pager

Question: I have a view pager to display some editable items in it. When the user edits the items, i need to save them, in order to show them again when the user opens the said screen again.
I'ved tried putting the save routine inside the "saveState" method, however, that method never gets called
in which method can i save the data i need ?
<code>@Override
public void destroyItem(View collection, int position, Object view) {
    Log.d(TAG, "destroyItem "+position);
    ((ViewPager) collection).removeView((View) view);
}

@Override
public boolean isViewFromObject(View view, Object object) {
    Log.d(TAG, "isViewFromObject");
    return view == ((View) object);
}

@Override
public void finishUpdate(View view) {
    Log.d(TAG, "finishUpdate");
}

@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
    Log.d(TAG, "restoreState");
}

@Override
public Parcelable saveState() {
    Log.d(TAG, "saveState");
    return null;
}

@Override
public void startUpdate(View view) {
    Log.d(TAG, "startUpdate");
}
</code>
Answer: I figured out the answer - it is "in any method in the activity that governs the viewpager"
there is no need to save the state of the views, there is a need to save t he state of the data, as the state of the data is what determines how the views will look like.
any change to the data should be saved in the activity in which the pager was opened.

Saving data in a view pager


Create multiple jQuery image pans on 1 page

Question: There is a wonderful script by Manos which allows you to pan a cropped image when hovering over it. Here is the code and here is a demo
What I would like to do is to place multiple images on 1 page with various sizes for each image. (I tried creating a JSfiddle for this but did not work well...)
I attempted to add more than 1 on a page, but each image mirrors the action and each instance needs to be the exact same size image or it can't calculate the proper panning.
Thanks very much in advance.
Answer: Instead of using a global $imagePan modify the MouseMove function to accept the image in context, and instead of using id's you should be using classes.
http://jsfiddle.net/VPr52/9/
It still needs heavy optimization, calculating the widths and height each time the mouse moves, is too much, better to calculate it once and save it in the image using $.data.
Good luck!
Comment: UberNeet this is brilliant - different size images works as well with your update which is terrific - thank you! I'll keep testing/optimizing away and post any updates for others - thanks very much!


How could I get a correlation value that accounts for gender?

Question: For instance if I were trying to relate Age and Height, I would do something like this:
<code>df <- data.frame(Age, Height)
cor(df)
</code>
How could I get Pearson's r value and the p-value for the relationship between Age and Height while accounting for the effect of Gender?
Comment: The problem here was not so much "how to use R" but how to find a correlation coefficient while taking another variable into account, which suggests it ought to be on-topic. (I wonder whether we have another thread on partial correlation that this duplicates.)
Comment: That was exactly what I needed. I had never heard the phrase "partial correlation" before. If you will propose that as the answer (preferably with an example of usage) I will accept it.
Answer: This is called partial correlation, basically it, as Wikipedia notices,

measures the degree of association between two random variables, with
  the effect of a set of controlling random variables removed

Having correlation coefficients of three variables $X$, $Y$ and $Z$ we can correct correlation $\rho_{XY}$ by controlling correlations of $X$ and $Y$ with $Z$:
$$ \rho_{XY \cdot Z } = \frac{\rho_{XY} - \rho_{XZ}\rho_{ZY}} {\sqrt{(1-\rho_{XZ}^2) (1-\rho_{ZY}^2)}} $$
This is related to multiple linear regression. To test the hypothesis about partial correlation you use $t$-statistic in similar fashion as with regular correlation but with $N-3$ degrees of freedom. The same formula can be used for Pearson's or Spearman's correlation coefficients (for more see Altman, 1991 or Revelle, n.d.).
There are multiple R functions and libraries that enable you to calculate partial correlations like pcor, ggm or psych.

Altman, D.G. (1991). Practical Statistics for Medical Research. Chapman and Hall, pp. 288-299.
Revelle, W. (n.d.). Multiple Correlation and Multiple Regression In: An introduction to psychometric theory with applications in R.
Comment: I think this *could* be on topic if it is more about how this can be done / what it means, as opposed to what R code to use. Can you say more about what kind of thing a partial correlation is & how it works?


Valor mínimo do input date deve ser o dia de hoje

Question: Tenho um input do tipo data, e preciso que não seja possível selecionar data que não seja de hoje para trás, tentei dessa maneira, mas não tive muito sucesso:
HTML:
<input [(ngModel)]="atv.dataini" type="date" class="form-control" #one min="{{this.today}}">

TYPESCRIPT:
today = this.dNow.getFullYear() + '-0' + (this.dNow.getMonth() + 1) + '-0' + this.dNow.getDate();

também tentei dessa maneira:
HTML:
<input [(ngModel)]="atv.dataini" type="date" class="form-control" #one min="{{this.tdNow}}">

TYPESCRIPT:
dNow = this.formatDate(new Date());

formatDate(date) {
    let result = date.split('-').reverse().join('/');
    return result
}

Answer: Uma maneira simples é você capturar esses dados no model atv.dataini e dai verifica-los, comparando com a data de hoje e se não for o desejado levantar um erro para o usuario


Parent term relations select list as Hierarchical select list

Question: I would like to change the Taxonomy relation select list like as Hierarchical Select list, how can I change its nature?
Please help]1
Answer: Check "Hierarchical Select Taxonomy" sub-module in Hierarchical Select module. After installing "Hierarchical Select Taxonomy" module it will automatically convert normal select list into hierarchical select list. Please check screenshot below:
Comment: Thanks many its working well. One more help! How do I make this as Single Select list box, since it is now with multiple select options. Any code snippet are available for this?
Comment: Hierarchical select box works with multiple dropdown, u might need to do it custom if need in single dropdown


Undefined index: db_type in custom code

Question: I have created a module but my code gives me an error

Undefined index: db_type in student_install()

How can I fix this?
Following are my three files
student.INFO FILE
name        = student
description = "Add/edit/save student data."
core        = 7.x
package = "students"

students.MODULE FILE
<?php

/**
 * Students - The text editor for the Internet - http://ckeditor.com
 * Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
 *
 */

 function students_menu(){
 $items = array();
  // path location (http://www.url.com/foo/bar )
  $items[] = array(
    //path
    'path'=> 'admin/settings/students',
    // page title
    'title' => t('Manage Students'),
    // describe the page for the menu system.  site visitors will not see this
    'description' => ('Add students'),
    // function that is called when visiting the new path
    'callback' => 'drupal_get_form',
    'callback arguments' => 'Students settings',
    // permissions required to view page
    'access' => user_access('access administration pages'),
  );
  return $items;
}
 function students_settings()
 {
    $form['name'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Name?',
    '#size' => 20,
    '#maxlength' => 20,
    '#required' => TRUE, //make this field required
  );
  $form['last_name'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Last Name?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => False, //make this field required
  );
  $form['email'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your email?',
    '#size' => 20,
    '#maxlength' => 20,
    '#required' => TRUE, //make this field required
  );
  $form['age'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Age?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => TRUE, //make this field required
  );
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );
  return system_settings_form($form);

 }
 function students_get_form($form_id,$form_values)
 {
    drupal_set_message(t("Submited"));
 }

students.INSTALL FILE
function students_install(){
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      // the {tablename} syntax is so multisite installs can add a
      // prefix to the table name as set in the settings.php file
      db_query("CREATE TABLE node_field_students_data (
          id int unsigned NOT NULL default '0',
          name varchar(32) NOT NULL default '',
          age int unsigned NOT NULL default '0',
          roll_num int unsigned NOT NULL default '0',
          PRIMARY KEY  (id)
        ) /*!40100 DEFAULT CHARACTER SET utf8 */;");
      break;

    case 'pgsql':
      db_query("CREATE TABLE node_field_students_data (
          id serial CHECK (id >= 0),
          name varchar(32) NOT NULL default '',
          age integer NOT NULL default '0' CHECK (age >= 0),
          roll_num integer NOT NULL default '0' CHECK (roll_num >= 0),
          PRIMARY KEY  (id)
        )");

      // Pgsql requires keys and indexes to be defined separately.
      // It's important to name the index as {tablename}_fieldname_idx
      // (the trailing _idx!) so update scripts can be written easily
      db_query("CREATE INDEX node_field_students_data name_idx
                ON node_field_students_data (name)");
      break;
  }
}

function students_uninstall()
{
    switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      // the {tablename} syntax is so multisite installs can add a
      // prefix to the table name as set in the settings.php file
      db_query("DROP TABLE node_field_students_data");
      break;

    case 'pgsql':
      db_query("DROP TABLE node_field_students_data");

      // Pgsql requires keys and indexes to be defined separately.
      // It's important to name the index as {tablename}_fieldname_idx
      // (the trailing _idx!) so update scripts can be written easily
      break;
  }
}

Answer: The $db_type variable no longer exists in Drupal 7. You need to use template code that was designed for Drupal 7.
Comment: Generally speaking you can find the same value in `$GLOBALS['databases']['default']['default']['driver']`. But obviously the fact there are naked SQL statements being run in `hook_install()`, along with manual creation of tables that should have been created my CCK, means the code has many, many problems, and as you say needs to be upgraded (totally ripped out and started again in this case)

Undefined index: db_type in custom code


Uiwebview within uitableview

Question: Is it possible to divide uitableview into 3 parts, one of which is uiwebview (so i can display html string)? The other 2 parts are just regular strings so I can just display as text.
Answer: It is possible using custom subclasses of UITableViewCell (just split each cell into 3 subcells and insert a UIWebview into one.); however, it probably goes against the Apple HIG.
Answer: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...

[self addWebViewToTable:(UITableViewCell *)cell];

return cell;

}
- (void)addWebViewToTable:(UITableViewCell *)cell{
NSString* htmlString = @"
My First Heading

My first paragraph.
";
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(5.0f,1.0f,40.0f,40.0f)];
[webView loadHTMLString:htmlString baseURL:nil];
[[cell contentView] addSubview:webView];
[webView release];

}
Comment: Thanks. Is there a way to automatically resize the images in the html code? Currently they are too big to fit within the iphone screen.
Comment: @Dat NGuyen I am not sure if this is right way to do: look at this http://stackoverflow.com/questions/603907/uiimage-resize-then-crop post to resize your image, store image into documents or temp and then use local file as image source !! hope this helps

Uiwebview within uitableview


Unable to think about a Possible application ofCR equation in complex analysis

Question: I am unable to think about an example given in my class notes related to first course in complex analysis and so I am asking for help here.

Statement of Question->It has to be shown that $\text{Re}(w)$ admits a overall maximum $z_0$ along $L$, where $L$ is $\text{Re}(z)=x_0$ .

( Above lines I am giving only for reference).

Please Note that I am only struck in how (1) below implies f(y) = $-\text{Im}(w') (x_0 +i y)$ .

Let $f(y) = \frac{d \text{Re}(w) }{dy}$ $(x_0+i y)$ --(1) and then sir wrote $f(y)= - \text{Im}(w')(x_0 +iy)$.
My attempt ->
If I apply CR equation on (1)(let $f=u+iv$ then if $f$ is analytic, $u_x=v_y$ ,$v_x=- u_y$ ) using $u_y =-v_x$ . So, I am not getting $-\text{Im}(w') (x_0 +i y)$ .
Can someone please tell where I am making mistakes.
Comment: What do you mean by $\text{Re}(w)$ admits a overall maximum $z_0$ along $\text{Re}(z)=x_0$? What is the relation between $z$ and $w$?
Comment: If they are the same thing, shouldn't $\text{Re}(w)$ be simply constant along $L$?
Comment: @Caffeine Line is Re(z) = $x_0$ and it is to be proved that Re(w) admits an overall maximum $z_0$ along L.
Comment: Since on that line $\text{Re}(z)=x_0$, i.e. is constant, I do not see why $\text{Re}(w)=\text{Re}(z)=x_0$ shouldn't hold
Comment: @Caffeinr can you just tell how to get f(y) $= -\text{Im}(w') (x_0 +i y)$ .
Comment: @Caffeine can you please look at statement of question now if you have some time ? I have edited it .
Comment: What is $w'$? You did not define the relations between your variables, making it hard to understand the question
Comment: @Caffeine w' means differentiation of w. I hope question is clear to you now. If not kindly ask where it is unclear, It will also help others.
Comment: Ok, now I understand: $w$ is an (analytic) function of $z$, and $f$ is defined as the derivative of $\text{Re}(w)$ evaluated at $x_0+iy$. Am I right?
Answer: $$w(z)=u(z)+iv(z)\\
u(z)=\text{Re}(w);\ v(z)=\text{Im}(w)\\
f=\partial_y \text{Re}(w)_{|x_0+iy}=\partial_y u=^*-\partial_x v=-\partial_x\text{Im}(w)_{|x_0+iy}\\
$$
*: Cauchy-Riemann equations


$S=\{0,1,2,...,q^2-1\}$, is there a way to figure out how many elements contained in $S$ can be written as the sum of $2$ squares?

Question: I'm currently working on a proof, and have broken it down into a series of problems.  I've had success with every part except one.  My question is (and it may be really easy; it's getting late):
'Let $q$ be a prime such that $q\equiv 3 \mod 4$.  Given the set $S=\{0,1,2,...,q^2-1\}$, is there a way to figure out how many elements contained in $S$ can be written as the sum of $2$ squares?'
I've been trying to think of a clever way to exploit Fermat, but have been unsuccessful.  I know that any prime $ 3 \mod 4$ cannot be written as the sum of two squares [so $S$ has max of $q^2-1$ elements which can be written as the sum of two squares].
Also, I know that any integer $n$ can be written as the sum of two squares iff it's prime factorization contains an even number of primes $3 \mod 4$.  Maybe you good people of the Stack Exchange could help guide me in the right direction.
Comment: @awllower, not widely known example in all details, a number is represented by $x^2 + 5 y^2$ if and only if all prime factors $q \equiv 11,13,17,19 \pmod {20}$ have even exponents, while the **sum of the exponents** of any  prime factors $2$ or $ p \equiv 3,7 \pmod {20}$ is even. So, for example, $6 = 1+5, $ $14 = 9+5,$ $21 = 1 + 5 \cdot 4.$
Comment: you are incorrect on the characterization: a number for which **every** prime factor $q \equiv 3 \pmod 4$ has an even exponent is the sum of two squares. We can estimate the count of such numbers up to a bound, not count exactly
Comment: But the converse does not hold: there could be an even number of prime factors $\equiv3\pmod4$ while each of them appears an odd number of times.
Comment: if the prime has an even exponent, then it occurs an even number of times in the prime factorization, no?  For example, $3^4\cdot 7^6$ -- $7$ occurs $6$ (even) times, $3$ occurs $4$ (even) times in the prime factorization.
Answer: I do not believe there is any closed-form exact count of sums of two squares up to a positive $x,$ any more than there is a simple way to count the primes up to $x.$
Meanwhile, in LeVeque two volumes in one, in volume 2, page 260, Theorem 7-28, we have that the count of numbers up to some positive $x$ that are sums of two squares is
$$      \frac{Bx}{\sqrt {\log x}} + O \left( \frac{x}{\left(\log x \right)^{3/4}}\right)                $$
where the constant $B \approx 0.7642.$


Diagnosing the slow performance of my NAS?

Question: I recently built a NAS box on top of ubuntu server.  I have an average transfer of about 10mb/sec over gigabit wire to my computer.  I was hoping you guys could give recommendations on how to pinpoint where the bottleneck is in this system.  To my knowledge the router is only rated at 100mb/sec, and so are the nics (both server, and client), but shouldn't my files be transferring faster then 10mb/sec?  I made sure to shutdown all other traffic when getting the 10mb/sec baseline.
Thanks,
Max.
Comment: Note that transferring a 100MB file over a 100mb network should take about 15-20 seconds (since it will transfer at about 8MB/sec ... 100mb speeds are rarely maintained).  Just want to make sure you did not mix up your bits and bytes =)
Comment: When I experience crazy connectivity issues, I usually check duplex settings on devices before anything else.
Comment: What is your disk configuration? one drive will behave much different than a raid5 or raid10 array.
Comment: When they are both set to half duplex 100mbs, they run at 10 mbs, but when set at full duplex, they run at like 30kbs.
Comment: @Brian, right now just drives, I plan on putting a zraid on (with 3 terabyte drives), but held off until I could diagnose the speed issue (don't want to make it worse, if it is the drives).
Comment: Just a quick update, I tried a second router, and a second (wired) computer, they all got the same speed (10 mb/sec) or close.  I tried just a quick copy between drives, and it was transferring at around 100mb/sec, so it isn't hard drives.  Any other thoughts, or am I just doomed to this speed
Comment: 100mb/sec between drives, or 100MB/sec?  If the former, your drives are horribly slow.  Remember that drive transfers are typically measured in MegaBytes, while network transfers are measured in Megabits.
Comment: yes, I am sorry, 100MB/sec
Answer: Was this for transferring a single file?  Also, is this performance consistent across multiple client machines?  For testing, your best test is to take a very large file (500MB or so) and transfer it.
Here is how I would test it:

Borrow a laptop for testing, should be different O/S from your current machine(s) if possible
Send a large file from borrowed laptop to your current test machine (and vice versa)
Send a large file from borrowed laptop to NAS (and vice versa)
Send a large file from current test machine to NAS (and vice versa)

If all of the above yield 10Mb speeds, the issue is your router.  If the performance is only slow when transferring to/from the NAS, then the issue is your Ubuntu setup (I'd guess network config, bad driver, etc).  If the issue is only from your current test machine, but the borrowed one works fine, then it's likely a driver issue or config (e.g. duplex setting).
Hope this helps
Comment: Thank you, one thing I could think of is maybe an issue with right performance on the drives, but I will try that, thanks
Comment: Seems like that did it, switching the routers helped a lot


How to find the basis of an intersection of vector spaces, along with vector spaces relative to one another.

Question: The Question
I would appreciate a  nudge in the right direction. I have two vector spaces $V_1$ and $V_2$, given spanning sets for both respectively. I am trying to find a basis for $V_1 \cap V_2$ and a basis for $V_1$ relative to $V_1\cap V_2$.
Consider a vector space $V=K^4$ and its subspaces
$$V_1 = span \left\{ \left(
  \begin{matrix}
    3 \\ 3 \\ 2 \\ 2
  \end{matrix}
  \right), \left(
   \begin{matrix}
    2 \\ 1 \\ 2 \\ 2
  \end{matrix}
  \right),\left(
   \begin{matrix}
    0 \\ 1 \\ 2 \\ 0
  \end{matrix}
  \right),\left(
   \begin{matrix}
    2 \\ 3 \\ 2 \\ 1
  \end{matrix}
  \right) \right\},V_2 = span \left\{ \left(
  \begin{matrix}
    2 \\ 3 \\ 1 \\ 1
  \end{matrix}
  \right), \left(
   \begin{matrix}
    2 \\ 1 \\ 1 \\ 2
  \end{matrix}
  \right),\left(
   \begin{matrix}
    2 \\ 2 \\ 0 \\ 1
  \end{matrix}
  \right)\right\}$$
Find the bases of $V_1$ and $V_2, V_1 \cap V_2$ and $V_1$ relative to $V_1 \cap V_2$
My Understanding
I calculated the basis of the intersection to be the column vectors $(0,-2,0,1)^T$ and $(2,2,0,1)^T$, I did this by constructing the matrix $(Base(V_1)|-Base(V_2))$ and finding a basis for the kernel, of the form =( ). I then proceeded to calculate the column vectors by taking $Base(V_1)\cdot$ for each basis vector of the kernel. However, I can not see how the column vectors $(0,-2,0,1)^T$,$(2,2,0,1)^T$ can form a basis of $V_1$ as they do not have a third entry.
Comment: Consider $V_1$ with basis $(0,0,1)$ and $V_2$ with basis vectors $(1,0,0)$ and $(0,0,1)$. The intersection will simply be $V_1$ which has two entries that are zero. It doesn't mean anything is wrong.
Comment: Are you saying that you were expecting the basis for $V_1\cap V_2$ to have three elements but there are only two? I find it quite reasonable that the intersection would have dimension 2 (assuming that $V_1$ has dimension 3).
Comment: I was expecting the basis for $V_1\capV_2$ to have 4 elements, however I have two vectors both with 4 elements that both do not have a 3rd entry. I have not previously encountered this in my studies so it seems unusual to me.
Answer: I'm not sure about a switch of basis because the basis $\{(0,-2,0,1)^T,(2,2,0,1)^T\}$ of $V_1 \cap V_2$ doesn't have three vectors in it, like the basis $\{(3,3,2,2)^T,(2,1,2,2)^T,(0,1,2,0)^T\}$ of $V_1$ does. But you could always find a third linearly independent vector $\vec{v_3}$ in $V_1$ such that $\{(0,-2,0,1)^T,(2,2,0,1)^T,\vec{v_3}\}$ is a basis for $V_1$, then you could write every vector in $V_1$ as a linear combination of the basis vectors of $V_1 \cap V_2$ and $\vec{v_3}$.


Duvida Sistema Simples Escolar

Question: Bom estou fazendo um trabalho para faculdade, já estou no meio do caminho,  porém para fazer a parte final preciso:

O professor pode cadastrar um pdf/imagem, na área dele.
E o aluno na página dele consegue ver/baixar esse anexo.

O que tenho ate agora salva somente imagens.
O form para gravar o anexo.
<form action="gravar.php" method="POST" enctype="multipart/form-data">
    Imagem:
    <input type="file" name="imagem"/>

    <input type="submit" value="Enviar"/>
</form>

E a parte para gravar a Imagem no banco de dados.
<?php
$imagem = $_FILES["imagem"];
$host = "localhost";
$username = "root";
$password = "";
$db = "sistema";

if ($imagem != NULL) {
    $nomeFinal = time().'.jpg';
    if (move_uploaded_file($imagem['tmp_name'], $nomeFinal)) {
        $tamanhoImg = filesize($nomeFinal);
        $mysqlImg = addslashes(fread(fopen($nomeFinal, "r"), $tamanhoImg));

        mysql_connect($host,$username,$password) or die("Impossível Conectar");
        @mysql_select_db($db) or die("Impossível Conectar");
        mysql_query("INSERT INTO anexo (PES_IMG) VALUES ('$mysqlImg')") or die("O sistema não foi capaz de executar a query");

        unlink($nomeFinal);
        header("location:exibir.php");
    }
} else {
    echo "Você não realizou o upload de forma satisfatória.";
}
?>

E aqui eu exibo a imagem gravada, num PHP:
<?php
$host = "localhost";
$username = "root";
$password = "";
$db = "sistema";

mysql_connect($host,$username,$password) or die("Impossível conectar ao banco.");
@mysql_select_db($db) or die("Impossível conectar ao banco");

$result = mysql_query("SELECT * FROM anexo") or die("Impossível executar a query");
while ($row = mysql_fetch_object($result)) {
    echo "PES_ID' \">";
}

?>

Mas o que eu gostaria era de mostrar esse anexo somente quando o aluno na área dele clicasse no link "anexo" e ele veria somente o anexo daquele trabalho e não de todos os outros.
Comment: Código mal indentado é a raiz de muitos males... Aqui um tutorial sobre como fazer isso corretamente e que aparece na primeira página do google: https://www.youtube.com/watch?v=NfS4HpRZciA
Answer: Para guardar um arquivo em banco de dados e poder fazer o download depois, é necessário guardar o mimetype do arquivo, nome, tamanho, etc.
Para isso é necessário criar uma tabela da seguinte maneira
CREATE TABLE upload (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(30) NOT NULL,
    type VARCHAR(30) NOT NULL,
    size INT NOT NULL,
    content MEDIUMBLOB NOT NULL,
    PRIMARY KEY(id)
);

O tipo MEDIUMBLOB até 16 megabytes mais ou menos, porem existem os tipos a seguir que devem ser usados de acordo com sua necessidade.

TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB

Para recuperar as informações do arquivo que está sendo feito o upload existe a variável global $_FILES que possui as seguintes informações:
// O nome original do arquivo
$_FILES['userfile']['name'];

// O mimetype do arquivo. Esta informação é dada pelo browser do usuário.
// Por exemplo para uma imagem JPG seria "image/jpg"
$_FILES['userfile']['type'];

// O tamanho da imagem em bytes.
$_FILES['userfile']['size'];

// O nome do arquivo temporário criado quando o servidor recebe a
// requisição, e armazena para que o arquivo possa ser trabalhado.
$_FILES['userfile']['tmp_name'];

// O código de erro associado ao arquivo, caso houver.
$_FILES['userfile']['error'];

Para gravar no banco de dados basta criar o seguinte script
salvar.php
$host = "localhost";
$username = "root";
$password = "";
$db = "sistema";

mysql_connect($host,$username,$password) or die("Impossível conectar com o banco de dados.");
mysql_select_db($db) or die("Não foi possível selecionar o banco de dados.");

if (isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
    $fileName = $_FILES['userfile']['name'];
    $tmpName  = $_FILES['userfile']['tmp_name'];
    $fileSize = $_FILES['userfile']['size'];
    $fileType = $_FILES['userfile']['type'];

    $fp      = fopen($tmpName, 'r');
    $content = fread($fp, filesize($tmpName));
    $content = addslashes($content);
    fclose($fp);

    $query = "INSERT INTO upload (name, size, type, content ) VALUES ('$fileName', '$fileSize', '$fileType', '$content')";

    mysql_query($query) or die('Error, query failed');
}
mysql_close(); // Não esqueça de finalizar a conexão.
header("Location: listar.php");
exit(); // Sempre que quiser fazer algum redirecionamento, finalize o script para evitar erros no envio de cabeçalho.

Crie um página para listar os arquivos para o usuário clicar nos links e fazer o download.
listar.php
<?php

$host = "localhost";
$username = "root";
$password = "";
$db = "sistema";

mysql_connect($host,$username,$password) or die("Impossível conectar com o banco de dados.");
mysql_select_db($db) or die("Não foi possível selecionar o banco de dados.");

?>

        <title>Arquivos</title>

    <?php

    $query = "SELECT id, name FROM upload";
    $result = mysql_query($query) or die('Error, query failed');
    if (mysql_num_rows($result) == 0) {
        echo "Database is empty
";
    } else {
        while (list($id, $name) = mysql_fetch_array($result)) {
            echo '' . $name . '
';
        }
    }
    ?>

<?php mysql_close() ?>

E o arquivo para permitir o download do arquivo
download.php
<?php
if (isset($_GET['id'])) {
    $host = "localhost";
    $username = "root";
    $password = "";
    $db = "sistema";

    mysql_connect($host,$username,$password) or die("Impossível conectar com o banco de dados.");
    mysql_select_db($db) or die("Não foi possível selecionar o banco de dados.");

    $id    = (int) $_GET['id'];
    $query = "SELECT name, type, size, content FROM upload WHERE id = '$id'";

    $result = mysql_query($query) or die('Error, query failed');
    list($name, $type, $size, $content) = mysql_fetch_array($result);

    header("Content-length: $size");
    header("Content-type: $type");
    header("Content-Disposition: attachment; filename=$name");

    echo $content;

    mysql_close();
    exit();
}

Esse exemplo é usado para guardar arquivos no banco de dados, mas você pode guardar a imagem real no servidor e armazenar no banco de dados apenas o nome da imagem para download, assim não seria necessário o arquivo download.php e seus arquivos ficariam da seguinte maneira:
salvar.php
O campo anexo na tabela do banco de dados guarda agora só o nome do arquivo.
$host = "localhost";
$username = "root";
$password = "";
$db = "sistema";

mysql_connect($host,$username,$password) or die("Impossível conectar com o banco de dados.");
mysql_select_db($db) or die("Não foi possível selecionar o banco de dados.");

if (isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
    $fileName = $_FILES['userfile']['name'];
    $tmpName  = $_FILES['userfile']['tmp_name'];
    $fileSize = $_FILES['userfile']['size'];
    $fileType = $_FILES['userfile']['type'];

    $pasta = __DIR__ . '/';
    $nomeFinal = time().'.jpg';
    if (move_uploaded_file($imagem['tmp_name'], $pasta . $nomeFinal)) {
        $query = "INSERT INTO upload (anexo) VALUES ('$nomeFinal')";
        mysql_query($query) or die('Error, query failed');
    }
}
mysql_close(); // Não esqueça de finalizar a conexão.
header("Location: listar.php");
exit(); // Sempre que quiser fazer algum redirecionamento, finalize o script para evitar erros no envio de cabeçalho.

listar.php
<?php

$host = "localhost";
$username = "root";
$password = "";
$db = "sistema";

mysql_connect($host,$username,$password) or die("Impossível conectar com o banco de dados.");
mysql_select_db($db) or die("Não foi possível selecionar o banco de dados.");

?>

        <title>Arquivos</title>

    <?php

    $query = "SELECT id, anexo FROM upload";
    $result = mysql_query($query) or die('Error, query failed');
    if (mysql_num_rows($result) == 0) {
        echo "Database is empty
";
    } else {
        while (list($id, $anexo) = mysql_fetch_array($result)) {
            echo '' . $anexo . '
';
        }
    }
    ?>

<?php mysql_close() ?>

Comment: valeu amigo , ja me ajudou bastante =)

Duvida Sistema Simples Escolar


Is it true to say that : Every submodule of a module M contains in a maximal submodule?

Question: Let $R$ be an arbitrary ring with $1\neq 0$ and $_RM$ a left $R$-module. Is it true to say that : Every proper submodule  of a module $M$ is contained in a maximal submodule?
Comment: "Every nonzero module has a maximal submodule" is quite strong a property for the ring. See [this article by Hamsher for the commutative case](http://www.ams.org/journals/proc/1967-018-06/S0002-9939-1967-0217059-8/S0002-9939-1967-0217059-8.pdf)
Answer: Not all modules have maximal submodules at all, much less maximal submodules that contain any given submodule.
As an example, the (left) $\Bbb Z$-module $\Bbb Q$ does not have maximal submodles.
Comment: @KennyLau It's done [here](https://math.stackexchange.com/questions/234995/mathbbq-has-no-maximal-subgroups), for instance. That post is using the term "group", but that's the same as $\Bbb Z$-module for our intents and purposes.
Comment: Could you prove that $\Bbb Q$ does not have maximal submodules?


How would you rate the following books in terms of usefulness for experimental data analysis?

Question: I am looking at following books:

Statistical Models (Cambridge Series in Statistical and Probabilistic
Mathematics) - A. C. Davison
Essentials of Statistical Inference (Cambridge Series in Statistical
and Probabilistic Mathematics) - G. A. Young
Asymptotic Statistics (Cambridge Series in Statistical and
Probabilistic Mathematics) - A. W. van der Vaart.

They all cover different topics, I skimmed through the pages of both of them and it seems to me they are all useful for data analysis, but I wonder which one would be the most useful to buy / read first?
Comment: Hi there, exactly what type of experimental data analysis do you need? You may require a specialist book.
Comment: Any reason you're looking at books from only one publisher?
Comment: I own the last two, but not the first. Neither of the last two could be characterized as geared toward data analysis. These are books on *mathematical statistics*. The van der Vaart text is a beautiful one, but may be rough going for those without sufficient math preparation. The Young & Smith text is essentially a very high-level rapid introduction to some of the core ideas of mathematical statistics. It is a nice read, but lacks much depth in my opinion, and, I think that is intended. The Davison text *appears* to have a similar intent. None of these are about data analysis, per se.
Comment: In other words, you might consider editing your question to be more specific about what you are trying to learn. Understanding your goals better will invite more specific and useful answers. :)
Comment: @onestop Yes they are the only available in my library.
Answer: I haven't read any of those textbooks but a quick look at their table of contents makes me think you might find the first (Statistical Models by A.C. Davison) most helpful. That one takes the most applied perspective; the other two focus on the rigorous mathematical underpinnings of statistical inference. For doing actual data analysis, you will likely be better off with a textbook that has an applied perspective.
Even the Davison text, though, isn't specific to experimental data analysis. Its section on analysis of variance (a key statistical method in analysis of many experiments) is only eight pages long. The chapter on designed experiments is 47 pages long, which may seem like a lot until you realize that entire textbooks are written on design and analysis of experiments. Once you've covered basic statistical ground as in the Davison textbook (or more rigorously in one of the other books), you might be ready to focus specifically on experiments.
Most textbooks that cover data analysis for experimental data also cover the design of experiments. As you can see from questions like this one -- How to test hypothesis for group differences -- the analysis of experimental data is tied up with the design of the experiment. Poor experimental design can ruin your chances of answering the questions you want to answer. Even if you are not the one doing the experimental design, you need to know what a well-designed experiment looks like. Ideally, you will be involved in the design so that you can ensure that the data you'll have for analysis will be useful.
If you do decide to get a book focused on experimental design and analysis, you'll want to get one that is specific to your domain. I like Myers, Well, and Lorch's Research Design and Statistical Analysis. I've found it useful in a social science research setting. But if you're working in another area (clinical trials or ecology, for example), you can find books that cover experimental design and data analysis in those contexts.


Getting error "open failed: EFAULT (Bad address)" when okhttp tries to send choosed from PhotoPicker image

Question: This error occurs ONLY when an image was choosed from Photo Picker on android 13 (on versions without Photo Picker all works!).
What does code:
User picks image from Photo Picker.
Get image's uri and save file in body, there all is working too:
File imgFile = FilesHelper.INSTANCE.getFileFromUri(this, imgUri);
postBody.setPhoto(imgFile);

@Throws(Exception::class)
fun getFileFromUri(context: Context, uri: Uri): File? {
    var path: String? = null
    if ("content".equals(uri.scheme, ignoreCase = true)) {
        path = getDataColumn(context, uri, null, null)
    } else if ("file".equals(uri.scheme, ignoreCase = true)) {
        path = uri.path
    }
    return if (!path.isNullOrEmpty()) File(path) else null
}

private fun getDataColumn(context: Context, uri: Uri,
                          selection: String?, selectionArgs: Array<String?>?): String? {
    var cursor: Cursor? = null
    val column = MediaStore.Images.Media.DATA
    val projection = arrayOf(column)
    try {
        cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
        if (cursor != null && cursor.moveToFirst()) {
            val column_index = cursor.getColumnIndexOrThrow(column)
            return cursor.getString(column_index)
        }
    } finally {
        cursor?.close()
    }
    return null
}

But when body is sending as multipart,
final Map<String, RequestBody> multipart = new HashMap<>(2);
multipart.put("product",
            RequestBody.create(MediaType.parse("application/json"),
            BaseApplication.getGson().toJson(postBody)));
multipart.put("image\"; filename=\"%1.jpg\"",
            RequestBody.create(MediaType.parse("image/jpeg"),
            postBody.getPhoto())); // type File
....
serverApi.sendBody(multipart);
....

a warning was shown in logCat:
*
/sdcard/.transforms/synthetic/picker/0/com.android.providers.media.photopicker/media/1000000019.jpg: open failed: EFAULT (Bad address)*
and then retrofit/okhttp throws exception.
Retrofit version "com.squareup.retrofit2:retrofit:2.9.0"
Permissions in AndroidManifest, which are given before picking image:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>

And
 android:requestLegacyExternalStorage="true"
in <application> too.
Asking permissions:
if (VERSION.SDK_INT >= 33) arrayOf(Manifest.permission.READ_MEDIA_IMAGES) else arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)

Can I get and send that image without using MANAGE_EXTERNAL_STORAGE permission? Because application distributes via Google Play and is not files manager or something like that.
Maybe I should copy file in app's internal files dir or what?
Answer: Well, found solution: grant read uri permission
  private void onImagePicked(Uri imgUri){
    if(imgUri!=null) {
      try {

        grantUriPermission(getPackageName(),imgUri,Intent.FLAG_GRANT_READ_URI_PERMISSION);

        File imgFile = FilesHelper.INSTANCE.getFileFromUri(this, imgUri);
        postBody.setPhoto(imgFile);
      } catch (Exception e) {
        ...
      }
    }
  }


Population proportion

Question: A type of disease that affects people over the age of 60 is far more prevalent in men (2%)
than in women (0.1%). There is a screening test used on people over 60 that has different
accuracy rates for men and women.
What is the probability a person will test positive?
The prior probability for men to have a disease is 2 in 100 while for women it is 1 in 1000
So to find the probability that a random person selected has a diseases do we add the probabilities i.e 0.02+0.001 = 0.021 OR do we do (2+1)/ (100+1000) ?
Answer: You need to be on the same "scale".
men 2/100 = 20/1000
women 1/1000 = 1/1000 (duh)
Now you see the two ways you have formulated it are the same.
Answer: The probability of the disease (D) under the condition that the person is male (M) is 0.02 and under the condition that the person is female (F) it is 0.001:
$$
\begin{align}
p(D|M) &= 0.02,\\
p(D|F) &= 0.001.
\end{align}
$$
The probability of a random person having the disease is:
$$
\begin{align}
p(D) &= p(D|M) \cdot p(M) + p(D|F) \cdot p(F)\\
     &= 0.02 \cdot p(M)  +  0.001 \cdot p(F).
\end{align}
$$
As you can see, you need to know the probability of a person being female or male, otherwise, you cannot give an answer. Presuming that half of the people you consider are female, the result would be:
$$
\begin{align}
p(D) &= 0.02 \cdot 0.5  +  0.001 \cdot 0.5\\
     &= 0.0105.
\end{align}
$$

Population proportion


What is the difference between Image.resize and Image.thumbnail in Pillow-Python

Question: I want to resize an image in pillow-python, however I have 2 functions of choice to use:
Image.resize http://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.Image.resize
and
Image.thumbnail
http://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.Image.thumbnail
Both definitions point out to resizing the image,  Which one should I be using?
Answer: Image.resize resizes to the dimensions you specify:
Image.resize([256,512],PIL.Image.ANTIALIAS) # resizes to 256x512 exactly

Image.thumbnail resizes to the largest size that (a) preserves the aspect ratio, (b) does not exceed the original image, and (c) does not exceed the size specified in the arguments of thumbnail.
Image.thumbnail([256, 512],PIL.Image.ANTIALIAS) # resizes 512x512 to 256x256

Furthermore, calling thumbnail resizes it in place, whereas resize returns the resized image.
Comment: `thumbnail` also does not enlarge the image. So e.g. an image of the size 150x150 will keep this dimension if `Image.thumbnail([512,512],PIL.Image.ANTIALIAS)` is called.
Comment: Thanks. "Resizes in place" was the key to my issue. I was converting code to use thumbnail instead of resize and I was getting a null return.
Comment: Also, `thumbnail` preserves the aspect ratio. So applying `thumbnail(100, 200)` to a 512x512 image would change the image size to 100x100.
Comment: @HeinvanDyke thanks for the answer. is there a difference in quality when resizing, i.e., does one introduce artifacts while another doesn't?
Comment: `ANTIALIAS` no longer is a valid resample filter.  Should be removed.  Pillow has reasonable defaults, no not needed.
Answer: Two examples for thumbnailing, one taken from geeksforgeeks:
# importing Image class from PIL package
from PIL import Image

# creating a object
image = Image.open(r"C:\Users\System-Pc\Desktop\python.png")
MAX_SIZE = (100, 100)

image.thumbnail(MAX_SIZE)

# creating thumbnail
image.save('pythonthumb.png')
image.show()

The second example relates to Python/Django.
If you do that on a django model.py, you modify the def save(self,*args, **kwargs) method - like this:
class Profile(models.Model):
    user=models.OneToOneField(User, on_delete=models.CASCADE)
    image=models.ImageField(default='default.jpg', upload_to='img_profile')
    def __str__(self):
        return '{} Profile'.format(self.user.email)
    # Resize the uploaded image
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        img=Image.open(self.image.path)
        if img.height > 100 or img.width >100:
            Max_size=(100,100)
            img.thumbnail(Max_size)
            img.save(self.image.path)
        else:
            del img

In the last example both images remain stored in the file system on your server.


If $A : X' \rightarrow X$ and $k$ is a kernel on X, then $k$' defined by $k'(x,y) = k(A(x), A(y))$ is a kernel on $X'$ - proof help

Question: Studying kernels and I came across this PDF:
I am not a mathematician and I barely understand kernels, but I would like to see the proof for Lemma $4$.
If $A$ : $X' → X$ and $k$ is a kernel on $X$, then $k' $defined by $k'(x,x') = k(A(x), A(x'))$ is a kernel on $X'$.
I'm not sure how to begin to show that $k'$ is a kernel, much less that $k'$ is PSD.
I think for the latter I need to show something like:
$$ A^{T} \textbf{K} A \geq 0 => x^{T} \textbf{K} x \geq 0 $$
but I don't understand why $k' = k$.
Answer: I don't see lemma 4 in the PDF, but yes, you need to show $k'$ is positive semidefinite and symmetric.
Since $k$ is a valid kernel for all $x \in X$, any function which maps elements $x' \in X'$ to $X$ will induce a natural kernel on $X'$ (the pullback of kernel $k$ under $A$).
To see that $k'$ is symmetric, use that $k$ is a kernel:
$$
k'(x',x) := k(A(x'),A(x)) = k(A(x),A(x')) =: k'(x,x')
$$
To see that $k'$ is positive semidefinite, use that $k$ is a kernel:
$$
k'(x',x) := k(A(x'),A(x)) = k(\tilde{x}', \tilde{x}) \geq 0 \quad \forall \tilde{x}, \tilde{x}' \in X
$$


How do you get the return type of a function in jsdoc?

Question: I have two files src/a.js src/b.js.I want the type of response to be the return value of the request function.
If in Typescript I could have written this ⬇。Is there a similar syntax in jsdoc?

I don't want to use @typedef to define an additional type.

// src/a.ts

export function request() {
  return Promise.resolve({
    name: "William",
  });
}

// src/b.ts

import { request } from "./a";

export function handleResponse(response: ReturnType<typeof request>) {}

src/a.js
export function request() {
  return Promise.resolve({
    name: "William",
  });
}

src/b.js
/**
 * @param {???} response
 * @returns {void}
 */
export function handleResponse(response) {}

Answer: To get a similar effect in JSDoc without using @typedef, you can use import() syntax in the JSDoc comment to reference types from another module.
In your example, if you want to use the return type of the request function from src/a.js for the response parameter in the handleResponse function in src/b.js, you can do the following
src/a.js
/**
 * @returns {Promise<{name: string}>}
 */
export function request() {
  return Promise.resolve({
    name: "William",
  });
}

src/b.js
import { request } from './a';

/**
 * @param {ReturnType<typeof import('./a').request>} response
 * @returns {void}
 */
export function handleResponse(response) {}

Using import() in JSDoc comments allows you to reference types from other modules.
The syntax ReturnType<typeof import('./a').request> essentially translates to "the return type of the request function in the ./a module".
Comment if any more help required.


Bash command to sum specific columns of numbers from a file with many columns

Question: A  1  15  4
B  2  14  5
C  3  13  6
D  4  12  4

I would like to add columns 2 (1+2+3+4) and 3 (15+14+13+12) and eventually add them together, while ignoring columns 1 and 4. How can I accomplish this?
Answer: sum columns 1, 3 and 1+3
awk 'BEGIN {FS = " "} ; {sum+=$2} {sum2+=$3} END {print sum, sum2, sum+sum2}'  file

Answer: You can try below:
awk 'BEGIN {FS = " "} ; {sum+=$2} {sum1+=$3} END {print sum sum1}' file.txt