Eu preciso fechar um InputStream?

Question: Eu tenho o seguinte.
InputStream in = (InputStream) response.getEntity();

Eu preciso fechar? Sendo que o close() do inputStream não faz nada?
Comment: `InputStream` é uma classe abstrata. Quer dizer que na prática você sempre está usando alguma sub-classe dela, que pode ou não sobrescrever o método `close`. O fato de você ter criado uma variável do tipo `InputStream` não quer dizer necessariamente que ao chamar `close` estará chamando a versão que não faz nada. Se a sub-classe sobrescrever o método, é este que será chamado. E se a sub-classe foi bem implementada, o `close` fará tudo que for necessário para fechar corretamente o stream.
Answer: Vamos ver a documentação da classe, que é algo que deve fazer sempre que for usar algo, e parece que o AP fez, fica para os demais.
Aí vemos que ela implementa uma interface chama AutoCloseable. Vendo sua documentação diz que ela tem um método close() que deve ser chamado para fechar a classe que a implementa.
Mas ali mesmo também disse que isso pode ser feito de forma automática, como o nome já indica, e isso deve ser feito com o chamado try-resources, até para garantir que o fechamento seja chamado mesmo que ocorra um erro.
Então oficialmente deve fechar sim, mas deve fazer de forma segura, da maneira correta:
try (InputStream in = (InputStream) response.getEntity()) {
    // faz o que precisa
}

