Como limpar a tela no TkInter?

Question: Há uma forma prática de "limpar" uma tela, dando um destroy() em todos os widgets de uma vez, sem ter que fazer isso de um por um?
Comment: Está em um *frame* ou outro *container*? Experimentou destruir ele? Se não tem, porque não criar um para conter todos os *widgets* que deseja destruir juntos? Não sei se você sabe que estes controles destroem todos os filhos quando eles são destruídos.
Comment: De fato deve ser um problema no código. EU acho que isto é a forma mais simples de fazer isto. Erros assim não costumam ser de sintaxe. Você pode colocar todos estes *frames* dentro de outro *frame* que tem como função agrupar tudo o que você quer destruir de uma vez só.
Comment: As `widgets` estão divididas em várias `frames`. Eu tentei destruir as frames para tentar destruir as `widgets` que elas contém junto, mas nada aconteceu(deve ter sido algum problema no código, apesar do `idle` não acusar nenhum erro de sintaxe, vou verificar). Mas mesmo assim, eu ainda teria que destruir as `frames` uma por uma?

EDIT: De fato, foi um probleminha lógico, que já resolvi. Falta de atenção mesmo, rs. Mas deletar frame por frame em programas maiores deve dar um trabalhinho chato.
Comment: Gostei dessa dica, facilita bastante o trabalho, Obrigado.
Answer: A técnica básica é criar um frame para agrupar todos os controles que deseja destruir, já que cada controle tem por função destruir todos os seus filhos. Lembrando que você pode ter frames dentro de frames e eles não precisam ser visíveis. É uma forma de organizar os controles. Aí você só precisa destruí-lo.
Coloquei no GitHub para referência futura.

Como limpar a tela no TkInter?


if is not checking firebase reference to show and hide buttons

Question: I have a question is making only the first if button visible, he is not checking whether or not he has it node casino. I have two accounts shown in the image one with the casino node and the other without. but the button opencasino is showing for both. in debug I can see that you are looking for the current user. but the result of the first "if" is the same for both accounts. can anybody help me. Thanks in advance.

code
 final DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    final String userId = user.getUid();

    ref.child("users").child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {

                if (ref.child("users").child(user.getUid()).equalTo("cassino") != null) {

                    openCassino.setVisibility(View.VISIBLE);
                    buyCassino.setVisibility(View.GONE);

                } if  (ref.child("users").child(user.getUid()).equalTo("cassino") == null ) {
                    buyCassino.setVisibility(View.VISIBLE);
                    openCassino.setVisibility(View.GONE);

                }

            }
        }

same problem using if else
ref.child("users").child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for (DataSnapshot ds : dataSnapshot.getChildren()) {

            if (ref.child("users").child(user.getUid()).equalTo("cassino") != null)  {
                openCassino.setVisibility(View.VISIBLE);
                buyCassino.setVisibility(View.GONE);

            } else   {
                buyCassino.setVisibility(View.VISIBLE);
                openCassino.setVisibility(View.GONE);

            }

        }
    }

DEBUG IMG
Comment: Is your if logic within your for loop evaluating to the correct case? This will help tell if this is an android lifecycle/draw issue or a firebase issue. Also, why if(!null) followed by if(null) why not use an else statement?
Comment: I tried but using "if" "else" the same thing happens. follow the code ...
check my update for a post. thanks for your reply
Comment: That still doesn't tell me if these statements are evaluating correctly or not. Does ref.child("users").child(user.getUid()).equalTo("cassino") return a value here? If so, is this view within like a recycler view or anything like that?
Comment: in case it returns true! = it will display the opencasino button. if false returns the buycassino button. but it is not doing the checking it just checks the first "if" based on that makes the button visible. but without checking the firebase reference.
Comment: being clearer. if the casino node exists, display the opencasino button. if you do not have the casino node display the buycassino button.
Comment: Wait, why are you checking `ref` and not `ds` are you not checking the data you're getting from your listener?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/210340/discussion-between-garrett-manley-and-upz91).
Answer: It looks like you're checking the value from your database reference as opposed the DataSnapshot that your listener is returning in onDataChange()
Something like the below appears to be more what you're looking for, although the for loop itself may not be needed looking at the way your code is written.
for (DataSnapshot ds : dataSnapshot.getChildren()) {
  if (ds.child("cassino").exists())  {
    openCassino.setVisibility(View.VISIBLE);
    buyCassino.setVisibility(View.GONE);
  } else {
    buyCassino.setVisibility(View.VISIBLE);
    openCassino.setVisibility(View.GONE);
  }
}

Additional Notes
You may want to decouple your database logic from your visibility logic; unless of course it's just written this way for simplicity of articulating your issue.
Comment: hello thanks for your reply. I believe that the problem will now be the subject of a new question. thanks for your help.
Comment: hello thanks for your reply. using the account that has the casino node it does not display the opencasino. I did the debug and the uid and the casino node is loaded for the current user but it still shows buycassino that is in the "else". would you know tell me why this is happening?
Comment: Hello, I updated the question with the debug image. thank you for the patience.


Controller banks now mapped to channels and not tracks

Question: I have a Behringer X-Touch Compact hooked up to provide basic transport and level/pan controls to Logic Pro X (currently 10.4.8).
At some point recently (since I last worked on a track about a month ago) I'm finding that, regardless of which project I have opened, the fader banks now seem to be assigned per channel number (an abstract concept I'd never been aware of!) rather than track number. This basically makes it impossible to use, as I'll create tracks and then move them around into logical groups, but now the are non-contiguous, so navigating the banks is completely impractical:
In the screenshot, the drums are on track 12, playing through audio 4, so rather than my current fader bank being a group of adjacent tracks, it's now got a hole in the middle (track 11) since track 10 is audio 1, track 11 is audio 10. It's even worse for some of my other tracks where I've moved things around more.
I am certain this isn't the behaviour I used to have, but I have no idea what's changed - I can't find any relevant setting in the control surface settings.
The problem doesn't appear on my laptop running 10.5 (which I barely use) but I'm wary of upgrading my main machine to 10.5 in the middle of working on a project, so I'd like to get a sense of the root cause before trying that, if possible.
Comment: Breaking controls into channels sounds like it could be trying to do MPE, which is a workaround in MIDI where you send channel-wide messages (like pitch and aftertouch) on separate channels so you can have separate messages for each note. Try to see if the controller or Logic has an MPE function somewhere and turn it off.
Comment: @ToddWilcox thanks, though I don't think this is relevant - the channels being discussed here are Logic's audio channels (all the tracks in question are audio channels, not midi ones). All the midi data in this setup is coming through a single midi channel from the controller.
Answer: Finally figured this out. The setting in question is "Channel Strip View Mode" in Control Surfaces -> "Setup". It was set to "all" which caused it to assign strips to channels. Changing it to "Tracks" restored the behaviour I was expecting.


What is this piece of archery equipment for?

Question: An inexpensive (Barnett Sportflight) archery set I bought includes this little piece, about 1.5 inches long.  Can anybody tell me what it is for?
Answer: Without seeing all the parts for context, I'd say it looks like a budget sight. The trapezium cutout will attach somewhere on the front of the riser and slide up and down (to adjust vertical aim), and the screw part will move the sight left and right (to adjust horizontal aim).
To sight, line up the ball over the centre of the target. Shoot some arrows. If they're higher than centre, move the sight up; if they're low, move sight down. If they're right of centre, move sight right; if they're left, move sight left. If they're all over, keep practicing until you can consistently group 3 arrows together :-)


Proving a continuous function is constant

Question: For a closed interval $I=[a,b]$, consider the $C^1$-functions that are $0$ at the endpoints, denoted $C^1_0(I)=\{f\in C^1(I)\,|\,f(a)=f(b)=0\}$. Let $g\in C^0(I)$, but not necessarily differentiable. Suppose
\begin{equation}
\int_a^b gf'\text{dx}=0\,\quad \forall f \in C^1_0(I)\,.
\end{equation}
I am asked to prove that $g$ is constant on $I$. Obviously, I can not use integration by parts as $g$ is not differentiable. I thought about construction of a test function in a smart way, but I have trouble creating test-functions that are continous, satisfying the boundary conditions. Any hints?
Comment: Use elements of $C_0^1(I)$ to approximate indicator functions of subintervals of $[a,b]$.
Answer: If $g$ is not constant, there are $s,t\in (a,b)$ with $s<t$ such that $g(s)\neq g(t)$. Let $f\in C^1_0(I)$ be such that it rises to $1$ in a small interval around $s$, and in a completely symmetrical way sinks down to $0$ in a small interval around $t$. Otherwise $f$ is constant.
Use continuity of $g$ to show that if the two intervals are narrow enough, there is no way we can have $\int_a^b gf'\, dx=0$.
Answer: Apply your property to the $\mathcal{C}^1_0(I)$ function
$$f : t \mapsto \int_a^t g(x) \mathrm{dx} - \frac{t-a}{b-a} \int_a^b g(x) \mathrm{dx}$$
You get that
$$\int_a^b g^2(x) \mathrm{dx} = \frac{1}{b-a} \left(\int_a^b g(x) \mathrm{dx}\right)^2$$
The equality case of Cauchy-Schwarz implies that $g$ must be constant.
Comment: +1. Very neat proof!
Answer: Here is a proof which is very similar to the answer given by TheSilverDoe, but it might provide more insight:

Which functions can be written as $f'$, $f \in C_0^1(I)$? These are exactly the functions with zero mean, $M :=  \{f \in C(I) | \int_I f \, \mathrm{d} x = 0\}$.
Thus,
$$\int_I g \, f \, \mathrm{d}x = 0 \qquad\forall f \in M.$$

For every $C \in \mathbb{R}$, we have $\int_I C \, f \, \mathrm dx = 0$ for all $f \in M$, thus,
$$\int_I (g - C) \, f \, \mathrm{d}x = 0 \qquad\forall f \in M.$$

We can pick $C \in \mathbb R$ such that $g - C \in M$. Using $f = g - C$ yields
$$ \int_I (g-C)^2 \, \mathrm dx = 0$$
and therefore $g = C$.


Rails: How to receive errors from nested models

Question: I am trying to validate emails given from a CSV list of emails. So I have created the invite_list virtual attribute where when given a list of emails, it will loop and create a new record in the invited_only_emails model.
Now the thing is, this works fine, but how can I catch the validation error thrown by InvitedOnlyEmail while looping in Users model so I'll be able to use that error in the controller?
This is my main model:
class Users < ActiveRecord::Base
attr_accessor :invite_list
attr_accessible :invite_list

has_many :invited_only_emails

  def invite_list=(list)
    list.split(",").each do |address|
        self.invited_only_emails.create! :email => address
      end
  end

  def invite_list
    self.invited_only_emails.map {|email| email.email}.join(',')
  end
end

And this is the invited_only_emails model:
class InvitedOnlyEmail < ActiveRecord::Base
  attr_accessible :email
  belongs_to :users

  validates_format_of :email, :with => /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i

end

Thanks!
Answer: I think you could use validates_associated method:
class User < ActiveRecord::Base
  validates_associated :invited_only_emails
  # ...
end

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_associated
Answer: Have you looked at validates_associated?
http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_associated


What does k mean in AIC expression?

Question: I'm using the AIC() function in R, where the argument k (default to 2) stands for the number of parameters. I'm not sure to understand well what does it mean.
How can you know k?
For example, in the case of $y=ax^2+bx+c$, does k equal 3?
As a sidenote, I saw that there is a function named sic() which comes with the metomet package. However, I can't install this package as it doesn't seem to be available for latest release of R (version 2.13.0). Do you know where it can be found?
Comment: It seems that you asking 2 different questions, one about AIC, another about installing certain R package. Please ask 2 different questions.
Comment: Package metomet is not in the list of available, archived or orphaned packages. Rseek.org also gives nothing, so the question is why are you certain that such package exists at all?
Comment: Maybe this one? http://forums.cirad.fr/logiciel-R/viewtopic.php?t=2688&sid=bbd0e8ff814c3f00ec8458befa65c6db
Answer: k in AIC is a multiplier for the penalty term for complexity. The usual AIC, as developed by Akaike, used k = 2, so that is the default. In the BIC or SBC, k = log(n), where n is the number of observations. Either of these (or other similar measures) follow a formula
-2 loglikelihood + k*p
where p is the number of parameters. The penalty term for complexity is to make up for the fact that more complex models fit better, even if the added terms aren't very useful.
Comment: So k doesn't have to be an integer?
Comment: Nope, apparently not.

What does k mean in AIC expression?


properties of Sym^2 vector subspace/properties of tensor products

Question: I have a problem:
Let $V$ be an $n$-dimensional complex vector space and let $B=\{e_1,e_2,...,e_n\}$ denote the elements of a chosen basis. Let $\rho:G \to GL(V)$ be an irreducible representation. Let $T:V \otimes V \to V \otimes V$ be the automorphism defined by $T(e_i \otimes e_j)=e_j \otimes e_i$. Let $Sym^2(V)=\{z \in V \otimes V: T(z) = z\}$ and $Alt^2(V)=\{z \in V \otimes V : T(z) = -z\}$.
Prove that $Sym^2(V)$ is a vector subspace of $V \otimes V$ of dimension $\frac{n(n+1)}{2}$. I  have no idea how to prove the latter part (dim is $\frac{n(n+1)}{2}$). I know that in general, the dimension of a vector space is the number of basis vectors. So, in this case, the dimension is the number of basis vectors of $Sym^2(V)$. I have the following hint: $e_1 \otimes e_2 + e_2 \otimes e_1 \in Sym^2(V)$. I'm not asking for a handout, but can anyone point me in a direction/give me a tool that I can use to get this done? Thanks in advance.
Comment: The elements $s_{ij} := e_i \otimes e_j + e_j \otimes e_i$, $t_i := e_i \otimes e_i$, and $u_{ij} := e_i \otimes e_j - e_j \otimes e_i$ together form a basis of $V \otimes V$. We have $s_i, t_i \in {\rm Sym}^2(V)$, and $u_i \in {\rm Alt}^2(V)$. Use this and the fact that  ${\rm Sym}^2(V) \cap {\rm Alt}^2(V) = \{0\}$.
Answer: The idea is to decompose $V \otimes V$ as a sum of eigenspaces of $T$.  Since $T^2$ is the identity map, the only possible eigenvalues of $T$ are $\pm 1$.  The $+1$ eigenspace is precisely $Sym^2(V)$ and the $-1$ eigenspace is precisely $Alt^2(V)$.  The elements described in Derek's comment above give bases of these two eigenspaces.  Once you check that there are exactly $n^2$ of these elements (and they are linearly independent), you know that they give bases (since the dimension of $V \otimes V$ is $n^2$).  Then one simply has to count basis elements to get the dimension you're interested in.


SKShapeNode fillcolor comparison

Question: I'm working on a little game where I have to match some colours. I'm working only with SKShapeNodes; but I cannot seem to get this code to work. I'm only getting the "Different color" print.
<code>    func didBegin(_ contact: SKPhysicsContact) {
    let firstBody = contact.bodyA
    let secondBody = contact.bodyB

    if firstBody.categoryBitMask == PhysicsCategory.colorNode && secondBody.categoryBitMask == PhysicsCategory.colorBox || firstBody.categoryBitMask == PhysicsCategory.colorBox && secondBody.categoryBitMask == PhysicsCategory.colorNode {

        let firstNode = contact.bodyA.node as? SKShapeNode
        let secondNode = contact.bodyB.node as? SKShapeNode

        if firstNode?.fillColor == secondNode?.fillColor {
            /* TODO: Update score label */
            print("Same Color")
            point = +1
        }
        else {
            print("Differnet color!")
            /* TODO: Game over */
        }
    }
}
</code>
Any help appreciated :-)
Answer: I found the solution. One of the SKShapeNodes was made into a child of a SKNode containing the PhysicsBody.
Code works perfectly now.

SKShapeNode fillcolor comparison


Track down a memory leak on a wordpress site

Question: I'm running an AWS marketplace bitnami image for wordpress. The site has been running for a few months and recently started crashing. Something's leaking memory and I can't find out what it is.
I've updated php-fpm settings
pm = ondemand
pm.max_children = 20
pm.process_idle_timeout = 10s
pm.max_requests = 500

And I've drop max_memory in php.in to 64M
But I can still see the memory slowly disappearing.
bitnami@ip-172-31-7-85:/opt/bitnami/php/etc$ free -m
             total       used       free     shared    buffers     cached
Mem:          2000       1236        764         75         94        489
-/+ buffers/cache:        652       1348

The httpd and php-fpm processes just take more and more memory till the site falls over.
bitnami@ip-172-31-7-85:/opt/bitnami/apache2/logs$ ps aux --sort -rss
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
mysql     1478  0.6 11.0 1392736 227120 ?      Sl   19:35   0:24 /opt/bitnami/mysql/bin/mysqld.bin --defaults-file=/opt/bitnami/mysql/my.cnf --basedir=/opt/bitnami/mysql --datadir=/opt/bitnami/m
daemon    3841  1.1  3.0 1305952 62988 ?       Sl   20:36   0:01 /opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf -DDISABLE_BANNER
daemon    4045  4.3  2.5 286040 51928 ?        S    20:36   0:06 php-fpm: pool wordpress
daemon    3843  0.7  2.4 1305496 50564 ?       Sl   20:36   0:01 /opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf -DDISABLE_BANNER
daemon    4047  3.5  2.4 286012 50356 ?        S    20:36   0:05 php-fpm: pool wordpress
daemon    3842  0.8  2.4 1305892 50020 ?       Sl   20:36   0:01 /opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf -DDISABLE_BANNER
daemon    4048  0.6  2.3 1297712 48532 ?       Sl   20:36   0:01 /opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf -DDISABLE_BANNER
daemon    4118  3.0  2.1 285992 44916 ?        R    20:36   0:04 php-fpm: pool wordpress
daemon    4116  3.9  2.1 286000 44856 ?        S    20:36   0:06 php-fpm: pool wordpress
daemon    4115  1.4  1.6 273832 34420 ?        S    20:36   0:02 php-fpm: pool wordpress
root      3831  0.0  1.1 206004 23300 ?        Ss   20:36   0:00 /opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf -DDISABLE_BANNER
root      3793  0.0  0.3 267808  7836 ?        Rs   20:35   0:00 php-fpm: master process (/opt/bitnami/php/etc/php-fpm.conf)