Coloquei no GitHub para referência futura.
A documentação diz isso. Então deveria fazer. Mas de fato a documentação também diz que esse método faz nada.
Também vemos na documentação que ela é abstrata. Mesmo que não fosse ela não é final, então ela pode ser herdada, nesse caso é até obrigatório que seja. Então as derivações dela podem ter um recurso que precise ser dispensado.
Como é possível que use o tipo InputStream em algum lugar mas a implementação concreta do objeto usado seja de um tipo que use o padrão Disposable de forma efetiva, então se você não usar a forma que fecha o recurso de forma garantida poderá ter um vazamento de recurso.
Por isso ou deve usar o tipo mais concreto, final,  que você sabe que também tem nada no close() e que nunca mudará, ou então deve usar o try para garantir a dispensa.
Se você quiser confiar que só será usado em objetos que continuam com o comportamento de fazer nada no fechamento, então ok, mas é um risco que terá que assumir. Usar o try e ele ser um desperdício, ou não usar e no futuro, improvável, mudar e você ter que revisar todos códigos que fez para arrumar. Não é uma decisão simples.
Se trabalha em equipe deve ser combinado com todos para ser consistente.
Tem o lado mais "seguro" ou mais performático. Em quase todas situações, porque tudo deve ter um contexto e exceção do que fazer, eu iria pelo lado seguro, se tem o negócio ali então use. E se não usar documente muito bem fora do código para saber que um dia pode ter que mudar, e só faça isso se precisar de máxima eficiência e puder garantir que não virá algo que o fechamento será imprescindível.
Eu dei uma pesquisada e há controvérsias sobre o fechamento ou não. Inclusive tem códigos bem conhecidos que fecham e outros que não fecham. Acho que todos ignoraram a questão da herança levantada pelo hkotsubo e o wldomiciano.
O contexto de onde é usado também conta. Em uma aplicação que executa por bem pouco tempo até mesmo recursos que deveriam ser fechados por necessidade real não precisam porque a aplicação morre logo em seguida. Isso é ser pragmático.
Curioso como você se deu ao trabalho de ler toda documentação. Todas respostas sobre o assunto que li por aí ignoraram essa questão do método fazer nada.
Comment: Tenho uma observação, me diga se faz sentido: Apesar da doc de `InputStream` estabelecer que o método faz nada, temos que ter em mente que ela é uma classe abstrata, logo, sempre que temos objetos deste tipo, na verdade estamos lidando com instâncias de classes concretas que a extendem. Por isso, apesar das controvérisias que vc mencionou, eu acho que tem que fechar sempre. Veja uma a [`FileInputStream`](https://github.com/openjdk/jdk/blob/jdk-17%2B35/src/java.base/share/classes/java/io/FileInputStream.java#L439) por exemplo, ela faz coisas no `close()`.
Comment: @wldomiciano sim, vou dar uma mexida sobre isso.

Eu preciso fechar um InputStream?


Jquery Dialog window size

Question: How do I make a JQuery dialog size to the size of the window?
I tried using 'auto' but that just makes it size to its elements, and I don't want to specifiy the px's exactly b/c that won't be dynamic. thanks!
Comment: are you using jquery library or the the jquery UI library, or both?
Answer: I'm taking a little bit of a guess here, but you can get the size of the window using:
<code>var windowWidth = $(window).width();
var windowHeight = $(window).height();
</code>
So, I would take that, and pass that value to the jQuery Dialog.
<code>$( ".dialog" ).dialog({ height: windowHeight, width: windowWidth });
</code>

Jquery Dialog window size


Convergence of empirical distribution parameters of a sequence of generated normal variables

Question: I am generating a sequence of normal random variables (using the routines from boost C++ library). How fast would you expect the mean and the variance of the sequence converge to the actual variance?
In my case the true values are:
mean=-0.01208333333333333
variance=0.0075

For 10000000 generated variables I get:
Mean=-0.0120757,
var=0.00750125

which intuitively seem quite far (especially variance) for this ridiculously large number of samples. Should I expect faster convergence (i.e. there is some issue with my code), or is it what you would expect?
Answer: Your results are well within expectations. The random variable defined by $(n-1)s^2 \over \sigma^2$ is a $\chi^2$ random variable with variance of $2(n-1)$. Using this I find the standard deviation of $s$ to be 0.000003354, which when compared to your observed difference of 0.00000125 means this is not unusual. A similar argument shows your $\bar x$ result is also in line.
Answer: Doing this in Stata (actually Mata) I got the following results for 10 such large samples (first column is the mean, the second is the variance):
: res = J(10,2,.)

: for(i=1; i <= 10; i++) {
>         x = rnormal(10000000,1, -0.01208333333333333, sqrt(0.0075))
>         res[i,.] = meanvariance(x)'
> }

: res
                   1              2
     +-------------------------------+
   1 |  -.0120843169    .0075019019  |
   2 |  -.0121035264    .0074968712  |
   3 |  -.0120866703    .0074955339  |
   4 |  -.0120646992     .007499407  |
   5 |  -.0120959452    .0074969704  |
   6 |  -.0120737802    .0075110002  |
   7 |  -.0120411955    .0074920638  |
   8 |  -.0120973025    .0075073199  |
   9 |  -.0120785954     .007501123  |
  10 |   -.012116408    .0075042688  |
     +-------------------------------+

So your results seem to be in line with what happens inside Stata. That is no guarantee that there is no error, but it is still somewhat reassuring.

Edit:
I checked the variances from Stata's random normal number generators against the results mentioned in soakly's answer and not surprisingly it performs very well:
clear all

local n = 1000
local reps = 10000
local m = -0.01208333333333333
local v = .0075

set obs `reps'

mata
res = J(`reps',2,.)

for(i=1; i <= `reps'; i++) {
    x = rnormal(`n',1, `m', sqrt(`v'))
    res[i,.] = meanvariance(x)'
}

idx =st_addvar("double","v")
st_store(.,idx,res[.,2])

end

gen chi = (`n'-1)*v/`v'
qchi chi, df(`=`n'-1')


Mapserver ignores my template-file for GetFeatureInfo-requests

Question: I want my mapfile to support the GetFeatureInfo-request for some layers.
I added the following line to the layer:
TEMPLATE "change-template.txt"

And the fileitself looks like follows (only for testing-purposes until now):
# MapServer Template

[version]
test123

If I make my GetFeatureInfo-request, I get the following output:
GetFeatureInfo results:

Layer 'Change-North'
  Feature 3150:

So it hits a feature (if I change the coordinates I get different Feature-numbers), but I cannot get any stuff from my template. The mapserver respects my TEMPLATE-line, because if I comment it out, the GetFeatureInfo-request doesn't work any longer: 'Requested layer(s) are not queryable.'
What is wrong here?
Answer: OK, I found a solution myself now. This template will only be used with a GetFeatureInfo request with the parameter INFO_FORMAT set to text/html. But to support text/html you also have to set another value in the WEB-part of the mapfile:
    WEB
            METADATA
                    "WMS_FEATURE_INFO_MIME_TYPE" "text/html"
            END
    END

Also it only worked, if the name of the template-file ended with .html. But I'm using it to send back simple text-information. Hope this helps anyone, who runs into the same problem.


Regex replace or add substring in Python

Question: I need a unique regex to replace a substring or add it if missing.
Example:
set beta=10
"alpha=25 beta=42 delta=43" need to become "alpha=25 beta=10 delta=43"
"alpha=25 delta=43" need to become "alpha=25 delta=43 beta=10"

This following code is functional only to replace existing value, but if the index to replace does not already exist it does not add anything.
dest = re.sub(r'(.*)(beta=\d+)( .*)',r'\1 beta=10 \3',source)

I can do that, but I need this result in one expression:
if re.search(r'beta=\d+',source):
    dest = re.sub(r'(.*)(beta=\d+)( .*)',r'\1 beta=10 \3',source)
else:
    dest = source + " beta=10"

So if beta=xx exist in a string and it doesn't match beta=yy then replace
So if beta=xx does not exist in a string then append beta=yy to string
Comment: are `alpha` `beta` `delta` te only possible entries or there could be also `gamma` `eta` ...? Are input strings in order I mean do you have always `alpha= beta=  delta= ` or might you have `beta= alpha=...`?
Comment: Can you have anything else between `alpha` and `delta`? Is `delta` always present? Is `alpha` always present?
Comment: So if beta=xx exist in a string and it doesn't match beta=yy replace?
Comment: So if beta=xx does not exist in a string append beta=yy to string?
Comment: Yes, we can have any text before or after the label I have to update.

"Life is complex" , to yours questions, the response is yes to both.
Answer: Assuming that beta=10 is only present 0 or 1 times in the string, you could do it like this:
dest = re.sub("(beta=\d+|$)","beta=10",source+" ",1).strip()

The pattern considers the end of line to be an alternative match for beta=\d+ and, since we're only substituting the first occurrence, it will only apply when the line does not contain beta=\d+


ASP.NET entity data model get list with relitionships

Question: I have "Question" and "QuestionTypes". In "Question" table there is a foreign key that refrence the other table. I want to show question attributes with type name.
Repeater code:
<ItemTemplate>

             <%#Eval("QuestionSubject")%>

             <%#Eval("Question")%>

             <%#Eval("QuestionTypeName")%> //I want to get question typename
        	                          //TypeName is in other table

</ItemTemplate>

And here is code behind:
private IEnumerable<TableSurveyQuestion> Questions()
{
    int survey_id = Int32.Parse(Request.QueryString["survey_id"]);
    IEnumerable<TableSurveyQuestion> questions= db.TableSurveyQuestions.Where(a => a.SurveyId == survey_id);
    return questions;
}

I bind this founction to repeater data source.
I tried select new TableQuestions {typeName=x.TableQuestionTypes.TypeName} but this did not work.
In mvc I get it like this question.TableQuestionType.TypeName. How do this in ASP.NET web forms.
Thanks.
Answer: I found it
var sorular = from soru in db.TableSurveyQuestions
                  where soru.SurveyId == anket_id
                  orderby soru.QueueNo, soru.Subject ascending
                  select new
                  {
                      soru.TypeId,
                      soru.Subject,
                      soru.QuestionId,
                      soru.SurveyId,
                      soru.QueueNo,
                      SurveyTitle = soru.TableSurvey.Title,
                      TypeName = soru.TableSurveyQuestionType.TypeName,
                      SoruSayisi = db.TableSurveyQuestions.Where(a => a.SurveyId == anket_id).Count(),

                      Secenekler = from secenekler in soru.TableSurveyOptions
                                   select new
                                   {
                                       OptionId = secenekler.OptionId,
                                       OptionName = secenekler.OptionName,
                                       QuestionId = secenekler.QuestionId,
                                       VoteCount = secenekler.TableSurveyVotes.Count
                                   }
                  };

thanks.


Get detailed info via snmp from Juniper switch stack for monitoring

Question: I try to get the following information out of the switch stack for monitoring purposes. Here is the command and its output executed directly on the switch stack via ssh login:
root@stack> show virtual-chassis

Preprovisioned Virtual Chassis
Virtual Chassis ID: cf44.0df5.1234
Virtual Chassis Mode: Enabled
                                           Mstr           Mixed Neighbor List
Member ID  Status   Serial No    Model     prio  Role      Mode ID  Interface
0 (FPC 0)  Prsnt    GAxxxxxxx8 ex3300-48t 129  Master*     NA  2  vcp-255/1/2
                                                                 3  vcp-255/1/3
                                                                 1  vcp-255/1/1
1 (FPC 1)  Prsnt    GAxxxxxxx2 ex3300-48t   0  Linecard    NA  0  vcp-255/1/2
                                                                 5  vcp-255/1/3
                                                                 2  vcp-255/1/1
2 (FPC 2)  Prsnt    GAxxxxxxx3 ex3300-48t   0  Linecard    NA  1  vcp-255/1/2
                                                                 3  vcp-255/1/3
                                                                 0  vcp-255/1/1
3 (FPC 3)  Prsnt    GAxxxxxxx1 ex3300-48t   0  Linecard    NA  4  vcp-255/1/2
                                                                 2  vcp-255/1/3
                                                                 0  vcp-255/1/1
4 (FPC 4)  Prsnt    GAxxxxxxx7 ex3300-48t 129  Backup      NA  5  vcp-255/1/2
                                                                 6  vcp-255/1/3
                                                                 3  vcp-255/1/1
5 (FPC 5)  Prsnt    GAxxxxxxx5 ex3300-48t   0  Linecard    NA  4  vcp-255/1/2
                                                                 6  vcp-255/1/3
                                                                 1  vcp-255/1/1
6 (FPC 6)  Prsnt    GAxxxxxxx3 ex3300-48t   0  Linecard    NA  4  vcp-255/1/0
                                                                 5  vcp-255/1/1

In the end I would like to check for the amount of members and/or for status (Prsnt/NotPrsnt), also if there was a role change (e.g. Backup --> Master).
With snmpwalk I got a huge list of entries, but nothing matches with any values above.
So does it mean there is no possibility to get this info out of the stack?
Answer: Well this is a loaded one...Breaking it down
Number of Members
You're not going to get that, most likely, given the way the VC is depicted over SNMP.  There is no current "member count" value in the OID tree.  your best bet would be to walk .126.96.36.199.4.1.2618.104.22.168.220.127.116.11.2 and count the Serial numbers returned (or use the memberID, or MACs, or whatever).  It looks like you're using Icinga, so you're probably going to want to use a script to grab that OID and count the results, since Icinga won't do that for you.  I do similar things for dozens of other situations in Nagios.  (I beat out a quick script based on some of those situations; use it, or use it as an example to do what you want: https://gist.github.com/peelman/ef7b682de3af579c2896585385e18e7c).
Status of Members
I see of no (easy) way to get present/not present statuses.  That one you might just have to punt on, or monitor the VCP interfaces themselves one by one.
Role Changes
This would be a good one to use traps for; but if you're set on using polling and you are statically setting priorities so that you know what your master/backup will be most of the time, then you can look at the values under .220.127.116.11.4.1.2618.104.22.168.188.8.131.52.3; node .0 will be member 0, node .1 will be member 1, and so on.
A value of 1 is Master, 2 is Backup, and 3 is Linecard (that's available in the MIB itself).  The problem is that if you leave all that up to the dynamics of a default virtual chassis set up, without setting mastership priorities static member IDs (based on serial numbers), etc, those values could change.
npeelman@nagios:~$ snmpwalk -v2c -c community ex3300-test.domain.tld .184.108.40.206.4.1.2618.104.22.168.220.127.116.11.3
JUNIPER-VIRTUALCHASSIS-MIB::jnxVirtualChassisMemberRole.0 = INTEGER: master(1)
JUNIPER-VIRTUALCHASSIS-MIB::jnxVirtualChassisMemberRole.1 = INTEGER: backup(2)

References

You can find the entire Virtual Chassis MIB tree described here
Juniper's MIBs available here
Comment: Thank you for this very useful info. With that I can start program a script to check for values.


Reverse order of integration ∫∫ f(x, y)dydx + ∫∫ f(x, y) dydx

Question: Consider the integrals
\begin{equation}
\int_{0}^{1} \int_{0}^{2x} f(x, y) dy dx + \int_{1}^{2} \int_{0}^{4x-2x^2}f(x, y) dydx.
\end{equation}
I am trying to reverse the order of integration. For the first integral I got $x$ limits as $0$ to $y/2$, and $y$ limits as $0$ to $2$. For the second integral I got $x$ limits as $-2x$ to $1$, and $y$ limits as $0$ to $2$. I don't think this is correct, can someone help me find the correct limits, particularly for the second integral?
Comment: I always recommend drawing the region
Answer: Observe that the region of integration of the first integral is a triangle:
$A = (0,0), B = (1,0), C = (1,2) \to I_1 = \displaystyle \int_{0}^2 \int_{y/2}^1 f(x,y)dxdy$
For the second one: $y = 4x-2x^2 = -2(x-1)^2+2\to (x-1)^2 = \dfrac{2-y}{2}\to x =  \sqrt{\dfrac{2-y}{2}}+1$.
$I_2  = \displaystyle \int_{0}^2 \int_{1}^{1+\sqrt{\frac{2-y}{2}}}f(x,y)dxdy$.
Notice that the graph of $y = 4x-2x^2$ has a vertex at $(1,2)$ which is the maximum of $y$,hence the limits of integration.
Comment: hi, could you explain the y/2 to 1 please?
Comment: You travel from the curve $x = y/2$ to the curve $x = 1$.


Writing Fermat's last theorem in arithmetic hierarchy

Question: Somehow connected with How natural numbers can be defined using primitive recursive $\Sigma_0^0$:
OK, so here's how Fermat's last theorem is formulated:
$$\forall x,y,z,n>2 \quad (x^n+y^n + z^n \rightarrow xyz = 0)$$
I get how this formula is $\Pi_1$, as we see $\forall$ sign. (For checks: $\forall x,y,z,n>2$ means that for any x,y,z (no limitation of "greater than 2") and any n greater than 2, right?)
So, what would be $\Pi_0$ part? It seems that $x^n+ y^n + z^n \rightarrow xyz=0$ would be that part, but two seemingly contradictory definitions confuse me - one is that $\Pi_0$ is quantifier-fre formula - and in this case, I get it, but in somehow different definition, such as Wikipedia, it says that $\Pi_0$ only uses bounded quantifier. But then, it seems to say a different thing... (in this case, $\forall n > 2 \quad x^n+ y^n + z^n \rightarrow xyz=0$ seems to be $\Pi_0$ formula..)
Also, usually when we talk of Fermat's last theorem we says that $x,y,z$ are integers. But the above formula lacks any designation that these variables are integers. So we can neglect this designation because we assumed that we are under (Peano.. probably) arithmetic?
(The linked post can be closed if that post seems to be a duplicate post of this one.)
Answer: The expression $x^n + y^n = z^n$ is not expressible in Peano arithmetic as a quantifier-free formula, because exponentiation is not part of the language of Peano arithmetic. However, it is expressible as a $\Pi^0_1$ formula and, separately, as a $\Sigma^0_1$ formula. This is because exponentiation is primitive recursive, and there is a standard way of handling primitive recursive functions via Gödel's β function.
Because the ultimate the goal is to write
$$
(\forall x,y,z,n) [ (n > 2 \land x^n + y^n = z^n) \to xyz = 0]
$$
 to be $\Pi^0_1$, you want to replace $x^n + y^n = z^n$ with a $\Sigma^0_1$ formula;  then the long formula can be put into prenex form, and the resulting formula will have only universal quantifiers.

Separately, some books use $\Sigma^0_0$, $\Pi^0_0$, and $\Delta^0_0$ for quantifier-free formulas, and other use the same notation for formulas with only bounded quantifiers. I believe the former is more common. Some care is needed to establish the conventions in each text your read.
Answer: When talking about the arithmetic hierarchy, we are dealing with the language of Peano arithmetic, so every variable is of type natural number anyway. Then a bounded quantifier is one of the form $\forall a<b\colon \phi$ or $\exists a<b\colon \phi$ (i.e. more explicitly  $\forall a\colon (a<b\to \phi)$ or $\exists a\colon (a<b\land\phi)$). These play a special role as the validity of such statements can be checked systematically in finite time (if $\phi$ can be checked in finite time) by simply testing $a=0, 1, \ldots, b-1$ in sequence. Your innermost statement, which should by the way rather read
$$x^n+y^n=z^n\to xyz=0$$
has no quantifiers at all (if we have exponentiation as a primitive). Hence it is vacuously true that all the quantifiers it has are bounded.
Note however that the quantifier in $\forall n>2\colon\phi$ (i.e. $\forall n\colon (n>2\to\phi)$) is not bounded in the sense of arithmetic hierarchy because it uses $>$, not $<$.
In real analysis we are used to bounded quatifiers such as $\forall \epsilon>0$ or $\forall h\in[0,1]\setminus\mathbb Q$, i.e. in a much broader sense, but for building up a hierarchy these do not qualify as making their statements simpler than others. For example, in the theory of real numbers, the unbounded $\forall x\colon\phi(x)$ is equivalent to the bounded $\forall x>0\colon(\phi(x)\land\phi(1-x))$.
It is the "finite FOR loop testing" associated with bounded quantifiers as mentioned above that makes statements involving them simpler than others, and this  is a specialty of the theory of natural numbers.


Specifying the number of clusters in nearest neighbor clustering

Question: I've got a distance matrix between examples. I want to cluster them into m clusters with a nearest neighbor algorithm which works like this:
<code>1. Set i = 1 and k = 1. Assign example x_1 to cluster C_1.
2. Set i = i + 1. Find nearest neighbour of x_i
   among the patterns already assigned to clusters.
   Let d_n  denote the distance from x_i to its nearest neighbour.
   Suppose the nearest neighbour is in cluster n.
3. If d_n less than or equal to t then assign x_i to C_n where t is the
   threshold specified by the user. Otherwise set k = k+1 and assign x_i  to a
   new cluster C_k.
</code>
How could I adapt this algorithm so I could specify how many clusters I want?
Is anybody aware of an existing R implementation of nearest neighbour clustering?
Comment: In this algorithm you cannot specify the number of clusters, you can change them varying parameter 't'. For R implementations just Google it, there is at least one.
Comment: Is this a homework question?
Comment: In 3. I think you mean "less than equal" instead of "greater than or equal", do you ?
Comment: It is not a homework. Oops, it was a mistake, I mean "less than equal".
Answer: As Dmitry Laptev already said correctly, the threshold t is determining the number of clusters indirectly. Using your algorithm there is no way to determine the number of clusters beforehand while still producing meaningful results.
As a more convenient bottom-up agglomerative nearest neighbor clustering approach you may want to take a look at Single Linkage, which works in a comparable (albeit certainly not equivalent) way. Single Linkage is implemented in R in hclust in the package stats
If you liked this approach, you should also take a look at the other linkage algorithms, especially Ward's method, which tends to deliver better results.
Comment: Thank you. I looked into single linkage hierarhical clustering and it is somehow similar to NN method.
Answer: A quick google search produces k-Nearest Neighbour Classification and knn (weighted k-nearest neighbors
Comment: Michael, for finding R solutions use http://www.rseek.org instead of Google.  One of the first hits when searching on "cluster" takes you to the [Cluster task view](http://cran.r-project.org/web/views/Cluster.html) listing approximately 100(!) packages.
Comment: I think these two are not meant for clustering (they don't work with distance matrix).
Comment: @genesiss the first link not, but the second one. From the description of the method specClust it uses [spectral clustering](http://www.kyb.mpg.de/fileadmin/user_upload/files/publications/attachments/Luxburg07_tutorial_4488%5b0%5d.pdf), but yes, a precomputed distance matrix cannot be supplied as far as I see.


Jenkins server not opening ports for slave connection

Question: I'm using Bitnami Jenkins virtual image with VMWare.
I'm getting a ConnectException Connection timed out to my Jenkins server when I try to connect a web start slave. I can access the Jenkins server from a web browser (port 80). Using nmap on the Jenkins server shows the port isn't open but using netstat shows that it's listening to the port.
Nmap:
bitnami@linux:~$ nmap localhost

Starting Nmap 6.40 ( http://nmap.org ) at 2015-05-18 17:45 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00057s latency).
Not shown: 995 closed ports
PORT     STATE SERVICE
21/tcp   open  ftp
22/tcp   open  ssh
80/tcp   open  http
443/tcp  open  https
8009/tcp open  ajp13

Netstat (shows port 59730 which I expect):
tcp6       0      0 :::59730                :::*                    LISTEN

Any ideas why this isn't automatic or working with the bitnami virtual machine?
Comment: Could you provide more details about your deployment? Could it be that there are security groups enabled that do not allow access to this specific port? How are you configuring the slave?
Answer: Bitnami VM images enable Uncomplicated Firewall by default and have only ports 80, 443 and 22 open.
Even though the port to start the slave is open, as netstat shows, you can't reach it from outside the VM because of the firewall. You should configure the firewall to open the port (59730 in your case), as explained in this FAQ and it should work.


is there a list of default values of css properties ? (so I can make an exclusion array in js for them)

Question: All sites that list css properties such like MDN or w3schools list every CSS property on separate pages.
When I'm iterating over CSSStyleDeclaration I get bunch of data that 90% of it are default values. Now I have not found another way of checking these values than to go to every page and look and then create my exclusion array so when looping over the object I can filter out not touched values.
But if it were a list somewhere I could copy it and do it a lot quicker than manually looking on every page.
(I assume there is no programatic way of checking from JS if given value is default, I can be almost sure that if it say none or auto or normal or 0px it is the default but this is not certain way of doing it)
Answer: The default-values are defined in the Recommendation .
But there is no guarantee that browsers follow that Recommendation.
Comment: Yes, I know but no one in whole Internet created a simple table with columns like this  it would be much more helpful than jumping back and forth between pages.
Comment: If you think it would be helpful you could be the first one that creates this simple list :)
Comment: If I only have time, and this is not only to the javascript, many languages manuals should have taken that cheat-sheet approach.
Answer: The specifications define initial values, i.e. the values to be used in the absence of any stylesheet or equivalent. The default values, in the sense of values used in the absence of any author stylesheet (= page stylesheet), are implementation-dependent. They depend on browsers (conceptually, on browser default stylesheets) and on their settings (user stylesheets or browser settings).
Finding out the initial values is just raw work, but you shouldn't expect them to be default values. There doesn't seem to be any way to programmatically find out the default values. For a specific browser, you might be able to locate its default stylesheet or its description, but they would tell you just the "factory defaults."
Comment: Thanks for clarifying, I didn't know that initial !== default.
Answer: If this is just for IE you may want to check out the runtimeStyle property
Answer: Here's a list of initial values I created after finding the w3 spec documents expectedly difficult to read:
var inheritedStyleInitialValues = {
    'azimuth': 'center',
    'border-collapse': 'separate',
    'border-spacing': '0',
    'caption-side': 'top',
    'color': '',
    'cursor': 'auto',
    'direction': 'ltr',
    'elevation': '',
    'empty-cells': 'show',
    'font-family': '',
    'font-size': 'medium',
    'font-style': 'normal',
    'font-variant': 'normal',
    'font-weight': 'normal',
    'letter-spacing': 'normal',
    'line-height': 'normal',
    'list-style-image': 'none',
    'list-style-position': 'outside',
    'list-style-type': 'disc',
    'orphans': '2',
    'pitch-range': '',
    'pitch': '',
    'quotes': '',
    'richness': '',
    'speak-header': '',
    'speak-numeral': '',
    'speak-punctuation': '',
    'speak': '',
    'speak-rate': '',
    'stress': '',
    'text-align': 'left',
    'text-indent': '0',
    'text-transform': 'none',
    'visibility': 'visible',
    'voice-family': '',
    'volume': '',
    'white-space': 'normal',
    'widows': '2',
    'word-spacing': 'normal'
}

Note that these are only the styles that descendant dom nodes inherit from their ancestors (because those are the only ones I care about for what I'm working on). The ones left blank I either couldn't find defaults for or vary between browsers.
I made this a community wiki so feel free to add to this list
Answer: You can create a new element with the same tag you are examining, and not append it to the document. It will have a style object with only the defaults set, and can be compared to the element in question- but it seems silly.
The defaults are just as real as any style assignments in style sheets- the browser does not ignore them, why would you?
Comment: I try to create a list of styles that gets computed on a tag from various sources, even from another JS scripts (for debug purposes). But CSSStyleDeclaration can't differentiate if a style was voluntarily touched or not. I don't want to spam my field of view with repetitive data.
Comment: This doesn't seem to work anymore. I can see maybe in 2012 it did but right now if I do `document.createElement('div').style` in Chrome everything is set to `""`


How to add the info icon to the nav bar and implement the showInfoView method?

Question: I am attempting to add an info button to the top of the navigation bar. The info button directs the user to the information view. The following code adds the iPhone default info button to the navigation bar. It is placed inside RootViewController.m 's viewDidLoad function.
UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
    [infoButton addTarget:self action:@selector(showInfoView:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];

Now, the showInfoView method needs to be implemented, and the following code is used:
- (IBAction)showInfoView:(id)sender {

// Create the root view controller for the navigation controller
// The new view controller configures a Cancel and Done button for the
// navigation bar.
InfoViewController *addController = [[InfoViewController alloc]
                                          initWithNibName:@"InfoView" bundle:nil];

// Configure the RecipeAddViewController. In this case, it reports any
// changes to a custom delegate object.
addController.delegate = self;

// Create the navigation controller and present it modally.

UINavigationController *navigationController = [[UINavigationController alloc]
                                                initWithRootViewController:addController];
[self presentModalViewController:navigationController animated:YES];

// The navigation controller is now owned by the current view controller
// and the root view controller is owned by the navigation controller,
// so both objects should be released to prevent over-retention.
[navigationController release];

[addController release];

}
But when the program builds and runs, clicking the info button results in the program crashing.
Did anyone come across this problem before? I have searched extensively and I haven't seen any body with trouble implementing the showInfoView method.
Answer: Use this code:
UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
[infoButton addTarget:self action:@selector(showInfoView:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = infoButton;

The showInfoView: method should work fine provided that the nib file name is "InfoView.xib" not "InfoViewController.xib"
Comment: Throws following error: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton createViewForNavigationItem:]: unrecognized selector sent to instance 0x4b51bb0'


how do I programmatically save nodes with multiple photo uploads?

Question: I have a very straight forward content type created in Drupal - Title, Body, Taxonomy term (drop down select, 1 value only), and Photos (multiple permitted, up to 8, alt and title tags are enabled).  I also have the meta
I have a set of CSV files with data for those fields with corresponding photos. I need to iterate over these programatically and use node_save() to get these in the database as well as upload the related photos.
I followed the direction here, and while it was a good start, I am still confused as to how to handle multiple uploads.
Bulk saving nodes with a file field
Can any suggest a tutorial or provide some sample code that can better illustrate how to do this?
EDIT:
Based on the direction below, this is the code I have come up with
$images = array();
foreach ($file_data_array as $csv_data) {
    foreach($image_array as $file_data) {
  $file = new stdClass();
  $file->filename = basename($file_data['filepath']);
  $file->filepath = $file_data['filepath'];
  $file->filemime = $file_data['mime'];
  $file->filesize = filesize($file_data['filepath']);
  $file->uid = $uid;
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  $images[] = array(
    'fid' => $file->fid,
    'alt' => $file_data['alt'],
    'title' => $file_data['title']
  );
}
$node = new stdClass;
$node->type = 'baby_clothes';
$node->body = 'body';
$node->title = 'title';
$node->uid = 1;
$node->status = 1;
$node->active = 1;

//the name of my actual field is 'product images'
$node->field_product_images[LANGUAGE_NONE] = $images;

//this is my actual taxonomy field
$node->field_baby_clothes_category[LANGUAGE_NONE][0]['tid'] = 2; //actual ID of the taxonomy for this node

node_save($node);
}

Thoughts?
Answer: You would normally just build up the files in a loop like so:
$images = array();

foreach ($file_data_array as $file_data) {
  $file = new stdClass();
  $file->filename = basename($file_data['filepath']);
  $file->filepath = $file_data['filepath'];
  $file->filemime = $file_data['mime'];
  $file->filesize = filesize($file_data['filepath']);

  $file->uid = $uid;
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);

  $images[] = array(
    'fid' => $file->fid,
    'alt' => $file_data['alt'],
    'title' => $file_data['title']
  );
}

$node = new stdClass;
// Build up the rest of the node as normal

$node->field_images[LANGUAGE_NONE] = $images;

node_save($node);

This assumes you have your CSV data loaded into an array called $file_data_array.
fid, alt, title, height and width are the only columns available to an image field type so there's no need to build up an array for each field entry containing all the file details (you can ignore that bit in the other answer you linked to as it's unnecessary).
Also note the use of file_save() instead of drupal_write_record() to commit the file to the database...it's much better to use file_save() as it fires the necessary system hooks to let other modules react to your files being added.
Hope that helps
Comment: Thanks, that is helping quite a bit.  One thing I believe is confusing me, I guess I don't have to worry about writing the actual images files anywhere? What I mean is, this all looks like it just references a file. After these process, I just upload all of my files to the sites/default/files directory and let Drupal take care of the rest?
Comment: Please see the above code I added in my edit.  Clive, to take care of the image array, did you mean that the images array needed its on foreach loop within the foreach loop that iterates through the CSV file?
Answer: You need to create a dummy node normally and then look at the saved $node array to get an example.
Try the below in a block while you view that page

<?php print_r($node) ?>

Once you can see the format of the data you can then write the code required to save the picture fields. They will probably be a multi dimensional array with things like the alt and title tags set etc...
Post up the $node array in your question for more advice
Comment: Ah, thank you for that, very helpful to see what is available to me via that function.
Comment: For these purposes, it's better to use dpm() function that the Devel module provides, it makes browsing through your object or array much much easier.


Maps transformations in scala (computing tags frequencies)

Question: I'm still not proficient with scala, but I'm using it to process some data, which I read into from a file into the following data structure:
Map[Id, (Set[Category], Set[Tag])]
where
type Id = String

type Category = String

type Tag = String

Essentially, each key in the Map is the unique id of an entity that is associated with a set of categories and a set of tags.
My question is: which is the best ( = most efficient and most idiomatic) way to compute:

tags frequencies across all entities (type TagsFrequencies = Map[Tag, Double])
tags frequencies per category (Map[Category, TagsFrequencies])

Here is my attempt:
def tagsFrequencies(tags: List[Tag]): TagsFrequencies =
  tags.groupBy(t => t).map(
    kv => (kv._1 -> kv._2.size.toDouble / tags.size.toDouble))

def computeTagsFrequencies(data: Map[Id, (Set[Category], Set[Tag])]): TagsFrequencies = {
  val tags = data.foldLeft(List[Tag]())(
    (acc, kv) => acc ++ kv._2._2.toList)
  tagsFrequencies(tags)
}

def computeTagsFrequenciesPerCategory(data: Map[Id, (Set[Category], Set[Tag])]): Map[Category, TagsFrequencies] = {

  def groupTagsPerCategory(data: Map[Id, (Set[Category], Set[Tag])]): Map[Category, List[Tag]] =
    data.foldLeft(Map[Category, List[Tag]]())(
      (acc, kv) => kv._2._1.foldLeft(acc)(
        (a, category) => a.updated(category, kv._2._2.toList ++ a.getOrElse(category, Set.empty).toList)))

  val tagsPerCategory = groupTagsPerCategory(data)
  tagsPerCategory.map(tpc => (tpc._1 -> tagsFrequencies(tpc._2)))
}

As an example, consider
val data = Map(
  "id1" -> (Set("c1", "c2"), Set("t1", "t2", "t3")),
  "id2" -> (Set("c1"), Set("t1", "t4")))

then:
tags frequencies across all entities is:
Map(t3 -> 0.2, t4 -> 0.2, t1 -> 0.4, t2 -> 0.2)

and tags frequencies per category is:
Map(c1 -> Map(t3 -> 0.2, t4 -> 0.2, t1 -> 0.4, t2 -> 0.2), c2 -> Map(t3 -> 0.3333333333333333, t1 -> 0.3333333333333333, t2 -> 0.3333333333333333))

Answer: Here's a rewrite for idiom, not necessarily efficiency. I'd make your first method a little more general (the Iterable argument), use identity instead of t => t, and use mapValues:
def tagsFrequencies(tags: Iterable[Tag]): TagsFrequencies =
  tags.groupBy(identity).mapValues(_.size / tags.size.toDouble)

Because this now takes any Iterable[Tag], you can use it to clean up the second method:
def computeTagsFrequencies(data: Map[Id, (Set[Category], Set[Tag])]) =
  tagsFrequencies(data.flatMap(_._2._2))

And similarly for the last method:
def computeTagsFrequenciesPerCategory(data: Map[Id, (Set[Category], Set[Tag])]) =
  data.values.flatMap {
    case (cs, ts) => cs.map(_ -> ts)
  }.groupBy(_._1).mapValues(v => tagsFrequencies(v.flatMap(_._2)))

None of these changes should affect performance in any meaningful way, but you should of course benchmark in your own application.


Selecting the taxonomy terms to use using a textfield to search them

Question: My Drupal 7 site has almost thousand of taxonomy terms. So it is a hard work for my users to pick their desired category from thousand of taxonomy terms.
Is there any way to select a taxonomy term by using a small search box to choose the exact category and sub-category?
Answer: You can try using Views to build a custom search with exposed forms. And the use the fields to display terms the way you need it. That is probably the easiest.
Comment: can u please elaborate..


Mesure the impact of two variables

Question: <code>>          day1      day2      day3      day4       day5     day6
>          [,1]      [,2]      [,3]      [,4]      [,5]      [,6]
Round1[1,] 1.1207018 0.9727621 0.8193898 0.7632462 0.7999830 0.5990948
Round2[2,] 0.8691757 1.0327617 0.9073291 0.8068437 0.8067108 0.6849726
Round3[3,] 0.9204398 0.9728258 0.8829158 0.7979679 0.7517258 0.6474946
Round4[4,] 1.0180250 0.9232659 0.9483964 0.8013724 0.6599834 0.6239292
Round5[5,] 1.0481627 0.9085355 0.8098388 0.8491411 0.7670144 0.6623544
Round6[6,] 1.0158818 0.9829552 0.7984692 0.8601835 0.6692525 0.7082392
> >
</code>
For 6 days, participants participate on experiment on which they have to answer through mouse. The value in the Matrix are the means of response time every round.
I'm wondering, through such kind of data if it's possible to demonstrate which of the following : the effect of habituation or fatigue, have more impact on response time, between rounds, between days and between participant.
What type of analysis should I use in this case ?
Answer: You can use multilevel modelling.
I assume you the matrix you showed in your example is data for one particular participant and you have the data like that for individuals in your study (not only average values).
If that is the case, you can treat rounds (or repeated measures), days, and participants as different levels of variation of the response time. Different participants have different response time, but if there is some indication of either habituation or fatigue, you should also see additional significant effect of either day or round, respectively.

Mesure the impact of two variables


Magento2: Argument 1 [...] must be an instance of Magento\Framework\App\Helper\Context

Question: First of all, I'm quite new to Magento 2, but I've used Magento 1.x for some time.
I've read a lot about how to solve DI-related problems, but I'm stuck on this one:

Exception #0 (Exception): Recoverable Error: Argument 1 passed to Cefar\AO\Helper\Ao::__construct() must be an instance of Magento\Framework\App\Helper\Context, instance of Magento\Framework\ObjectManager\ObjectManager given, called in .../vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 93 and defined in .../Cefar/AO/Helper/Ao.php on line 11

Many other answers have suggested deleting the var/di and var/generation folders, sometimes var/cache also. While this solves the problem, it occurs again once bin/magento setup:di:compile is run, which means the code cannot be used in a production environment.
I've checked that the Ao class does not instantiate any objects. It also doesn't try to re-make any objects that could be provided by the context given. Here's the code:
namespace Cefar\AO\Helper;

class Ao extends \Magento\Framework\App\Helper\AbstractHelper
{
    const DEFAULT_GRID_COLS = 4;

    protected $_session;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Customer\Model\Session $session
    )
    {
        parent::__construct($context);
        $this->_session = $session;
    }

    public function getConfig($path)
    {
        return $this->scopeConfig->getValue($path);
    }

    public function isActive($url = null, $print = true) {
        $active = ($url && strstr($_SERVER['REQUEST_URI'], $url) !== false);

        if ($active && $print) {
            echo "active";
        } else {
            return $active;
        }
    }

    public function isLoggedIn()
    {
        return $this->_session->isLoggedIn();
    }

    public function limitWords($text = '', $limit = 10, $showDots = true)
    {
        $words = explode(' ', $text);
        $limited = array_slice($words, 0, $limit);
        $newText = implode(' ', $limited);

        if (count($words) > $limit && $showDots) {
            $newText .= '...';
        }

        return $newText;
    }

    public function getCurrentGrid()
    {
        return ($this->_getRequest()->getParam('grid'))
            ? $this->_getRequest()->getParam('grid')
            : self::DEFAULT_GRID_COLS;
    }
}

There's nothing particularly special here. I'm confused as to how this is even happening; every other defined class in the extension is getting its DI parameters correctly. Why is the ObjectManager apparatus providing an unwanted argument? The relevant call is given in the error report as:

.../vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(93): Cefar\AO\Helper\Ao->__construct(Object(Magento\Framework\ObjectManager\ObjectManager))

So it isn't even providing two arguments!
I've also read about providing type hints in a di.xml, but it doesn't seem to be relevant here as both types are part of the Magento libraries? I note that there is an entry for Magento\Framework\App\Helper\Context but not one for Magento\Customer\Model\Session... but that there are framework classes that use ID to import Magento\Customer\Model\Session already which work.
Answer: Long story short, this was because of a typo.
Sometimes when the helper was being included, it was being referred to as Cefar\AO\Helper\Ao, and other times, Cefar\AO\Helper\AO. Essentially, the ObjectManager was resolving both of these references to the same class, but it only had type hints for one of the names so it didn't know what to provide to the incorrect one.
A little help would have been nice, Magento! Maybe an error report that the requested class wasn't found? Still, at least this is finally over with.


PhoneGap: Update Files (.html) for further use offline

Question: I want to have an app, that provides only simple information in an table.
I use PhoneGap. I got my information right now and I can write them in the HTML file.
But there will be some changes, do I have to wait with the publish, or is it possible to get the new infos.html file from my server with an click on a refresh button and store it local, so the user still can get it w/out internet connection?
Answer: You can't replace the local files. What you can do is build your interfaces dynamically using Javascript and use AJAX to download the HTML for them. You can store it locally for offline access using window.localStorage.


What is the point of the NBA regular season?

Question: I am trying to get into NBA, but ... I don't get it. The regular season seems completely pointless and irrelevant to me. There are 30 teams, and the top 16 (that's more than half!!) make it to the playoffs.
Huh?
Doesn't that make the regular season completely irrelevant and uninteresting to watch? What's the point of it, when most teams go through to playoffs anyways. There's just so little on the line? Is it really all just a seeding-competition to determine who fights who in playoffs?
This is in contrast to European soccer, where the winner of the regular season is the champion. That means every game means something, you're not just waiting for playoffs to come.
Comment: There are still at least 12 matches to go for teams in the EPL, but unless something significant changes in the next two months (on the order of [1958](https://en.m.wikipedia.org/wiki/Munich_air_disaster)) only three teams have a realistic chance of the title, and only five have even a mathematical chance. A game involving two of the other fifteen teams is now entirely pointless under the criteria you're focused on.
Comment: @Nij The point about this question is why the league type regular season is even played if the only point is to eliminate about half of the teams before the playoffs. In a simple regular season system like the EPL every team always stays in the game and there are various other points about the season results like relegation or qualification for continental competitions!
Answer: The NBA regular season (and similarly, the NHL) isn't pointless. You say that roughly half the teams make the playoffs, which means that roughly half miss the playoffs. The regular season helps filter the top half from the bottom half when determining the playoff field.
In addition, it helps to seed the playoffs. The best teams in each conference get to play the worst teams (that made the playoffs) in each conference. If the 8th best team is truly much worse than the 1st place team, then there should be no problem and the 1st place team gets to advance to the second round easily. If there isn't a large disparity, then the large playoff field does become necessary as a Best-of-Seven series can help ensure that the better team gets to advance.
The biggest reason why the NBA regular season (and NHL, and NFL, etc) matters though is probably the Draft. During each off-season, there is a draft process held in which every team gets to claim signing rights of newly-eligible players. The draft is mostly in reverse-regular-season-standing order, so worse teams get to have a higher seeding in the picks. This helps the league stay competitive.
Comment: Regarding the last paragraph: still many teams are not "tanking", even though it would be beneficial for the team that can't reach the playoffs in that season.
Comment: Yeah, tanking can be a problem. That is why they have the draft lottery in place. In the NHL, any team that misses the playoffs can win the draft lottery and move up to a Top 3 pick. Teams lower in the standings have better odds but it's not guaranteed. I know the NBA has a similar system but not sure on the specifics


MySQL Case Conditions Deduction to generate balance

Question: I have a MySQL table named, "store_update_stock" to store purchase & issue of items. Order status column maintain the states, "purchase" or "issue" when need. Purchase quantity has denoted by plus values (eg:-10) & issue quantity has denoted by minus values (eg:- -2) in the table.
To get the purchase & issue summary I used the following query.
SELECT item_id, item_name, order_status, (CASE order_status
        WHEN "issue" THEN store_update_stock_details.qty * (-1)
        ELSE store_update_stock_details.qty
        END) quantity FROM store_update_stock

And generated the expected output as follows :
+---------+-----------+--------------+----------+
| item_id | item_name | order_status | quantity |
+---------+-----------+--------------+----------+
|    1000 | A4        | purchase     |       10 |
|    1001 | A3        | purchase     |        5 |
|    1000 | A4        | issue        |        2 |
|    1000 | A4        | issue        |        3 |
|    1001 | A3        | purchase     |        6 |
+---------+-----------+--------------+----------+

But I need to get further the balance of each items after performing purchases & issues by modifying the above query and get the output as follows :
+---------+-----------+---------+
| item_id | item_name | balance |
+---------+-----------+---------+
|    1000 | A4        |       5 |
|    1001 | A3        |      11 |
+---------+-----------+---------+

What can be done in my query to get the desired output. Can anyone helpme ?
Comment: It looks like all you might need is a simple aggregate sum and a group by: `select item_id, item_name, sum(quantity) as balance from store_update_stock group by item_id, item_name` maybe?
Comment: @jpw. That's it
Answer: It looks like all you might need is a simple aggregate sum and a group by:
select item_id, item_name, sum(quantity) as balance
from store_update_stock
group by item_id, item_name

maybe?


Find the the least integral value of a for which all the roots of the equation $x^4-4x^3 -8x^2 +a=0$ are real

Question: The least integral value of a for which all the roots of the equation $x^4-4x^3 -8x^2 +a=0$ are real.
let $f(x) =x^4-4x^3 -8x^2 +a=0$
$  f'(x) = 4x^3 -12x^2 -16x $
Put $f'(x) = 0 $ we get x =0, -1, 4. How to proceed further, I am not getting any idea on this. Please guide thanks.
Answer: By your work, we have that $f(x) =x^4-4x^3 -8x^2 +a$ is a continuous function which is strictly monotone in each one of the following intervals: strictly decreasing in $(-\infty,-1]$, strictly increasing in $[-1,0]$, strictly decreasing in $[0,4]$, and strictly increasing in $[4,-\infty)$. Now apply the Intermediate Value Theorem. For example, for $x\in(-\infty,-1]$, $f(x)$ attains once and only once each value in $(\lim_{x\to-\infty}f(x),f(-1)]=(+\infty,-3+a]$. Hence we have one root in $(-\infty,-1)$  if and only if $-3+a<0$, i.e. $a< 3$.
Can you take it from here?
Comment: answer is 2, why it is not 1. if $ 0\leq a <3$
Comment: @sultan The smallest integer $a$ IS 1. Note that $x^4-4x^3-8x^2+1=0$ HAS $4$ real roots.  $2$ is largest one.
Comment: thanks a lot.. i am very greatful to...you...God bless you.. thanks once again.
Answer: Let $f(x)=x^4-4x^3-8x^2+a$, $$f'(x)=4x^3-12x^2-16x=0 \Rightarrow x=4,-1,0$$
Next $f''(x)=12x(x-2)-16.$ so $f(x)$ has local minima at at $x=4,-1$ and loca max at $x=0.$ Hence $f_{min}=a-128, a-3$, $f_{max}=a$. For four real rootss: $f_{min}<0$ and
$f_{max}>0.$ Thus, for four real roots $$a \in( 0,3).$$
Both the integers $a=1,2$ are the solutions.
See the fig. for a=1, below
$f(x)$ for $a=1$">
See the fig. for $a=2$, below
Comment: why answer is not 1, it is given answer is 2. why.
Comment: @sultan both a=1 and 2 are solutions, I have now added both the figures.
Comment: Ok thanks a lot .. it was really great..... and very helpful... i am really greatful to you.... God bless you.
Comment: @sultan Also, now choose a solution.
Answer: Hint
I think that considering the second derivative could help.
$$f''(x)=12 x^2-24 x-16$$ shows that

$x=-1$ corresponds to a minimum since $f''(-1)=20$
$x=0$ corresponds to a maximum since $f''(0)=-16$
$x=4$ corresponds to a minimum since $f''(4)=80$

So, in order to have four real roots, you need ... ?
Answer: The easiest way to see what is going on is to sketch the curve - you have enough information for a sufficiently good sketch. Then changing the constant term shifts the curve vertically (moves it up or down).
How much do you need to shift it, and in what direction (up or down) to meet the condition?
I think a sketch would be a helpful guide to the mathematical analysis you need to do.
Answer: Hint: Consider $g(x) =x^4-4x^3 -8x^2$ and look for horizontal lines that cross the graph of $g$ four times (tangencies count twice). The values of $g$ at its critical points are the key in this argument.


What's the "$it" in a shell command?

Question: > sys | get host.users | echo $it

It's from the introduction page of the Nu Shell.
I've already known something like "$.." is a variable in shell, but I can't find any definition before using.
image
Answer: From the repo: ...$it to refer to the value being piped to the external command.
So, in order to use commands outside of Nu once you have the data you want, $it refers to the value you wanna pipe to the external command.
In your example it is explained:

If this looks very similar to what we had before, you have a keen eye!
  It is similar, but with one important difference: we've called echo
  with the value we saw earlier. This allows us to pass data out of Nu
  into echo (or any command outside of Nu, like git for example)

What's the "$it" in a shell command?


Fantec SRC-2080x7 connect backplane from SAS to Sata

Question: I've read this topic: How exactly does a SAS SFF-8087 breakout cable work? + RAID/connection questions
Which basically explains that you can go from sata to SAS, but not vice versa.
However, from the store page of the Fantec SRC-2080x7 chassis I've seen a few reviews where people seem to use a breakout cable to connect the sata ports from the motherboard to the Mini SAS port (SFF-8087) on the backplane (where sata HDD's are connected).
Is there an exception to this backplane regarding this cable?
Because the SFF-8087 breakout cable doesn't seem to be working for me. Which would be consistent with the topic I linked above, though I'd be suprised if the people in the reviews haven't tested it before posting their review.
Note: The store page is in german and I've been translating everything to english by using Google Translate
This is the page of the chassis by the manufacturer, but also in german (even the english language at the top-right doesn't help).
EDIT: My backplane model is DH-6GMSAS-03A
Answer: SFF-8087 connectors are frequently used for SATA multi-port connections as well - on backplanes or sometimes even on RAID controllers. In reverse, you can use a SFF-8087-to-4xSATA fanout cable to connect standard on-board SATA ports to a (passive) SAS cage or the Fantec case you've linked to, where you plug the SATA drives (obviously, SAS drives would fit but won't work).
That said, I've seen some really low-quality fanout cables that were hard to correctly plug into the SFF-8087 receptacle - and in one case extremely hard to remove again. Make sure everything is plugged correctly, the 8087 is latched, and the drives are powered before or together with system power.
Comment: SAS cabling is somewhat higher-grade but basically the same as SATA cabling, the different connectors are invisible to the controller or drives. Therefore, if everything is correctly connected it should work in any case. I've even run SAS drives over SATA cables (fanout + adapters) without problems.
Comment: I think I've figured out why no data connection is made. I have a forward breakout cable, and apparently need a reverse breakout cable.
Comment: Hm yes the power lights turn on properly, and the data LED just blinks very briefly upon powering the system but no activity (no spin-up or anything) leading me to believe it has no actual connection to the motherboard.

Tried it with both of my SFF-8087 fanout cables as well as in the different backplanes (they're separated in an upper and lower backpane) but no combinations seem to work.

If it's true that it should work that at least makes me a happy person because a SAS controller would be way more expensive. I'll have a look if wiggling the cables fixes anything and report back, Thx!
Comment: Upon further testing it would seem the upper backplane only provides power to 1 of the 4 HDD's, whereas using the same molex connections on the lower backpane provides power to all 4 HDD's just fine. I'm beginning to suspect there's more to this then just the cables, so I contacted amazon and will wait for their response.
Comment: could it potentially have something to do with my Motherboard requiring some kind of compatibility? it's an MSI H55M-E33. I'd doubt it, but backplanes and SAS are pretty new terrain for me.
Comment: So this answer is incorrect? https://serverfault.com/a/778095/161482
Comment: Well, not entirely. You *can* connect a SAS backplane with SATA drives to a SATA controller without a problem.


Componente com mesmo height

Question: Existe uma maneira de fazer com que um LinearLayout tenha o mesmo height que um TextView?
       <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/blue"/>

        <ImageView
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentRight="true"
            app:srcCompat="@drawable/edit"/>

        <ImageView
            android:id="@+id/lista_imagem"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="5dp"
            android:layout_marginLeft="5dp"
            app:srcCompat="@drawable/avatar"
            android:layout_marginStart="5dp" />

        <TextView
            android:id="@+id/lista_nome"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toEndOf="@+id/lista_imagem"
            android:layout_toRightOf="@+id/lista_imagem"
            android:text="Titulo"
            android:textSize="12sp"
            android:textStyle="bold" />

Eu queria que o
 android:layout_height=""

Do meu linear layout tivesse o mesmo tamanho do TextView lista_nome, lembrando que este deve ser wrap_content porque o texto muda de tamanho. Existe uma maneira de fazer isso? Sei que por dimen você define um valor padrão, mas teria uma forma de fazer esse valor ser igual ao do TextView, por exemplo?
Edit: O TextView não pode ficar dentro desse LinearLayout
Answer: É possível se feito no java.
Atribua um Id ao LinearLayout(android:id="@+id/linearLayout") e no onCreate() adicione o seguinte código:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ...
    ...
    final LinearLayout layout = findViewById(R.id.linearLayout);
    final TextView listaNome = findViewById(R.id.lista_nome);
    ...
    ...

    listaNome.getViewTreeObserver().addOnGlobalLayoutListener(new

         ViewTreeObserver.OnGlobalLayoutListener() {
             @Override
             public void onGlobalLayout() {

                 //Remove o listenner para não ser novamente chamado.
                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                     layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                 } else {
                     //noinspection deprecation
                     layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                 }

                 //Obtém os parâmetros do LinearLayout
                 LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) layout.getLayoutParams();
                 //Atribui a altura do TextView à altura do LinearLayout
                 layoutParams.height = listaNome.getHeight();
                 layout.setLayoutParams(layoutParams);
             }
         });
}

Comment: Muito obrigado ramaral, funcionou aqui
Answer: Uma forma alternativa sem precisar usar o java:
<LinearLayout
          ...
          android:layout_alignParentTop="true"
          android:layout_alignBottom="@+id/lista_nome"
          .../>

Comment: Isso só funciona nesse caso especifico, em que as views estão num RalativeLayout e nessa posição relativa entre elas.

Componente com mesmo height


Conecto no banco mas os valores não altera quando dou UPDATE MYSQL Qt C++

Question: Os dados são carregados na tabela, ai eu altero os dados na tabela, quando clico no botão para atualizar, consigo pegar os dados(ate mesmo as alterações) e guardar na variável, mas parece que quando entro na query sql nada acontece. Preciso poder atualizar os dados da tabela assim que alterar algo e clicar no botão atualizar.
Conexão com o banco(ok):

void ConectaBanco()
{
    //Variavel do tipo DataBase
    QSqlDatabase db;

    //Conexao com o MYSQL
    db = QSqlDatabase::addDatabase("QMYSQL");

    //Servidor que vai receber o DB (padrão do server local)
    db.setHostName("127.0.0.1");

    //Porta que vai conectar com o DB (por padrão vai ser 3306)
    db.setPort(3306);

    //Seleciona o banco de dados
    db.setDatabaseName("cursos");

    //Usuario do BD
    db.setUserName("root");

    //Caso tenha senha no mysql
    //db.setPassword();

    //Teste de conexao
    if(db.open())
    {
        qDebug()<<"Sucesso ao abrir a conexão";
    }
    else
    {
        qDebug()<<db.lastError().text();
    }
}

Função atualizar:

void MainWindow::on_pushButton_clicked()
{
    int fila = 0;
    ConectaBanco();
    int CdAluno = ui->tabelaCarga->model()->data(ui->tabelaCarga->model()->index(fila,0)).toInt();
    QString NmAluno = ui->tabelaCarga->model()->data(ui->tabelaCarga->model()->index(fila,1)).toString();
    QString NmCurso = ui->tabelaCarga->model()->data(ui->tabelaCarga->model()->index(fila,2)).toString();
    QString NmEscola = ui->tabelaCarga->model()->data(ui->tabelaCarga->model()->index(fila,3)).toString();

    QSqlQuery query("UPDATE matricula set NmAluno= '"+NmAluno+"', "
                                         "NmCurso= '"+NmCurso+"', "
                                         "NmEscola='"+NmEscola+"' "
                                         "WHERE CdMatricula='"+CdAluno+"'");
    query.exec();

}

Quando debugo e coloco o mouse em cima do da string UPDATE aparece a seguinte mensagem: no much value

Gostaria de saber como resolver o problema e conseguir alterar os dados perfeitamente.
Answer: Ao invés de concatenar a string de query, tente algo assim:
#include <QVariant>
...
...

QSqlQuery query
query.prepare("UPDATE matricula SET NmAluno= ?, NmCurso= ?, NmEscola=? WHERE CdMatricula=?");

query.addBindValue(NmAluno);
query.addBindValue(NmCurso);
query.addBindValue(NmEscola);
query.addBindValue(CdAluno);

if( ! query.exec()) {
    qDebug() << "Erro ao executar query!!";
}

E cuidado, o que está no seu método void ConectaBanco(), só pode sr executado uma única vez. Se você adicionar um BD duas vezes, você vai ter um erro de conexão duplicada(como tá aparecendo aí na sua telinha de output do Qt Creator) e o seu código pode não funcionar como você espera. Se eu fosse você criaria uma classe auxiliar pra manejar as conexões ao MySql.
Answer: A função atualizar deveria estar com o campo CdMatricula no formato string para a query reconhecer o codigo:

void MainWindow::on_pushButton_clicked()
{
    ConectaBanco();
    int linha = 0;
    QString CdAluno = ui->tabelaCarga->model()->data(ui->tabelaCarga->model()->index(linha,0)).toString();
    QString NmAluno = ui->tabelaCarga->model()->data(ui->tabelaCarga->model()->index(linha,1)).toString();
    QString NmCurso = ui->tabelaCarga->model()->data(ui->tabelaCarga->model()->index(linha,2)).toString();
    QString NmEscola = ui->tabelaCarga->model()->data(ui->tabelaCarga->model()->index(linha,3)).toString();

    qDebug()<<CdAluno<<NmAluno<<NmCurso<<NmEscola;

    QSqlQuery query;

    query.prepare("UPDATE `matricula` SET `NmAluno` = '"+NmAluno+"', "
                                         "`NmCurso` = '"+NmCurso+"', "
                                         "`NmEscola` = '"+NmEscola+"'"
                                         " WHERE `matricula`.`CdMatricula` = '"+CdAluno+"'");

    if(query.exec())
    {
        qDebug()<<"Query executada com sucesso!";
    }
    else
    {
        qDebug()<<"Erro ao executar a query";
    }

    //atualiza a tabela automaticamente
    on_btnCarga_clicked();
}


how to interpret metrics for my model

Question:
I understand how these metrics are determined but can anyone give me typical poor, acceptable, good, and outstanding values RAE and RSE?
Answer: Without any other context, it is difficult to give absolute ranges that generalize to every problem.
I suppose the only objective ranges that could be given are as follows:
If the resulting relative value is greater than 1, your model is bad because a simple mean model beats it.
If the resulting relative value equals zero, then your model perfectly predicted the validation data which is good.
That said, if your model is meant to predict stock prices and it had any relative error metric consistently and statistically significantly less than 1, that would be considered amazing. On the other hand, s your model were given as an input the height an object was dropped and had to predict the amount of time it fell, a value very close to zero would be expected.

how to interpret metrics for my model


creating json file from database

Question: I need to create this json in the following format
<code>{
  "status": true,
  "message": "",
  "orders": [
    {
      "orderId": "1",
      "orderDate": "1/06/2021",
      "products": [
        {
          "productName": "Product 1",
          "quantity": "1",
          "price": "5.00"
        },
        {
          "productName": "Product 2",
          "quantity": "2",
          "price": "24.00"
        },
        {
          "productName": "Product 3",
          "quantity": "1",
          "price": "6.50"
        }
      ]
    },
    {
      "orderId": "2",
      "orderDate": "2/06/2021",
      "products": [
        {
          "productName": "Product 1",
          "quantity": "1",
          "price": "3.00"
        },
        {
          "productName": "Product 2",
          "quantity": "1",
          "price": "11.50"
        }
      ]
    },
    {
      "orderId": "3",
      "orderDate": "03/05/2021",
      "products": [
        {
          "productName": "Product 1",
          "quantity": "1",
          "price": "3.00"
        },
        {
          "productName": "Product 2",
          "quantity": "1",
          "price": "11.50"
        }
      ]
    }
  ]
}
</code>
This is my code that I use to retrive the information from the database
<code>$stmt = $con->prepare("SELECT OrderID, OrderDate, ProductName, ProductQty, ProductPrice FROM Orders where CustomerID = ?");
$stmt->bind_param("s", $CustomerID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($OrderID, $OrderDate, $ProductName, $ProductQty, $ProductPrice);
while($stmt->fetch()) {
    $message[] = array(
        "status" => true,
        "message" => "",
        "orders" => array(
            array(
                "orderId" => "$OrderID",
                "orderDate" => "$OrderDate",
                "products" => array(
                    array(
                        "productName" => "$ProductName",
                        "quantity" => "$ProductQty",
                        "price" => "$ProductPrice"
                    ),
                )
            )
        )
    );
}

$json = $message;

header('content-type: application/json');
echo json_encode($json);
</code>
This is how the information from the database displays. I do not know how to show the information about the products correctly. Can anyone show me how to do it in the format that I require in php? Thanks in advance for any help.
<code>[
  {
    "status": true,
    "message": "",
    "orders": [
      {
        "orderId": "1",
        "orderDate": "1/06/2021",
        "products": [
          {
            "productName": "620",
            "quantity": "1",
            "price": "5.00"
          }
        ]
      }
    ]
  },
  {
    "status": true,
    "message": "",
    "orders": [
      {
        "orderId": "1",
        "orderDate": "1/06/2021",
        "products": [
          {
            "productName": "240",
            "quantity": "1",
            "price": "5.00"
          },
          {
            "productName": "270",
            "quantity": "1",
            "price": "10.00"
          }
        ]
      }
    ]
  },
  {
    "status": true,
    "message": "",
    "orders": [
      {
        "orderId": "1",
        "orderDate": "1/06/2021",
        "products": [
          {
            "productName": "30",
            "quantity": "1",
            "price": "5.00"
          }
        ]
      }
    ]
  },
  {
    "status": true,
    "message": "",
    "orders": [
      {
        "orderId": "1",
        "orderDate": "1/06/2021",
        "products": [
          {
            "productName": "280",
            "quantity": "1",
            "price": "5.00"
          }
        ]
      }
    ]
  },
  {
    "status": true,
    "message": "",
    "orders": [
      {
        "orderId": "1",
        "orderDate": "1/06/2021",
        "products": [
          {
            "productName": "610",
            "quantity": "1",
            "price": "5.00"
          }
        ]
      }
    ]
  }
]
</code>
Answer: You are repeating the orders structure which you shouldn't. That's why you get the wrong structure. This is what you should do instead (your code, modified):
<code>// specify your return response array only once
$message = array(
    "status" => true,
    "message" => "",
    "orders" => array();
);

$stmt = $con->prepare("SELECT OrderID, OrderDate, ProductName, ProductQty, ProductPrice FROM Orders where CustomerID = ?");
$stmt->bind_param("s", $CustomerID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($OrderID, $OrderDate, $ProductName, $ProductQty, $ProductPrice);

while($stmt->fetch()) {
    // and fill its "orders" member with your orders list
    $message["orders"][] = array(
        "orderId" => "$OrderID",
        "orderDate" => "$OrderDate",
        "products" => array(
            array(
                "productName" => "$ProductName",
                "quantity" => "$ProductQty",
                "price" => "$ProductPrice"
            ),
        )
    );
}

$json = $message;

header('content-type: application/json');
echo json_encode($json);
</code>
Comment: Thanks for this. It has got me started on the right track. Only thing is orderId and orderDate is repeating each time and I just want to show it once
Comment: I have changed the code a bit (moved the $message declaration from between the `bind_params` row and the `while` cycle to the top). I'd debug the bind_result part, as that's where your problem is.
Answer: You can try like below
<code>const data = [
    {
        "status": true,
        "message": "",
        "orders": [
            {
                "orderId": "1",
                "orderDate": "1/06/2021",
                "products": [
                    {
                        "productName": "620",
                        "quantity": "1",
                        "price": "5.00"
                    }
                ]
            }
        ]
    },
    {
        "status": true,
        "message": "",
        "orders": [
            {
                "orderId": "1",
                "orderDate": "1/06/2021",
                "products": [
                    {
                        "productName": "240",
                        "quantity": "1",
                        "price": "5.00"
                    },
                    {
                        "productName": "270",
                        "quantity": "1",
                        "price": "10.00"
                    }
                ]
            }
        ]
    },
    {
        "status": true,
        "message": "",
        "orders": [
            {
                "orderId": "1",
                "orderDate": "1/06/2021",
                "products": [
                    {
                        "productName": "30",
                        "quantity": "1",
                        "price": "5.00"
                    }
                ]
            }
        ]
    },
    {
        "status": true,
        "message": "",
        "orders": [
            {
                "orderId": "1",
                "orderDate": "1/06/2021",
                "products": [
                    {
                        "productName": "280",
                        "quantity": "1",
                        "price": "5.00"
                    }
                ]
            }
        ]
    },
    {
        "status": true,
        "message": "",
        "orders": [
            {
                "orderId": "1",
                "orderDate": "1/06/2021",
                "products": [
                    {
                        "productName": "610",
                        "quantity": "1",
                        "price": "5.00"
                    }
                ]
            }
        ]
    },
    {
        "status": false,
        "message": "",
        "orders": [
            {
                "orderId": "1",
                "orderDate": "1/06/2021",
                "products": [
                    {
                        "productName": "800",
                        "quantity": "50",
                        "price": "5.00"
                    }
                ]
            }
        ]
    },
    {
        "status": false,
        "message": "",
        "orders": [
            {
                "orderId": "1",
                "orderDate": "1/06/2021",
                "products": [
                    {
                        "productName": "1800",
                        "quantity": "50",
                        "price": "5.00"
                    }
                ]
            }
        ]
    }
];

const resutl = data.reduce((acc, cur) => {
    const key = cur.status ? "successItems" : "failureItems";

    if (acc[key]) {
        return {
            ...acc,
            [key]: {
                status: cur.status,
                messgae: '',
                orders: [
                    ...acc[key].orders,
                    ...cur.orders
                ]
            }
        }
    } else {
        return {
            ...acc,
            [key]: {
                status: cur.status,
                messgae: '',
                orders: [
                    ...cur.orders
                ]
            }
        }
    }
}, {});
console.log('resutl', resutl);

console.log('resutl', Object.values(resutl));

</code>
Comment: thanks for replying. I should have said I am using php as well. Sorry about that. What code is that you have used?
Comment: I used Javscript here. You can apply the same in php as well. Refer this docs
https://www.php.net/manual/en/function.array-reduce.php. See if you make it or else I will post the answer in php.

creating json file from database


Caveat in interpreting many-one reducibility as "computational difficulty"

Question: I am learning computability theory and recently was exposed to the following definition. For two sets $A, B \subseteq \mathbb N$, we say that $A$ is many-one reducible to $B$ and write $A \leq_m B$ if there exists a total computable function $f$ for which
$$ x \in A \iff f(x) \in B $$
on all $x \in \mathbb N$. The interpretation I was given for this is that $A \leq_m B$ means that computing membership in $A$ is "no harder than" computing membership in $B$. This makes some sense: if we treat total computable functions as being a priori "very easy to compute", then $A \leq_m B$ states that there is a "very easy"  way to turn an indicator function $1_B$ for $B$ into one for $A$: let $1_A = 1_B \circ f$.
However, this interpretation of $\leq_m$ has a serious caveat; namely, that in general a set is not many-one reducible to its complement. For example, take the halting set $K = \{ n : \varphi_n(n) \downarrow \}$, and assume towards contradiction that all sets were many-one reducible to their complements. Then we'd have $\overline K \leq_m K$ (by assumption) and also $K \leq_m K$ (by reflexivity). Since a set $A$ is many-one reducible to $K$ exactly when it is c.e., then we'd know that $K$ and $\overline K$ are both c.e. And since if a set and its complement are both c.e. then that set is computable, we'd have that $K$ is computable, which is not true. Contradiction!
So it's not generally true that $A \leq_m \overline A$. But it is generally true that computing membership in $A$ is "no harder than" computing membership in $\overline A$: simply test for $a \in \overline A$ and negate the result.
My question, then, is this: is there a compelling interpretation for $\leq_m$ (as the flawed one is) without such serious defects? Alternatively, is there a compelling reason why we are interested in the ordering $\leq_m$ which requires our reduction $f$ to act on the input instead of the output? (I recognize the subjectivity of what is "compelling" so I have marked this as a soft question)
Comment: There are plenty of times where positive and negative information do behave differently; for example, it's easy to show that a number is in the halting problem, but it's hard to show that it isn't. $\le_m$ preserves the "sidedness" at work here, which - sometimes - is something we care about. See also **enumeration reducibility**, which blends aspects of $\le_T$ and $\le_m$.
Comment: @NoahSchweber Thanks for the comment! I find it a satisfying response to my question; if you want to turn it into an answer I can mark it as accepted.
Answer: Quoting a comment from @NoahSchweber so I can close this question:

There are plenty of times where positive and negative information do behave differently; for example, it's easy to show that a number is in the halting problem, but it's hard to show that it isn't. $\leq_m$ preserves the "sidedness" at work here, which - sometimes - is something we care about. See also enumeration reducibility, which blends aspects of $\leq_T$ and $\leq_m$. –


Fazer um laço de repetição após realizar funções

Question: Estou com dificuldade neste código, adaptei em duas funções como orientado pelo prof. mas estou com dificuldade na fase final, que pede: utilize for ou while por n vezes (n equivalendo à quantidade de produtos informada). Dentro da estrutura de repetição, devo chamar a função "verificar_produto", permitindo que o usuário consiga cadastrar todos os produtos e verificar se teria ou não limite sobrando para comprá-los.
Alguém poderia me ajudar a estruturar essa fase?
def obter_limite (salario, idade, limite):
  print('Irei fazer uma análise de crédito para você, para isso preciso apenas de alguns de seus dados. \n')

  salario = float(input('Qual seu salário? '))
  ano_nascimento = int(input('Qual seu ano de nascimento? \n'))

  import datetime
  agora = datetime.datetime.now()
  idade = agora.year - int(ano_nascimento)
  print('Sua idade é: ', idade)

  limite = float(salario * idade / 1.000) + 100
  print('\nJá analisei seu crédito! Você poderá gastar na loja: R${:.2f}'.format(limite))

  return limite
limite = obter_limite(salario, idade, limite)

def verificar_produto (limite):
  produto = input('Informe o nome do produto que deseja comprar: ')
  preço = float(input('Informe o valor: '))

  porcentagem = preço*100/limite
  if porcentagem <= 60:
    print('\nLiberado')
  elif porcentagem <= 90:
    print('\nLiberado ao parcelar em até 2 vezes')
  elif porcentagem <= 100:
    print('\nLiberado ao parcelar em 3 ou mais vezes')
  else:
    print('\nBloqueado')
    print('Escolha outro produto com valor inferior ao seu limite de crédito')

  desconto = float(7)
  if preço >= 23 and preço <= idade:
    print('Você ganhou um desconto, o valor do produto ficará: R${:.2f}'.format(preço - 7))

  return limite, preço, desconto
limite, preço, desconto = verificar_produto (limite)

#Quantidade #laço repetição de produto soma valores e verificação do limite
n = int(input('\nQuantos produtos deseja cadastrar? '))
for n (verificar_produto)
  while preço <= limite
print(verificar_produto)

Answer: Para repetir algo n vezes, você pode usar um for juntamente com range:
for _ in range(n):
    # faz algo

range(n) gera uma sequência de números de 0 a n - 1 (o que na prática vai fazer com que o loop itere por n vezes).
A variável _ é uma convenção do Python que indica que não me interessa o valor do número (já que nesse caso não vou usar esse valor, só estou usando o range para executar algo várias vezes).
Outro detalhe é que não faz sentido a função obter_limite receber como parâmetros a idade, o salário e o limite, já que essas informações serão sobrescritas dentro da função. Além disso, verificar_produto está acessando a idade, mas esta variável só existe dentro de obter_limite e não será possível acessá-la fora desta função.
Enfim, pelo que entendi do funcionamento do programa, ficaria assim:
import datetime

def obter_limite():
  print('Irei fazer uma análise de crédito para você, para isso preciso apenas de alguns de seus dados. \n')

  salario = float(input('Qual seu salário? '))
  ano_nascimento = int(input('Qual seu ano de nascimento? \n'))

  agora = datetime.datetime.now()
  idade = agora.year - int(ano_nascimento)
  print('Sua idade é: ', idade)

  limite = float(salario * idade / 1.000) + 100
  print('\nJá analisei seu crédito! Você poderá gastar na loja: R${:.2f}'.format(limite))

  # retorna o limite e a idade, que serão usados depois
  return limite, idade

def verificar_produto(limite, idade):
  produto = input('Informe o nome do produto que deseja comprar: ')
  preço = float(input('Informe o valor: '))

  porcentagem = preço * 100 / limite
  if porcentagem <= 60:
    print('\nLiberado')
  elif porcentagem <= 90:
    print('\nLiberado ao parcelar em até 2 vezes')
  elif porcentagem <= 100:
    print('\nLiberado ao parcelar em 3 ou mais vezes')
  else:
    print('\nBloqueado')
    print('Escolha outro produto com valor inferior ao seu limite de crédito')

  desconto = float(7)
  if preço >= 23 and preço <= idade:
    preço -= 7
    print('Você ganhou um desconto, o valor do produto ficará: R${:.2f}'.format(preço))

  # desconta o preço do limite e retorna o novo limite atualizado
  return limite - preço, preço

limite, idade = obter_limite()

n = int(input('\nQuantos produtos deseja cadastrar? '))
for _ in range(n):
    limite, preço = verificar_produto(limite, idade)

Repare que a função verificar_produto recebe o limite atual e retorna o novo limite atualizado (já descontado do preço do produto que acabou de ser comprado).
Claro que tem outros detalhes para arrumar (se o produto for bloqueado, não deveria pedir para digitar outro produto ou então encerrar? o cálculo da idade não é preciso, pois só leva em conta o ano, etc), mas aí já fugiria um pouco do escopo da pergunta, que era como fazer o loop.
Comment: Ual! Me ajudou na dúvida sobre a estrutura de repetição e ainda esclareceu sobre o detalhe dos parâmetros. Muito obrigada!
Comment: @LetíciaMaciel Se a resposta resolveu o seu problema, vc pode aceitá-la, [**veja aqui**](https://pt.meta.stackoverflow.com/q/1078/112052) como e porque fazê-lo. Não é obrigatório, mas é uma boa prática do site, para indicar a futuros visitantes que aquilo resolveu o problema. Não esqueça que [**vc também pode votar**](/help/privileges/vote-up) na resposta, caso tenha achado  útil.


Reading a two dimensional array

Question: I'm trying to read a two dimensional array (30.7) from a external file in Fortran 90 as
READ(*,*)Fname

OPEN(UNIT=10, FILE=Fname, ACTION="READ")

   DO i=1,30

      READ(10,*)(indices(i,j),j=1,7)
  END DO

Data has some missing values represented as blank. When I read data into array (,*)(indices(i,j)), it assigns 0.00 for missing data. How to over come this problem? Attaching the data below.
337.60,220.40,0.00,0.00,200.42,216.61,261.04
323.00,249.20,65.30,0.00,201.93,210.91,309.98
116.80,474.80,0.00,0.00,203.43,215.76,234.93
72.10,505.90,0.00,0.00,204.93,215.72,233.47
148.30,771.70,0.00,0.00,206.44,217.00,239.05
90.70,287.20,0.00,0.00,207.94,215.43,216.85
337.20,334.50,10.20,0.00,209.45,226.85,306.57
142.50,142.80,0.00,0.00,210.95,240.09,240.31
279.10,289.60,51.80,0.00,212.45,227.75,262.30
273.60,337.70,0.00,0.00,213.96,256.86,223.66
332.40,425.60,0.00,0.00,215.46,238.36,237.63
45.70,299.30,0.00,0.00,216.96,223.92,241.41
49.10,529.40,0.00,0.00,218.47,235.81,282.17
185.30,331.80,38.00,0.00,219.97,235.81,309.29
552.90,454.80,0.00,0.00,221.47,224.60,269.09
176.20,441.60,0.00,0.00,222.98,232.44,293.95
170.00, ,0.00, , , ,327.96
200.00, ,0.00, , , ,291.69
241.20,156.00,0.00,0.00,227.49,235.55,278.66
118.00,383.20,3.20,0.00,228.99,269.28,325.31
62.00,189.70,0.00,0.00,230.50,248.73,266.95
400.20,244.20,0.00,0.00,232.00,239.70,271.27
163.70,826.60,0.00,500.00,233.50,245.06,294.98
250.40,236.60,0.00,0.00,235.01,261.72,288.24
51.30,684.20,0.00,0.00,236.51,245.06,237.37
412.50,128.90,0.00,500.00,238.01,245.16,268.66
452.00, , , , , ,314.68
481.00,155.50,0.00,0.00,241.02,278.72,348.44
162.20,201.90,0.00,500.00,242.52,250.36,255.58
171.80,152.00,0.00,500.00,244.03,246.85,339.06

Comment: Well what do you *want* it to do for the missing data?
Comment: possible duplicate of [Fortran90 Array read blank values as null](http://stackoverflow.com/questions/6730471/fortran90-array-read-blank-values-as-null)
Comment: Based on the number of blanks count is adjusted for example column 2 has 3 missing then coult will be 27 and so on. How can i skip the loop if i find a missing value.
Answer: Before your DO loop, assign a unique value to the indices array, some value that you know won't occur in the data set. Example:
    indices = -99.
    DO J=1,30
        Read(1,*) indices(J,:)
    END DO

The missing values in indices will still have the value -99 after reading the file. You can then count the number of -99s in each column.
Answer: The namelist method can skip non-provided values, but that has a very particular format.   Otherwise if you want to skip non-provided values and have blanks not interpreted as zero you will have to provide your own additional level of processing.  Interpreting blanks as zeros on numerical input is the Fortran way.   I think that you basically have to write your own parser.  Read the lines into a string, then split them into sub-strings via commas (or blanks too?).    If the sub-string is blank leave the value unchanged -- that is what you want?   Otherwise use an "internal" read to read the values from the string into the number.  Not trivial, but you want to do something non-standard.  Look through the string intrinsics provided with Fortran, they will make the processing easier.
Answer: try: open(unit=10, file=... blank=blank)
Don't know if it works, but blank="zero" resets your blank spaces to 0... supose my solution will do the opposite ;)
Comment: Please format your answer to make the code readable.  And please try to post solutions that are more reliable than "probably works".

Reading a two dimensional array


how do you find time signatures which does not match 3 , 4 ,5 , 7 counts,etc ? Or Can some songs have no time signatures ?

Question: how do you find time signatures which does not match 3 , 4 ,5 , 7 counts,etc ?
For example ,
I know that the second song sung here is 6/8 . But what is the time signature of the first one ?

The second one is quite clearly 6/8 .. But I am missing the time signature of the first song ?
Or do some songs have no time signatures ? Is it acceptable ?
Comment: The rhythmic structure of Indian music is often much more complex than the Western idea of "the same small number of beats in every bar". Some Indian rhythmic patterns have more than 100 beats before they repeat. There are also patterns like 14 beats divided into 5+2+3+4. Google for "tala" or "taal".
Comment: Questions about basic analysis of specific pieces are generally disallowed on this site. Try to rephrase the question, or likely it will be closed. Your other question seems to be within the parameters.
Comment: I have edited to be more general to gain knowledge on music theory yet getting insights on analysis of a piece of music .
thanks
Comment: "Can some songs have no time signatures  Is it acceptable ?"  Of course. https://en.wikipedia.org/wiki/Free_time_(music) https://en.wikipedia.org/wiki/Gregorian_chant
Comment: So what is the time signature or tala of the above mentioned song ?
Comment: Check out Colon Nancarrow for irrational time signatures.
Answer: Charles Ives dispenses with time signatures in his Concord Sonata (at least in the "Emerson" movement).  The measure bars merely function as synchronization points; one can plainly see that the "measure" on the lower left stave has substantially more beats on the lower staff than on the upper (look at all those minims!), and also more beats than the subsequent measure.
Answer: Start counting at the first heavy beat, and keep counting till you reach the next heavy beat. It may not be apparent straight away, but when you think you have the magic number, count through the song. If it fits, you've most likely solved it. You may have to try with a slow and a fast count, as some time sigs are compound, like this one It could be a slow 4, or the 4 could be split on each beat to give 3 on each - triplets. In which case, it's 12/8. However, that could still be written as a 4/4 time sig., with a written note at the top of the music, saying crotchet = 3 quavers, usually with the note signs. Sorry, can't do that for you - no doubt someone else will!
Comment: I suggest you try that idea using this recording https://www.youtube.com/watch?v=Joyk_EMtzn0 starting at 2:45 (The fact that the video tells you what the right answer is, and that Ravi Shankar is beating time anyway, probably won't be much help!)
Answer: Part of the intro might indicate that the first part is also 6/8. The tempo is not steady, so it is very difficult to know for sure.  It is performed freely.
Answer: There's another problem which is that many pieces of music change their time signature often.  Just because something starts in, say, 3/4 does not mean that it will stay in 3/4 for long.  Also some pieces of music have different voices or instruments playing in different time signatures at the same time (which gives the conductor a problem).  It's done so that the stresses on beats occur in different places in different parts.
You can't expect to be able to tell just by listening.  For example it's not uncommon to find stretches of music in 6/8 where each bar has two dotted crotchets in it, in other words it will sound exactly the same as 2/4.  But if it's written like that it'd probably be because in a few bars time some of those half bar dotted crotchets will become three quavers or a crotchet and a quaver as the rhythm begins to develop.  It might be clearer what's going on seeing all of that in 6/8, even if you might thing the music should be written first in 2/4 then 6/8.


Problem with views edit link not appearing

Question: I have created a view (block) that has contained in its fields user account information (including content profile fields). Along with that, there is an edit link to edit the profile information. The problem I am experiencing is; when logged in as a regular user, the edit link does not appear. When logged in as user 1 it does appear. I thought this would be a permission issue but I can't see what should be checked. I think I have enabled all the necessary permissions. Aren't users enabled to edit their profiles by default?
Here is a screenshot of the view's settings:

I am using Drupal 6.26 and views 6.2.16 and displaying this view in a panel. Any suggestions as to what I may be missing?
Thanks.
Answer: Found the answer to my problem. I had missed enabling access user profiles permission for authenticated users.


Alter the CSS of the first p tag after each H4 tag

Question: I have a stylesheet which indents paragraphs by 20px, but I do not want an indent on the first paragraph after each H4.
So I have something like this:

Paragraph 1

Paragraph 2

Sub Heading

Paragraph 3

Paragraph 4

Using jquery I want to override the css on Paragraph 3 so there is no text-indent.
I tried this but nothing happened:
$("#myDiv > h4").next("p").css({"text-indent":0});

Answer: You can do this with just CSS:
#myDiv > h4 + p {
    text-indent: 0;
}

That selector means: select p preceded by h4 that is a child of #myDiv.
+ is the adjacent sibling selector.
Or as JavaScript if you prefer:
$('#myDiv > h4 + p').css('text-indent', 0);

Answer: What about this?
Use h4 + p as your selector.
Answer: many ways are there...
$(document).ready(function(){
    $('#myDiv h4').each(function(){
    $(this).next().css({"text-indent":0});
    });
});

Answer: DEMO
$('#myDiv h4').next('p').css({textIndent:0});

Answer: $("#myDiv > h4:first-child")css({"text-indent":0});

http://api.jquery.com/first-child-selector/


select limited rows from large records

Question: I have more than 1000 records from a function call and using take() I got first 10 records as follows,
$users = Users::GetActivatedUsers()->take(10)->get();

so, I want to go through all of records (1000 or above) 10 by 10. I have done following part for it. but it is only going with first 10 records only. so how can I get rest of records 10 by 10
$count = $users->count();

if (!empty($users) && ($count > 0)){

// operation in this function

}

Thank You!
Answer: You can use the chunk function of the Query Builder to give you chunks in the size you would like and you can pass a callback to do what you would like with the returned chunks:
Kit::GetActivatedUsers()->chunk(10, function ($chunk) {
    foreach ($chunk as $user) {
        ...
    }
});

Laravel 8.x Docs - Queries - Chunking Results chunk

select limited rows from large records


Retrieve database structure

Question: Can I retrieve full database structure using its connection string as collection of tables, its columns, relationships, etc?
Can I modify database using these objects?
Edit: Database - MS SQL Server. I need to be able to retrieve and edit database tables, column names, types, etc in code.
Comment: You need to give us a bit more detail.  What kind of database are you using.  How far have you got on your own etc.
Answer: You can try DbConnection.GetSchema() , see here for a little tutorial.

Retrieve database structure