The sites under very low load. But it's only taking 10 mins before it crashes.
I'm getting the following in my error_log
[Thu Mar 09 18:43:49.420787 2017] [pagespeed:warn] [pid 1549:tid 140430532409088] [mod_pagespeed 126.96.36.199-0 @1549] Fetch timed out: http://ourdomaincom/wp-content/uploads/2015/01/ourdomain_page_3.jpg-200x200.jpg (connecting to:172.31.7.85) (1) waiting for 50 ms
[Thu Mar 09 18:43:49.583085 2017] [pagespeed:warn] [pid 2201:tid 140430112970496] [mod_pagespeed 188.8.131.52-0 @2201] Fetch timed out: http://ourdomain.com/wp-content/plugins/LayerSlider/static/js/layerslider.transitions.js?ver=5.6.9 (connecting to:172.31.7.85) (1) waiting for 50 ms
[Thu Mar 09 18:43:49.584180 2017] [pagespeed:warn] [pid 1548:tid 140430381405952] [mod_pagespeed 18.104.22.168-0 @1548] Fetch timed out: http://ourdomain.com/wp-content/themes/thefox/js/custom_woo_js.js?ver=4.6.1 (connecting to:172.31.7.85) (1) waiting for 50 ms

How can I fix this or track down the memory leak?
Comment: Those errors are generated by Pagespeed, you could try turning that off. Why would fetching static resources time out? Is it sending requests for static content to PHP? You haven't included configuration so we can't check. You could use dynamic PHP, or configure PHP to restart the worker process after X invocations (pm.max_requests). You could switch from Apache to Nginx, Nginx is very lean, takes 15MB RAM (plus 175 virtual) on my server.
Comment: Thanks @Tim - That's helpful. I'll try turning off mod_pagespeed. Also I'll look at config - it does seem that php is trying to serve static content.
Comment: It is very unlikely to be a memory leak - far more likely that the system is just overloaded - mod_pagespeed and wordpress on a box with with 2Gb of memory? You should also be checking the nfconntrack limits.
Answer: Turns out the site had been hacked.
I migrated it into the hands of the fine folks at WPEngine. They've been amazing, identifying the problem, and sorting it quickly.
It's not been a good introduction to wordpress. Kind of hope I never have to look after another wp installation :(
Comment: wordpress: a remote code execution API that comes with  blogging functionality as a free extra.


What is the maximum amount of eigenvectors that a square matrix n x n might have?

Question: having the following arbitrary matrix:
$A=\begin{pmatrix}
a_{1,1} & \cdots & a_{1,n}\\
\vdots & \ddots & \vdots \\
a_{n,1} & \cdots & a_{n,n}
\end{pmatrix}$
What is the maximum amount of (linearly independent) eigenvectors and eigenvalues of $A$ ? How to calculate the actual number of eigenvectors and eigenvalues of $A$?
thanks!
Comment: Notice that is $v$ is an eigenvector then so are $2v$ and $-17v$ and $\pi v$ and so on. So rather than ask for the number of eigenvectors the sensible question asks for the number of *linearly independent* eigenvectors.
Comment: I suggest you start by [this wiki article](http://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors).
Answer: Think about $A=I$, how many (linearly independent) eigenvectors does $A$ have?
With regards to computing the eigenvectors/eigenvalues of a general $A$ you have to find pairs $(\lambda,v)$ such that
$$Av=\lambda v.\quad\quad (*)$$
One way to go around this is first compute the possible $\lambda$s by solving for the roots of
$$\det(A-I\lambda).$$
Then compute the corresponding $v$s by solving the linear equations defined by $(*)$.
For more info, I'd recommend you have a look at these camcasts.


Fixar URL dos SRC pelo HTACCESS

Question: Eu estou usando URL amigavel via HTACCESS e porque estou usando isso as páginas perder o styles e js. Por causa que o caminho (URL) é feito como ex /categoria/pizza então ele procura src="categoria/pizza/style.css" . Teria alguma forma de fixar a URL base pelo HTACCESS?
Comment: Aguardamos um retorno sobre as respostas já dadas
Answer: Neste caso o ideal é você especificar o caminho dos arquivos para a) URL completa ou b) caminho relativo (ex: "/style.css" ou "/css/style.css"). Este problema nào está relacionado com o htaccess
Comment: Não teria alguma forma de indicar a URL pelo HTACCESS?
Comment: Se você possui um número limitado de arquivos, seria possível, no entanto você perde flexibilidade com isso. A forma recomendada é realizar o ajuste para buscar o arquivo no caminho correto.
Answer: Uma alternativa é definir a tag <base> no cabeçalho das páginas HTML.
http://www.w3schools.com/tags/tag_base.asp
Também defina no httaccess a exceção de regra de reescrita para quando encontrar uma pasta ou arquivo, tal com a base onde a regra será aplicada.
RewriteBase /
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d

Answer: Minha recomendação é você especificar sempre o caminho absoluto do arquivo, já que o PHP interpreta com base no caminho do servidor e os src e href em relação ao caminho do navegador... nesses casos você teria que criar uma variável ou uma constante para resolver essa diferença
$UrlSite = explode(DIRECTORY_SEPARATOR,trim(parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH), '/\\'));
$DirSite = explode(DIRECTORY_SEPARATOR,__DIR__);
if(in_array($UrlSite[0], $DirSite) AND $UrlSite[0] != ''){
   $Directory = "/$UrlSite[0]/";
   //é atribuido ao smarty {$Directory} no arquivo de configuração do smarty
}else{
   $Directory = "/";
}

Na variável acima eu comparo o caminho do servidor com o caminho do navegador, se a pasta fora a mesma nos 2, ele grava na variável... então nos src e href coloco a variável sempre na frente do caminho absoluto. Ex:

Sendo que aqui a pasta imagens está na raiz do meu projeto
Agora algo que considero muito importante, por que não usar a tag <base>?
Simples, pois ela não tem compatibilidade com navegadores antigos, IE9 ou anteriores continuarão sem encontrar seus arquivos ou seja, você teria de deixar de dar suporte para essas versões...
Meu htaccess está da seguinte forma
<IfModule mod_rewrite.c>
   RewriteEngine On
   Options -Indexes
   ErrorDocument 404 /Errors/404.html
   ErrorDocument 403 /Errors/403.html
   RewriteRule ^/?$ page/php/Home.php
</IfModule>

A principio essa foi a melhor solução que encontrei, pelo menos foi a unica compatível com todas as necessidades e com todos os navegadores... não encontrei nenhuma forma de fazer isso diretamente pelo .htaccess

Fixar URL dos SRC pelo HTACCESS


How to synchronize MyViewController code to Java in Android Studio using Intel's Multi-OS Engine

Question: I am following
this tutorial provided by intel. At step 13, the instructions say:

Go back to Android Studio and right click on the QuizApp project, click Multi-OS Engine Actions and choose Synchronize to Java.

I am unable to find such menu. Instead here is a screenshot of the menu that I see. Essentially I am trying to link the UI I created in Xcode with the java code counterpart in my common module.
I am currently running android studio version 3.0.1 with multi-os engine plugin version 1.4.1 and OS X 10.11.6
Answer: I had the same problem.
You have to create a binding instead.
Context Menu - create binding
This will generate a .nbc file, where you can add the header files of your native code.
binding.nbc
Do not forget the import statement in the "Import headers" section.
After you added all your bindings you can generate the Java classes.
Generate Bindings
Maybe this link can help you as well.
https://discuss.multi-os-engine.org/t/no-synchronize-to-java-menuepoint/1440


Alter entity reference autocomplete field

Question: I have made a module to alter the way entity reference works with autcomplete fields. I have override the entity_reference_autcomplete function where i have changed the following line:
<code>        $key = "$label ($entity_id)";
</code>
with
<code>        $key = "$label";
</code>
It seems to work when completing fields in form , but after the form has been submitted the autcomomplete field gets blank and the result is not saved . How can i solve this issue ?
Comment: You will also need to use a modified submit function. probably the default one tries to get $entity_id from the input using some regex or something
Comment: @AyeshK can you give more details ?
Answer: This should be done by writing a custom CTools EntityReference selection plugin.  Your new class would just extend EntityReference_SelectionHandler_Generic_node and I think it would only need to override the getLabel() method to make things "just work".


Problems with rsGetElementAt_uchar4

Question: I'm trying to implement a median filter in RenderScript. But the work of the code is not stable. Reading elements not from the current line rsGetElementAt_uchar4 (inputAlloc, x , y + a ) causes errors. What is the problem ? Is there an example of such a filter using RenderScript?
<code>    #pragma version(1)
#pragma rs java_package_name(a.myapplication)
#pragma rs_fp_relaxed

rs_allocation inputAlloc;
int bWidht, bHeight;

static uchar4 arrpix[9];
static uchar4 buff;

uchar4 __attribute__((kernel)) median(uchar4 in, uint32_t x, uint32_t y)
{

uchar4 arrpix[9];
uchar4 buff;

                      if((x<bWidht) && (y<bHeight)){
        arrpix[0] = rsGetElementAt_uchar4(inputAlloc, x -1 , y - 1);
        arrpix[1] = rsGetElementAt_uchar4(inputAlloc, x    , y - 1);
        arrpix[2] = rsGetElementAt_uchar4(inputAlloc, x +1 , y - 1);

        arrpix[3] = rsGetElementAt_uchar4(inputAlloc, x -1 , y    );
        arrpix[4] = in;
        arrpix[5] = rsGetElementAt_uchar4(inputAlloc, x +1 , y    );

        arrpix[6] = rsGetElementAt_uchar4(inputAlloc, x -1 , y + 1);
        arrpix[7] = rsGetElementAt_uchar4(inputAlloc, x    , y + 1);
        arrpix[8] = rsGetElementAt_uchar4(inputAlloc, x +1 , y + 1);

for(int i=0; i<4; i++)

for(int i=0; i<=8; i++){

if(arrpix[i].r>arrpix[i+1].r){
buff.r = arrpix[i].r; arrpix[i].r = arrpix[i+1].r;
arrpix[i+1].r = buff.r;}

if(arrpix[i].g>arrpix[i+1].g){
buff.g = arrpix[i].g; arrpix[i].g = arrpix[i+1].g;
arrpix[i+1].g = buff.g;}

if(arrpix[i].b>arrpix[i+1].b){
buff.b = arrpix[i].b; arrpix[i].b = arrpix[i+1].b;
arrpix[i+1].b = buff.b;}

}
}
    return arrpix[4];
}
</code>
Answer: You need to check x>0 and y>0 because 0-1 =-1
Bottom loops don't look completely correct either. Can you fix the spacing and did you mean to use i in both loops?

Problems with rsGetElementAt_uchar4


How to put a Kendo control into a Kendo template?

Question: I'm trying to put a NumericTextBox into a Kendo template.
Here is the code:

Which is strangely rendered into  this:

I cannot understand from where comes </script> tag...
I'm loading a template into a modal window by using this code:
        editAktionsgruppen.kendoWindow = $("
").kendoWindow({
            title: "Bestätigen",
            resizable: false,
            visable: false,
            modal: true
        }).html($("#clone-wizard-template").html()).data("kendoWindow");

Isn't this a correct way to input a control in the template?
Comment: What is the template being loaded into? a grid? a pop-up window? I'd add html into the template and then initialize it with jQuery when the template is loaded...
Comment: @Neil, oh, yes, I missed this info! I'm loading it into a modal window. I added more details into the question.
Answer: I would probably write it like this:
var popUpWindow = $("
").kendoWindow({
    title: "Bestätigen",
    resizable: false,
    content: {
       template: kendo.toString($('#clone-wizard-template').html())
    },
    visable: false,
    modal: true
});

//add kendo validation to popup window
$('#my-form').kendoValidator();

//initialise the numeric textbox (you could specify a class on the input and find
//by that instead instead of using an id)
$('#NumInput').kendoNumericTextBox();

//wire-up an ok/submit button
$(popUpWindow).find('.t-button').on('click', function() {
 var validator = $('#my-form').data('kendoValidator');

   if(valiator.validate())
   {
    // do stuff
   }
});

//show the window
$(popUpWindow).data('kendoWindow').center().open();

then the client template:


assigning css into a class in a twig form

Question: I am beginner dev. in symfony 2 and twig and I would like to add a bootstrap combobox https://github.com/danielfarrell/bootstrap-combobox/ that I have found on the net.
I want to add this combobox on my twig template. However as it is written here:
<code><select class="combobox">
  <option></option>
  <option value="PA">Pennsylvania</option>
  <option value="CT">Connecticut</option>
  <option value="NY">New York</option>
  <option value="MD">Maryland</option>
  <option value="VA">Virginia</option>
</select>
</code>
it is used basic values from css ...but what I want to do,listing:
<code> {{ form_row(form.city) }}
</code>
this in combobox...
as further example it is written:http://symfony.com/doc/current/cookbook/form/form_customization.html#method-2-inside-a-separate-template
A clear help would be appreciated!
Answer: <code>{{ form_row(form.city, {'attr': {'class': 'class-name'}}) }}
</code>
or
<code>{{ form_widget(form.city, {'attr': {'class': 'class-name'}}) }}
</code>


What is the difference between normal distribution and standard normal distribution?

Question: Two terms normal distribution and standard normal distribution are used in statistics. Does standard term contribute to the normal distribution anything? Please give a simple-however a substantive reasoning in the back of these terms.
Comment: Standard normal distribution stands for the case $\mu=0$, $\sigma=1$. Please, have a look at the [wikipedia entry](http://en.wikipedia.org/wiki/Normal_distribution).
Comment: Of course; a normal distribution with a mean of zero and a unit SD is just one particular kind of normal distribution: the **standard normal distribution**, as the previous comment stated.
Comment: Is it possible to think of normal distribution without zero,1. For example, N(mu,variance)
Comment: What do you mean with 'substantive reasoning'?
Answer: A normal distribution is determined by two parameters the mean and the variance. Often in statistics we refer to an arbitrary normal distribution as we would in the case where we are collecting data from a normal distribution in order to estimate these parameters. Now the standard normal distribution is a specific distribution with mean $0$ and variance $1$.  This is the distribution that is used to construct tables of the normal distribution.
Conveniently if $X$ has the a normal distribution with mean $m$ and variance $s^2$ then if we define
$$Z=\frac{X-m}{s}$$    then $Z$ has the standard normal distribution.  So for any specific normal distribution we can calculate probabilities of the form $P[a < X < b]$ from the tables for $Z$.  This is because we can write $X=sZ+m$.  So the standard normal plays a special role with respect to the general family of normal distributions.
Comment: @subhashdavar, maybe you could be more specific in your question; what are your thoughts exactly? What part confuses you? I think Michael's answer and Procastinator's comment are pretty clear.
Comment: @ Michael Chernik This is a statistical way to explain. Assume that I have a small understanding of the discipline.
Comment: @subhashdavar  My answer is not very heavy on statistics.  Maybe the math formulas cause you some confusion.  Let me try again.  When we say that a variable has a nromal distribution we are talking about a family of distributions.  The standard normal distribution is a specific one with mean 0 and variance 1.  So you can compute a table of values for the standard normal.  Another normal distribution has mean 1 and variance 4.  If you take a variable with a normal distribution with mean 1 and variance 4 subtract 1 and divide by 2 and you have a variable that is a standard normal.
Comment: @subhashc.davar what do you mean by a "scale-free" variable?  If it has all three characteristics of: normally distributed, a mean of zero, and a variance of one - then it has a standard normal distribution.
Comment: By subtracting the mean and dividing by the standard deviation you transform one normally distributed variable to a standard normal and in that way you can determine probabilities for any normal distribution based on the standard normal tables.
Comment: @ Michael Thanks for the statistical interpretation of the distributions. If I have a scale-free variable, do various observations represent Z quantities and we may say it has a standard normal distribution.
Comment: generally, real world data is not distributed normally. There  is dispersion, skewness etc. In order to make a conclusion, we use say dispersion for a general conclustion about say mean estimate.Normality assumption enables us to do analysis in terms of probabilities of say mean effect size. Linking z estimates to probabilities  enables estimates of effect-sizes and so on. Assumption of Standard Normal Distribution is helpful in Linear problems. Recently, Null Reference Distribution has been postulated to cope with  complex problems and hypotheses.


Question about "Quotient Group of Cyclic Group is Cyclic"

Question: I found a proof of the fact that

if $G$ is a cyclic group and $H$ is a subgroup of $G$, then $G/H$ is a cyclic subgroup.

They don't mention that $H$ is a normal subgroup. But to define the quotient group, doesn't $H$ have to be normal?
https://proofwiki.org/wiki/Quotient_Group_of_Cyclic_Group
Comment: Yes, but a cyclic group is always commutative, so each subgroup of it is always normal.
Comment: This is not a detail, but some important insight for a beginner in abstract algebra. It is the start to understand, what a normal subgroup really is.
Comment: Thanks, I had forgotten that detail.
Answer: Cyclic groups are abelian. Let $h\in H$, $g\in G$ for $H\le G$, abelian $G$. Then $$ghg^{-1}=gg^{-1}h=h\in H.$$ Thus $H\unlhd G$.


Exceção na validação Request do Laravel

Question: Tenho uma Request que faz a validação dos dados. Uma das validações é o unique para restringir a repetição dos itens. Porém, os itens são cadastrados em categorias. Preciso que quando o item for de outra categoria, ele deixe fazer o cadastro.
public function rules()
{
    return [
        'preco'         => 'required',
        'categoria'     => 'required',
        'insumo'        => 'required|min:3|max:100|unique:insumos,insumo,'.$this->id,
    ];
}

'insumo' esse é o valor que preciso liberar a duplicação, caso a categoria que esteja recebendo no formulário seja diferente da que já está cadastrada no banco.
por exemplo:
Id - Insumo - Categoria - Preço
1  - Tomate -    5      - 1.00

se cadastrar outro "Tomate", mas a categoria for outro valor, ele deixe cadastrar.
Alguém consegue imaginar uma forma de fazer isso ?
Ficando assim no banco de dados:
Id - Insumo - Categoria - Preço
1  - Tomate -    5      - 1.00
2  - Tomate -    7      - 1.50

Answer: Crie uma validação personalizada com a linha de comando:

php artisan make:rule CategoryInputUnique

gerando na pasta app\rules uma classe CategoryInputUnique, dentro possui um método com a seguinte assinatura passes($attribute, $value) onde deve escrever um código para busca no banco de dados se há repetição desse nome com esse número de categoria (vale lembrar que é bom criar um índice nesses dois campos pelo banco de dados), exemplo:
<?php namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;

class CategoryInputUnique implements Rule
{
    public function __construct()
    {
        //
    }

    public function passes($attribute, $value)
    {
        $categoria = request('categoria', 0);
        $id = (int)request('id', 0);
        $result = DB::table('insumos')
            ->where('insumo', '=', $value)
            ->where('categoria', '=', $categoria);
        if ($id === 0) {
            return $result->count() === 0;
        }
        $model = $result->first();
        if ($model) {
            return (int)$model->id === $id;
        }
        return true;
    }

    public function message()
    {
        return 'The validation error message.';
    }
}

nesse código vai verificar se há repetição, onde foi informado de forma aleatória nome da tabela (coloque o nome real da sua tabela) e os dois campos categoria e insumo (coloque aqui também de acordo com a sua tabela) e vai contar se há registros com essas duas informações.
Para utilizar é só declarar no array de validação a sua instância:
public function rules()
{
    return [
        'preco' => 'required',
        'categoria' => 'required',
        'insumo' => ['required',
                     'min:3',
                     'max:100',
                     function ($attribute, $value, $fail) {
                        $categoria = request('categoria', 0);
                        $id = (int)request('id', 0);
                        $result = DB::table('insumos')
                            ->where('insumo', '=', $value)
                            ->where('categoria', '=', $categoria);
                        if ($id === 0) {
                            if (!($result->count() === 0)){
                                $fail($attribute.' is invalid.');
                            }
                        }
                        $model = $result->first();
                        if ($model) {
                            if (!((int)$model->id === $id)) {
                                $fail($attribute.' is invalid.');
                            }
                        }
                        return true;
                     }
        ],
    ];
}

Pode utilizar o método facade para criar uma extensão dentro da classe AppServiceProvider:
public function boot()
{
    Validator::extend('categoriainputunique', function (
             $attribute,
             $value,
             $parameters,
             $validator
    ) {
        $categoria = request('categoria', 0);
        $id = (int)request('id', 0);
        $result = DB::table('insumos')
            ->where('insumo', '=', $value)
            ->where('categoria', '=', $categoria);
        if ($id === 0) {
            return $result->count() === 0;
        }
        $model = $result->first();
        if ($model) {
            return (int)$model->id === $id;
        }
        return true;
    });
}

e na validação chame somente pelo nome da extensão:
public function rules()
{
    return [
        'preco' => 'required',
        'categoria' => 'required',
        'insumo' => ['required', 'min:3','max:100', 'categoriainputunique'],
    ];
}

Referencias

Custom Validation Rules
Custom Validation Rules - Using Rule Objects
Custom Validation Rules - Using Closures
Custom Validation Rules - Using Extensions
Comment: funcionando 100% vlw Mestre! você é um monstro!

Exceção na validação Request do Laravel


Custom story-node-form.tpl.php not working

Question: I have created a custom node add form for story content type. Though this appears as expected but do not working. Problem is when i click on the Submit button then this form just redirect me again in node/add/story path instead creating the story page!Here is what i have did (Here i have used bartik theme):

template.php

    function bartik_theme() {
    return array(
    'story_node_form' => array(
    'arguments' => array('form' => NULL),
    'template' => 'story-node-form',
    'render element' => 'form',
    ),
    );

story-node-form.tpl.php

<?php print drupal_render($form['title']); ?>

<?php print drupal_render($form['body']); ?>

<?php print drupal_render($form['actions']); ?>

<?php print drupal_render($form['additional_settings']); ?>

<?php print drupal_render($form['actions']); ?>

Now if i click on the Submit button then this story creating form just redirect me again in node/add/story path instead creating the story page! What i am missing here? Thanks
Comment: You really shouldn't be doing stuff like that in the theme layer. You want to create a custom form use the form api inside of a custom module or modify the existing form using hook_form_alter also in a custom module not the theme. https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7
Comment: It's recommended to do this in the theme layer, actually. You're just missing the hidden input fields like the form CSRF token, the form's ID, etc. Try adding `` in your tpl.
Answer: I have solved this by doing <?php print kpr($form); ?> and put all the hidden input fields in the form like token, form_id etc that worked!


Token replacement pattern for triggered rules on node creation

Question: I am currently using triggered rules to send notifications whenever a certain node type is created (by anonymous, unauthenticated users). In the email notification sent I would like to include some of the content submitted in the form but I cannot find any of the replacements tokens when editing the ruleset for the event.
Right now, the token replacement patters for Form and for Form State are listed as empty.
How can I get hold of the relevant replacement tokens for the Form content?
Is there any modules that are capable of sending similar notifications (with node/Form content) upon node creation?
I am using Drupal 6.20, Rules 6.x-1.4, Token 6.x-1.15, CCK 6x.2.9
Answer: This should be possible with the the above modules.
You do not need to get data from the form/form_state.
I'm assuming the data you want is from a cck field because you're sending the email when a new node is created.
Rules has the "Replacement patterns for saved content" field set for pattens.
In there there's going to be cck specific token replacements. You can use those cck tokens to get the data you want.
These replacement tokens will look like [node:field_name_of_your_field-formatted]
Also make sure you're using the "After saving new content" event.


Como enviar Google Chart por email?

Question: Qual seria uma solução viável para enviar um Chart através de email, via PHP? Para obter o Chart, utilizo da seguinte forma:

      google.load("visualization", "1", {packages:["corechart"]});
              google.setOnLoadCallback(drawChart);
              function drawChart() {
                var data = google.visualization.arrayToDataTable([
                 ['Element', 'Density', { role: 'style' }],
                 ['Copper', 8.94, '#b87333', ],
                 ['Silver', 10.49, 'silver'],
                 ['Gold', 19.30, 'gold'],
                 ['Platinum', 21.45, 'color: #e5e4e2' ]
               ]);

                var options = {
                  title: 'Company Performance',
                  hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
                  vAxis: {minValue: 0}
                };

                var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));

                google.visualization.events.addListener(chart, 'ready', function () {
                 chart_div.innerHTML = '';
                 console.log(chart_div.innerHTML);
               });

                chart.draw(data, options);
              }

Dessa forma ele me retorna o Chart em uma versão "printável".
Comment: Tirando como conclusão os componetes de texto que usam formatação, você terá que jogar seu html no corpo do email.
Comment: Sim, mas a API do Google Charts é chamada apenas no cliente e dessa forma não funciona num email. Estou em busca de uma alternativa viável para obter esse chart do lado do servidor e enviar apenas a imagem.
Answer: Google Charts são desenhados utilizando SVG. Alguns provedores de emails fornecem leitura de SVG, outros não. A solução que encontrei foi converter SVG para PNG e salvar o arquivo PNG no servidor e incluir uma tag  no corpo do email.
Do Google Chart ao PHP
O Google Chart trabalha no Front-end. PHP é uma linguagem server-side. Você precisará executar o frontend para que o gráfico seja desenhado e, posteriormente, coletar todo o SVG gerado e encaminhá-lo ao PHP. Com jQuery, você poderia pegar o conteúdo utilizando algo simples, como
var content = jQuery('#chart_div').html();

Feito isso, utilize uma chamada Ajax para entregar o conteúdo ao servidor para que possa ser enviado por email.
Observações: Particularmente, eu preferi escrever o SVG no próprio PHP do que utilizar o Google Chart. Você pode aprender como fazer gráficos utilizando SVG e fazer com que o próprio PHP escreva todo o conteúdo SVG e converta para PNG. Dessa forma, não há necessidades de execuções de script front-end. O próprio servidor se encarregaria de tudo.
Convertendo SVG para PNG
   $path = 'path/to/file.png';

    $im = new Imagick();
    $im->readImageBlob($svg_value);

    /* png settings */
    $im->setImageFormat("png24");
    // $im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1);  /* Optional, if you need to resize */

    $im->writeImage($path); /* (or .jpg) */
    $im->clear();
    $im->destroy();

Comment: [Aqui](http://keepcoding.ehsanabbasi.com/php/convert-google-chart-to-png-and-pdf/) se segue o mesmo conceito.

Como enviar Google Chart por email?


Linguagem de programação diretamente com hardware

Question: Vou fazer aplicações que necessitam de uma ligação direta com o hardware, por exemplo, um mini-robô programável que recebe informações de um sensor e envia para a programação tratar e devolver a ação correta a outra placa ou circuito e etc. necessária de acordo com cada informação recebida. Qual seria a linguagem ideal? C?
Answer: Não existe linguagem mais adequada, pelo menos não com esta descrição.
Existe a que resolve o problema. Se o hardware usado não aceita códigos escritos em C, ela não é adequada. O mesmo vale para C++. Em alguns raros casos pode ser que você só consiga fazer sua aplicação, ou parte dela, em Assembly desse hardware. Pode ser que a linguagem ideal ou mesmo única para esse hardware seja uma que o fabricante inventou. Pode ser Java ou C#, ou quem sabe Lua. Depende também da aplicação. E depende mais ainda de qual você sabe e domina.
Não é a toa que o Lego Mindstorms NXT permite diversas linguagens, tem até dialetos. Imagino que deva existir bibliotecas muito boas para acessar o hardware através da maioria ou todas elas, mas este é apenas um exemplo.
Sem conhecer tudo isto que eu apontei e talvez algumas coisas mais fica difícil dizer qual é mais adequada. E uma destas coisas só você pode responder. Qual você conhece bem e terá satisfação em usar? Há fatores políticos envolvidos?
Qualquer um que diga qual linguagem você deve usar estará sendo tendencioso.
Coloquei no GitHub para referência futura.
Comment: @MarceloBonifazio por isso que certas respostas tem data de validade. Muita coisa mudou de lá pra cá. É claro que C é a linguagem mais usada nesta área, mas está longe de ser a única e não necessariamente a mais adequada. Não tenho como saber. Ir no *default* pode ser mais fácil mas não quer dizer que está indo na mais adequada. PHP e JS também faz, viu?
Comment: Alguém discorda e negativou, pena não saberemos porque.
Comment: Como eu falei, pode fazer qualquer coisa em qualquer linguagem, desde que o hardware tenha a linguagem e bibliotecas específicas bem implementadas. Como a pergunta é genérica, não sei dizer. Agora você está falando em computador, já é outra coisa.
Comment: http://programmers.stackexchange.com/q/84514/164719

Tendencioso ou não, a linguagem C é fundamental pra quem deseja se aventurar no mundo de sistemas embarcados rs

Principalmente em relação a performance, lembrando que o NXT faz parte da família da linguagem C.

https://en.wikipedia.org/wiki/List_of_C-family_programming_languages
Comment: Se eu fosse ele usaria Portugol... :v uahuehaue
Comment: So pra deixar claro que não fui eu que negativei rs, apesar de não concordar em 100%, existem pontos que concordo e alguns pontos que não concordo inteiramente.
Comment: Um outro exemplo legal seria, eu desligar o monitor através do C ou então aumentar e abaixar o volume do computador e etc... é possível isso?
Comment: A sua resposta tá ótima. Mas, não apenas a sua conclusão como a aceitação pelo AP apenas confirmam pra mim que a pergunta é baseada em opiniões: "Qualquer um que diga qual linguagem você deve usar estará sendo tendencioso."
Answer: O Maniero está certo, mas como você disse "aplicações que necessitam de uma ligação direto com o hardware" de cara eu indicaria linguagens de baixo nível, pois essa é uma característica delas. Isso vai depender do sistema que você vai usar. Por exemplo: se for usar um microcontrolador PIC, onde os recursos são escassos, Assembly ou C são as opções. Mas se for usar um sistema mais robusto, dotado de microprocessador, com mais recursos, passa a ser interessante o uso de linguagens de alto nível.


MvcSiteMapProvider bug with pagination

Question: It's continue ASP.NET MVC incorect generation url when using pagination, but there I found how fix it. How fix that when using @Html.MvcSiteMap().SiteMapPath() I can't understand.
Problem in that when in actions ShowForum or ShowTopic and when I using pagination some forum or topic. In @Html.MvcSiteMap().SiteMapPath() I get url at parent page with number of page
UPDATE
For route configuration I'm using route attribute
    [HttpGet]
    [Route("{forumName}", Name = "showForum", Order = 6)]
    [Route("{forumName}/Page/{page}", Order = 5)]
    [OutputCache(Duration = 30, VaryByParam = "forumName;page", Location = OutputCacheLocation.ServerAndClient)]
    public async Task<ActionResult> ShowForum(string forumName, int page = 1)

    [HttpGet]
    [RefreshDetectFilter]
    [Block(VisibleBlock = false)]
    [Route("{forum}/{topicName}", Name = "showTopic", Order = 8)]
    [Route("{forum}/{topicName}/Page/{page}", Order = 7)]
    [OutputCache(Duration = 30, VaryByParam = "topicName;page", Location = OutputCacheLocation.ServerAndClient)]
    public async Task<ActionResult> ShowTopic(string forum, string topicName, int page = 1)

My ForumDynamicNodeProvider
    public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
    {
        var rootTitle = ManagerLocalization.Get("Forums", "FORUMS");
        var pageParameter = new List<string> { "page" };
        var url = "~/Forums";
        var attr = new Dictionary<string, object> { { "Controller", "Forums" } };

        var nodes = new List<DynamicNode>
                        {
                            new DynamicNode
                                {
                                    Key = "forum_home",
                                    Title = rootTitle,
                                    Url = url,
                                    Attributes = attr
                                }
                        };

        var forums = this._forumsService.GetAllForumsForMap();
        var topics = this._forumsService.GetAllTopicsForMap();

        foreach (var forum in forums)
        {
            var forumRouteValue = new Dictionary<string, object> { { "forumName", forum.NameTranslit } };

            nodes.Add(new DynamicNode
            {
                ParentKey = forum.ForumId != -1 ? $"forum_{forum.ForumId}" : "forum_home",

                Key = $"forum_{forum.Id}",
                Title = forum.Name,
                PreservedRouteParameters = pageParameter,
                Controller = "Forums",
                Action = "ShowForum",
                RouteValues = forumRouteValue,

            });

            var forumTopics = topics.Where(item => item.ForumId == forum.Id);

            foreach (var topic in forumTopics)
            {
                var topicRouteValue = new Dictionary<string, object> { { "forum", forum.NameTranslit }, { "topicName", topic.TitleTranslite } };

                nodes.Add(new DynamicNode
                {
                    ParentKey = $"forum_{forum.Id}",
                    Key = $"topic_{topic.Id}",
                    Title = topic.Title,
                    PreservedRouteParameters = pageParameter,
                    Controller = "Forums",
                    Action = "ShowTopic",
                    RouteValues = topicRouteValue,
                });
            }
        }

        return nodes;
    }

Comment: Please post your node configuration. You should also post your route configuration here (rather than linking to another question) as it pertains to paging. It is unclear what the "solution" was on your other question - it appears you just took the pagination off of the route.
Comment: Ok. I added route configuration and ForumDynamicNodeProvider
Answer: The problem is that you are using the same route key name {page} in two different places in the same node ancestry in combination with PreservedRouteParameters. PreservedRouteParameters gets its data from the current request. So, it is important that a route key have the same meaning in each request in the same node ancestry. For it to work correctly with PreservedRouteParamters, you need to do three things:

Use a different route key for each separate page parameter (for example, {forumPage} and {page}).
Ensure the ancestor page parameter is passed to the request of its descendants, so when building the URL to an ancestor node the value is in the current request. The simplest way is to build the URL with the page information of all ancestors ({forumName}/Page/{forumPage}/{topicName}/Page/{page}).
Any route keys that have the same meaning between nodes should stay the same ({forumName} in both routes).

Then you need to add the parameters when building the URL of the child node. You must build the URL manually within your application because the request will not have all of the parameters unless you do.
@Html.ActionLink("TheTopicName", "ShowTopic", "Forums",
    new { forumName = 1, forumPage = 2, topicName = "foo", page = 1 }, null)

The reason you must supply all of the data in the child node request is because the ancestor node needs it to build its URL. It pulls this information from the request, so it must be present in the request for it to function. MvcSiteMapProvider has no way of knowing what the current page number of the ancestor node is unless it is provided in the request by a URL that is built outside of your menu.

See the MvcSiteMapProvider-Forcing-A-Match-2-Levels project in the code download for How to Make MvcSiteMapProvider Remember a User's Position for a similar configuration and the solution. In that case, it is using productId instead of forumPage as the parameter that is preserved on the descendant nodes so you can navigate back to the parent product.

Note that you could use a similar configuration (with PreservedRouteParameters and SiteMapTitleAttribute) for your entire forum rather than using a dynamic node provider. However, in that case I would suggest you disable the /sitemap.xml endpoint and roll your own.
Comment: If correctly to say. Change keys of routes. That help with topic, but for sub forum it's didn't help me
Comment: I have updated my answer. I am not sure how I can be any more clear than this, as I have already provided a working sample - when using `PreservedRouteParameters` the all of the data needs to be in the request of the child node or the ancestor URL won't be built.
Comment: How I wrote, I fix problem with link to topic, I have problem with @Html.MvcSiteMap().SiteMapPath() in forum when I'm using pagination
Answer: I found how this fix, thank you to NightOwl888. I'm not the first time understood what should to do.
First I removed initialization PreservedRouteParameters in ForumDynamicNodeProvider
Second I added in action
        if (forumPage > 1)
        {
            var node = SiteMaps.Current.FindSiteMapNodeFromKey(forumName);

            if (node != null)
            {
                node.RouteValues["forumPage"] = forumPage;
            }
        }

Also I need change generation tree in ForumDynamicNodeProvider because SiteMaps.Current doesn't work in async

MvcSiteMapProvider bug with pagination


Subring Example

Question: Let S={[0],[1],[2],[3],[4]}.  Is S a subring of Z(mod 6)?
My thoughts: I have a lot of trouble sort of working with the sets I am given in certain situations like these.  I know the first two qualifications of a subring are closed under addition and multiplication.  So do I just take the individual congruence classes [0] and [2] for example and add combinations together to see if their addition concludes that it isint a subring?
Answer: $|S|=5$ and $|\Bbb Z_6|=6$, so isn't even a subgroup, since $5$ doesn't divide $6$..
Answer: Yes, you are right. If you want to do it 'by foot' you could say for example that $[1]+[4]=[5]$ is not in the set, and you are done. Obviously you can answer the question using an abstract argument as well (see @ajotatxe's answer).

Subring Example


Is this proof involving quantifiers valid?

Question: Is this a valid proof? If so can someone explain it?
Prove that: $\forall x: \exists y : (x \leq y) \land \lnot I(y)$
Premises: $\forall x: \forall y: [I(x) \land \lnot I(y)] \implies (x \lt y)$ and $\exists z : \lnot I(z)$
Proof: We let $a$ be an arbitrary element. Then $I(a) \lor \lnot I(a)$.
Case 1: $I(a)$
By rules of instantiation and our second premise we instantiate b such that $\lnot I(b)$. $I(a) \land \lnot I(b)$ so by modus
ponens and our first premise, $a \lt b$ and by our definition of $\leq$, $a \leq b$. Therefore $(a \leq b) \land \lnot I(b)$. Then
by existence, $\exists y : (a \leq y) \land \lnot I(y)$.
Case 2: $\lnot I(a)$
We know $a = a$, so by definition $a \leq a$. We assumed $\lnot I(a)$, so using conjunction we have $(a \leq a) \land \lnot I(a)$.
Thus by existence  $\exists y : (a \leq y) \land \lnot I(y)$.
Then in both cases, by generalization, we have $\forall x: \exists y : (x \leq y) \land \lnot I(y)$.
For case 2: if we took $a$ as arbitrary why did we use rule of existence and not generalization?
Answer: Your proof is exactly correct! Well done.
And you used existential introduction in both cases exactly because you were trying to prove an existential: $\exists y (a \leq y \land \neg I(y))$
It's only after that proof by cases that you introduce a universal ... which is why you introduced $a$ as an arbitrary object.
Yes, it may feel weird that in case $2$ you end up creating the existential using the same object as that you end up creating the universal at the end with ... this is certainly unusual for a proof ... but it is all perfectly valid!
Indeed, when the statement says: $\forall x \exists y ...$, then of course for some of the $x$'s the $y$ could be the same as the $x$ ... and that's exactly what is going on here.


NHibernate one-way association with XRef table

Question: I'm stuck trying to get the mapping I want to persist correctly. For my example, I have an ItemY class which can have 0,1,* Assets. However, an Asset can belong to an ItemY or an ItemZ object. I'm trying to use a cross-reference table to store this.
Schema
TABLE [dbo].[ItemY](
    [ItemYID] [int] IDENTITY(1,1) NOT NULL,
    --more columns here

TABLE [dbo].[Asset](
    [AssetID] [uniqueidentifier] NOT NULL,
    [AssetTypeID] [int] NOT NULL,
    [DisplayOrder] [int] NOT NULL,
    [Location] [varchar](255) NOT NULL,

TABLE [dbo].[ItemYAsset](
    [ItemYID] [int] NOT NULL,
    [AssetID] [uniqueidentifier] NOT NULL,

Mappings:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MyAssembly" namespace="My.Namespace">
<class name="ItemY" table="ItemY">
    <id name="ItemYId" column="ItemYID">
        <generator class="identity" />
    </id>
    <bag name="Images" table="ItemYAsset" inverse="true" cascade="all-delete-orphan">
        <key column="ItemYID" not-null="true" />
        <many-to-many class="Asset" column="AssetID" unique="true" />
    </bag>

</class>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MyAssembly" namespace="My.Namespace">
    <class name="Asset" table="Asset">
        <id name="AssetId" column="AssetID">
            <generator class="guid.comb" />
        </id>
        <property name="DisplayOrder"></property>
        <property name="Location"></property>
    </class>
</hibernate-mapping>

I don't want to expose an ItemY property on Asset, since an Asset doesn't always belong to an ItemY. My ItemY class persists fine, and also persists the Asset class, but there is nothing added to the association table (ItemYAsset). Any idea what I'm doing wrong?
Answer: inverse="true" means the "other side" is responsible for persisting the relationship.
Since you have no "other side" (the relationship is unidirectional), remove that attribute.


Composer installing Tripal module only above v4 and if continuing with v4, getting error with Chado module

Question: As part of college course work, I am required to make a genomic database with a local website with basic features. I have installed Drupal 10.2.3 with PostgreSQL 14.11 and PHP 8.3.4.
My primary question is, should I continue with Tripal version 4 even though it is still in development? If no, how do I downgrade to stable v3.10 when facing this error?
When trying to install (or downgrade to) Tripal v3.10 using

sudo -u www-data composer require 'drupal/tripal:^3.10'

I am getting following error
<code>
  Problem 1
    - Root composer.json requires drupal/tripal ^3.10, found drupal/tripal[dev-4.x, 4.0.0-alpha1, 4.0.0-alpha2, 4.x-dev (alias of dev-4.x)] but it does not match the constraint.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.
</code>
My composer.json only contains the below
<code>{
    "require": {
        "drush/drush": "^12.4",
        "drupal/core": "^10.2"
    }
}
</code>
I am  new to Drupal as well as website development in general, and figured I would face less issues with v3 than v4 (which is still in development).
As a side note, I tried continuing with drupal/tripal:4.0.0-alpha2, and was able to proceed until I got error in Chado installation via Home > Administration > Tripal > Data Storage > Chado > Install Chado. From my limited understanding, it has something to do with missing "drupal_chado_installations" table but it seems to exist when I give command

SELECT * FROM information_schema.tables WHERE table_name = 'drupal_chado_installations'

I am also adding the Chado installation error if someone feels it is better to continue with Tripal v4
@ http://localhost/admin/tripal/storage/chado/install

The website encountered an unexpected error. Try again later.
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42P01]:
Undefined table: 7 ERROR: relation "drupal_chado_installations" does
not exist LINE 3: "drupal_chado_installations" "i" ^: SELECT
"i"."install_id" AS "install_id", "i"."schema_name" AS "schema_name",
"i"."version" AS "version", "i"."created" AS "created", "i"."updated"
AS "updated" FROM "drupal_chado_installations" "i"; Array ( ) in
Drupal\tripal_chado\Database\ChadoConnection->getAvailableInstances()
(line 279 of
modules/contrib/tripal/tripal_chado/src/Database/ChadoConnection.php).
Drupal\Core\Database\StatementWrapperIterator->execute() (Line: 851)
Drupal\Core\Database\Connection->query() (Line: 239)
Drupal\pgsql\Driver\Database\pgsql\Connection->query() (Line: 525)
Drupal\Core\Database\Query\Select->execute() (Line: 155)
Drupal\pgsql\Driver\Database\pgsql\Select->execute() (Line: 279)
Drupal\tripal_chado\Database\ChadoConnection->getAvailableInstances()
(Line: 47) Drupal\tripal_chado\Form\ChadoInstallForm->buildForm()
call_user_func_array() (Line: 536)
Drupal\Core\Form\FormBuilder->retrieveForm() (Line: 283)
Drupal\Core\Form\FormBuilder->buildForm() (Line: 73)
Drupal\Core\Controller\FormController->getContentResult()
call_user_func_array() (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
(Line: 627) Drupal\Core\Render\Renderer->executeInRenderContext()
(Line: 121)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext()
(Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
(Line: 181) Symfony\Component\HttpKernel\HttpKernel->handleRaw()
(Line: 76) Symfony\Component\HttpKernel\HttpKernel->handle() (Line:
58) Drupal\Core\StackMiddleware\Session->handle() (Line: 48)
Drupal\Core\StackMiddleware\KernelPreHandle->handle() (Line: 28)
Drupal\Core\StackMiddleware\ContentLength->handle() (Line: 32)
Drupal\big_pipe\StackMiddleware\ContentLength->handle() (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass() (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle() (Line: 50)
Drupal\ban\BanMiddleware->handle() (Line: 48)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle() (Line:
51) Drupal\Core\StackMiddleware\NegotiationMiddleware->handle() (Line:
36) Drupal\Core\StackMiddleware\AjaxPageState->handle() (Line: 51)
Drupal\Core\StackMiddleware\StackedHttpKernel->handle() (Line: 704)
Drupal\Core\DrupalKernel->handle() (Line: 19)

My settings.php file already contains the database connection detail so many solutions mentioning that are not working
<code>$databases['default']['default'] = array (
  'database' => 'teak_wood_genes_db',
  'username' => 'postgres_molecular',
  'password' => '**********',
  'prefix' => 'drupal_',
  'host' => 'localhost',
  'port' => '5432',
  'driver' => 'pgsql',
  'namespace' => 'Drupal\\pgsql\\Driver\\Database\\pgsql',
  'autoload' => 'core/modules/pgsql/src/Driver/Database/pgsql/',
);
</code>
Comment: There is only one question you may ask at a time on Drupal Answers.
Comment: Noted (as this is my first post). Ig my primary question is, should I continue with Tripal version 4 even though it is still in development? If no, how do I downgrade to stable v3.10 when facing this error?
Comment: There isn't a version 3.10 - that's an old versioning pattern from Drupal 7, it's not relevant to Drupal 8+. According to the module page, v4 is the only release available
Comment: Thank you! I am still getting the hang of various versions and their compatibility. So this means v4 is the only option for Drupal 10 right.
Comment: It looks that way, you can see what tags are available here: https://git.drupalcode.org/project/tripal/tree/4.x. There's no 3.x branch, so it seems the developer went straight from the old 7.3 to 4.0 for numbering
Comment: Thank you! Got a clearer picture now
Answer: Version 3.10 does not exist for that version of Drupal. Composer is telling you all the available versions.


Script não funciona

Question: O objectivo é caso o campo esteja vazio escreva na "label" que o campo não pode estar vazio.
O objectivo do form é ir ao confirmaNovaParagem.php  enviar os dados e depois o confirmaNovaParagem reenvia o utilizador para a pagina de adicionar paragens.
O que acontece é que o script não funciona  e vai logo para o ConfirmaNovaParagem.php.
Sou iniciante em javascript desculpe qualquer erro mas óbvio.

            Adicionar Paragem

        <form name="Adicionaparagem" action="confirmaNovaParagem.php" method="post">

                Nome da paragem:

                <input type="text" name="adicionanomeparagem">

                Latitude paragem:

                <input type="text" name="adicionalatitudeparagem">

                Longitude paragem:

                <input type="text" name="adicionalongitudeparagem">

                Estado paragem:

                <select name="estadoparagem">
                    <option value="1">Activa</option>
                    <option value="2">Inactiva</option>
                </select>

                    <input class="botao" value="Adicionar"  onclick="valida_form ()" type="submit" >

    </form>

Answer: Tens de parar o envio da form com event.preventDefault(), isso impede o button de agir como esperado. Depois fazes a verificação e caso seja válida corres form.submit();
Dá uma olhada a este exemplo, depois de clicares no enviar ele espera 5 segundos e envia a form, portanto interrompendo o que é esperado.
var button = document.querySelector('button');
var form = document.querySelector('form');
button.addEventListener('click', function(e) {
    e.preventDefault();
    setTimeout(function() {
        form.submit();
    }, 5000);
});

jsFiddle: https://jsfiddle.net/ov57u1zp/

No teu caso o código teria de ser:
<input class="botao" value="Adicionar"  onclick="valida_form(event)" type="submit" >

e na função:
function valida_form (e){
    e.preventDefault();
    // resto da lógica de validação
    // ...
    // e depois, se tudo estiver certo:
    document.querySelector('form[name="Adicionaparagem"]').submit();

Answer: vou listar o que eu achei no seu arquivo, que pode estar te causando problemas.

O seu html não está completamente formado. Existe um fechamento de div extra antes do fechamento do form.
A sua função não continha um retorno, sendo assim, toda vez que você clicava no botão, a ação de submit era executada.
O seu onclick estava chamando a função, mas não estava tratando o retorno, quando se coloca, onclick="return valida_form()", ele executa a função e caso o retorno seja falso, o submit não é executado. Caso o retorno seja verdadeiro, o submit é executado.
Nessa linha document.getElementById("adicionanomeparagem").value == "" você está tentando pegar o elemento pelo id, porém os seus inputs não possuem id e sim name. Adicione a propriedade id para o input desejado.
Nessa linha var div = document.getElementById("adicionanomeparagem"); você estava tentando pegar uma "div" que possui o mesmo id do seu input. O que não seria o correto, pois o id é unico, ou seja, somente um elemento no dom, pode possuir aquele id.

Aqui está um boa referência de como fazer validação de formulários.
Abaixo seque o meu código com apenas algumas modificações, nada sofisticado, do que eu faria no seu código.

            Adicionar Paragem

        <form name="Adicionaparagem" action="confirmaNovaParagem.php" method="post">

                Nome da paragem:

                <input id="adicionanomeparagem" name="adicionanomeparagem" type="text">

                Latitude paragem:

                <input type="text" name="adicionalatitudeparagem">

                Longitude paragem:

                <input type="text" name="adicionalongitudeparagem">

                Estado paragem:

                <select name="estadoparagem">
                    <option value="1">Activa</option>
                    <option value="2">Inactiva</option>
                </select>

                    <input class="botao" value="Adicionar"  onclick="return valida_form ()" type="submit" >

        </form>

Script não funciona


Gráficos de porcentagem em R

Question: Olá, preciso  fazer um gráfico de barras com histórico de porcentagem de clientes que compraram o produto ao longo dos anos de 2012 a 2022. No eixo x deve conter os anos e no eixo y as porcentagens. Na coluna cliente é sinalizado se ele comprou naquele ano 1 pra sim e 0 pra não.
Tabela1<- filtrar(dados, Clientes==1, Ano_Compra=> 2012)
Numerador <- (Tabela1$Clientes)
Denominador <- dados$Clientes)
Total_p<- round (sum(Numerador/(Denominador)*100,1)

Comment: Benvinda ao StackOverflow em português! Sua pergunta está ampla, pocentagem sobre o mês, ano? Qual linguagem está desenvolvendo sua solução? Pode colocar o que tentou para que alguém possa ajudar a encontrar a solução?
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: `filtrar` não é uma função do R. Pode ser `subset(dados, Clientes==1 & Ano_Compra => 2012)`.
Comment: Fiz igual a esse código, mas não consegui colocar as porcentagens em cima das barras, sabem como eu faço isso? Tentei o geom_text mas não consegui

ggplot(subset(dados, Clientes == 1), aes(Ano_Compra)) +
  geom_bar(aes(y = ..prop..), fill = "skyblue") +
  scale_x_continuous(breaks = 2012:2022, labels = 2012:2022) +
  scale_y_continuous(labels = scales::percent)
Answer: Aqui vão duas maneiras de traçar gráficos de barras a partir de variáveis binárias.
R base
Primeiro calculam-se os totais com tapply, a seguir transformam-se em porcentagens.
Quanto ao gráfico, o eixo dos y vai ser traçado manualmente. A escala é formatada, chama-se barplot e o eixo no fim.
totais <- with(dados, tapply(Clientes, Ano_Compra, FUN = sum))
porc <- 100*totais/sum(totais)
y_axis <- seq(0, max(porc) + 1L, by = 2.5)
barplot(porc, yaxt = "n", ylim = c(0, max(porc) + 1L))
axis(2, at = y_axis, labels = paste0(y_axis, "%"))

Created on 2022-03-21 by the reprex package (v2.0.1)
Pacote ggplot2
A base dados é filtrada com subset para se ficar só com as linhas de compra 1, a contagem dessas linhas é feita pelo geom_bar.
library(ggplot2)

ggplot(subset(dados, Clientes == 1), aes(Ano_Compra)) +
  geom_bar(aes(y = ..prop..), fill = "skyblue") +
  scale_x_continuous(breaks = 2012:2022, labels = 2012:2022) +
  scale_y_continuous(labels = scales::percent)

Created on 2022-03-21 by the reprex package (v2.0.1)

Dados de teste
set.seed(2022)
n <- 4000
Ano_Compra <- sample(2012:2022, n, replace = TRUE)
Clientes <- rbinom(n, 1, 0.5)
dados <- data.frame(Ano_Compra, Clientes)

Created on 2022-03-21 by the reprex package (v2.0.1)
Comment: Se [utiliza uma resposta na pergunta seguinte](https://pt.stackoverflow.com/questions/547317/como-inserir-porcentagem-no-gr%c3%a1fico-em-r), deve ao menos **aceitar a resposta**.

Gráficos de porcentagem em R


Provide User with list field of images to select

Question: I am using the flexslider module in conjunction with the views slider to create a slideshow on my Drupal project. Instead of just allowing the user to upload an image for the slideshow (the image really just acts as a background), I would like to provide the user with a list of possible images to choose from. I'm new to Drupal, so this is probably a really easy thing to accomplish, but multiple Google queries have left me in the dark.
Answer: I previously used IMCE for FileField module:

it opens a simple file browser and let you select files from configured path of server.


How to add a space between a string for every 5th letter?

Question: Hey, I'm trying to figure out how to input a space between every fifth letter in my program after the computer asks how many coins they would like. So this is what it looks like currently.
pile1_str = "pile 1: "
x="O"
y=1
while y <= pile1:   #pile1 being the number of chips the user inputs
    pile1_str = pile1_str + x
    print(pile1_str)
    y= y+1

Here's what it's supposed to look like when you input, say 12 coins:
pile 1: OOOOO OOOOO OO
What can I do to insert a space in the string after every n-th (5th) character?
Comment: So what is the problem?
Answer: pile1_str = "pile 1: "
x="O"
y=1
while y <= pile1:
    pile1_str = pile1_str + x
    if y%1==0:
        pile1_str = pile1_str + " "
    print(pile1_str)
    y= y+1

Answer: length = 19
groupSize = 5
pile = 'O' * length
spacedPile = ' '.join(pile[i:i+groupSize] for i in xrange(0, len(pile), groupSize))
print spacedPile

Comment: Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* and *why* this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now!  Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply.


Alert for possible thread protection

Question: Please monitor this question/ thread
People pathologically hoard so much cash that they impoverish the entire nation
It possibly approaches a situation where it will need to be protected.
Since I have posted an answer on the thread, as a matter of principle I would not want to be the one to decide on that.
Answer: Thread has been protected by denesp. I guess we can consider this to be solved.

Alert for possible thread protection