How does conditional probability relate to mathematical operators? How to know when to define events as conditional?

Question: I noticed in my introductory statistics course that most operators like AND/OR relate to mathematics operators like multiplication and addition. Is there any relation between conditional probability to mathematical operators?
My follow up question for this is: I'm struggling to determine when to define an event as a conditional probability event or when to define it as A and B have occurred. I'm not sure why this is not making sense for me, but it'd help to know a better way to understand when and how to define conditional probability.
Answer: Probability theory is a branch of mathematics, so it is a "mathematical operator". It is defined in terms of joint probability of two events $A$ and $B$ occurring together
$$
P(A\; \mathrm{and} \;B) = P(A, B)
$$
and the marginal probability $P(B)$,
$$
P(A | B) = \frac{P(A,B)}{P(B)}
$$
Comment: @Jeygopi the above is the definition, you cannot go simpler then that.
Comment: I meant more of the lines:

P(A and B) = P(A) * P(B)

P(A|B) = P(A) (operator) P(B)

Is there something I can look up to understand conditional probability in this way?
Comment: @Jeygopi more of what?
Comment: More along the lines, is there something analogous to a binary operator that P(A|B) can be related to?
Answer: The simplest way to understand conditional probability at an introductory level is to undertake exercises where you relate probabilities to areas and relative-areas in a Venn diagram.  There are many resources available that teach conditional probability in this way, but I will give a simple outline here.  Consider a Venn diagram with two events $A$ and $B$ represented as interlocking circles (picture taken from this related question), and suppose we treat the areas as being equivalent to the probabilities.  The probability of $A$ is the area of the purple circle and the probability of $B$ is the area of the blue circle.  The conditional probability of $A$ given $B$ would be the relative size of the intersection where both these events occur (the dark-blue area in the middle) relative to the area of the blue circle.

If you do a quick search online you will find hundreds of introductory resources that explain conditional probability by reference to Venn diagrams, and this gives you a nice visual illustration of the concept.  You will also be able to find exercises to test your knowledge.  I would recommend this as a starting point for anyone having difficulty understanding the relationship between conditional probability and the AND/OR operations on events.
Answer: When you say
$$P(A \text{ and }B)=P(A)\cdot P(B)$$
that is true for independent events. For non independent events, the chain rule for probability says:
$$P(A\text{ and }B) = P(A|B)\cdot P(B)$$
In fact, when $A$ and $B$ are independent, $P(A|B)=P(A)$ and you get the first definition back.
The event $A|B$ makes sense when the probability of $A$ is influenced by the outcome of $B$. Its probability $P(A|B)$ is defined as Tim said before.


Is this a condition to be order isomorphic to a subset of the integers?

Question: Let $S$ be a totally ordered set such that any nonempty subset of $S$ bounded above has a greatest element and any nonempty subset of $S$ bounded below has a least element.  Is $S$ order isomorphic to a subset of the integers?
Comment: @JensRenders: No, an empty subset _does not_ contain a least element (or a greatest one).
Comment: @EricWofsey Yes thank you.  I've updated the question to match this.
Comment: @JensRenders: It would be _true_ but uninterestingly so, because the only $S$ that satisfies the assumption is then $S=\varnothing$. With Eric Wofsey's correction there is actually something to prove.
Answer: Yes.
Assume without loss of generality that $S$ has a least element. (Otherwise pick an element and handle the part of $S$ above and below the chosen element separately -- for those below mutatis mutandis with the order swapped).
Now we can keep assigning the "smallest element of $S$ not yet used" to integers starting with $0$ and counting upwards. (After the first step, the set of integers not yet used is always bounded below by the original least element).
This can either end when we've used up all of the elements, or when we've assigned elements to all the natural numbers. But in the latter case, the set of elements that we have assigned yet cannot be upwards bounded in $S$ -- because then they would have a largest element, which they haven't -- so also in that case there cannot be any elements left.
Answer: Pick any element $a\in S$, and consider $T=\{x\in S:a\leq x\}$ and $U=S\setminus T$.
Every subset of $T$ has least element, so $T$ is well ordered, and thus order isomorphic to some ordinal number. Now for every $\alpha > \omega$, take $\omega \subset \alpha$ to be subset bounded above with no greatest element. This imply, that $T$ is order isomorphic to some subset of $\mathbb{N}$. Dual argumentation shows that $U$ is order isomorphic to subset of $\mathbb{Z}\setminus\mathbb{N}$.


Pressure Formula using calculus

Question: Can someone help me with this question?
The pressure of an ideal gas, measured in kPa, is related to its volume, $V$, and temperature, $T$, by the equation:
$PV=0.34T$.
The temperature is measured with an error of $3$ Kelvin and the volume is measured with an error of $0.6 \ m^3$ . If it is known that the actual values are $T=282$ Kelvin and $V=3 \ m^3$, what is the maximum error in the measurement of the pressure? Round your answer to $3$ decimal places.
I know I need to solve for $P$ so $P=.34T/V$ and then I don't know what to do.  I just want to be able to understand how to do the problem before its due.
Comment: Hint : You need the derivates with respect to $V$ and $T$. Multiply them with $\Delta V$ and $\Delta T$ respectively and add the products.
Comment: I did that and I got -6.052 and thats wrong
Comment: Oh, I forgot to mention that you have to use the absolut value of the derivates.
Answer: $$P=0.34\times\frac{T}{V}$$
$$P=0.34\times\frac{282\pm 3}{3\pm0.6}$$
$$\implies 0.34\times\frac{282-3}{3+.06}\leq P\leq 0.34\times\frac{282+3}{3-.06}$$
$$\implies 0.34\times{279}{3.06}\leq P\leq 0.34\times\frac{285}{2.94}$$
$$\implies 31\leq P\leq 32.959$$
The actual value of $P$ is $P=0.34\times\frac{282}{3}=31.96$
Therefore the maximum error is $32.959-31.96=0.999$
(note I chose 32.959 rather than 31 because its interval from 31.96 is the greater).

Pressure Formula using calculus


Automatic ZFS Snapshots on Solaris 10

Question: I'm trying to enable automatic ZFS snapshotting on a Solaris 10 server.
From extensive googling, I've managed to understand that there are/were some automated services to do this, like:

http://mij.oltrelinux.com/devel/zfsbackup/

And even locate a manual of sorts for a built in service:

http://download.oracle.com/docs/cd/E19120-01/open.solaris/817-2271/6mhupg6oc/index.html

Alas, on the Solaris I'm working on, I can't seem to find the "Time Slider" service, nor the auto-snapshot service other articles refer to, that is supposed to be built in, and simply enabled.
Does anyone know how I can install/enable this service?
Answer: This service isn't available for Solaris 10, you need an OpenSolaris based distribution or Solaris 11 Express to get it.
Of course, nothing prevents you to re-implement it but you will miss the Gnome file manager integration.
Comment: I got the same answer from Oracle support... Apparently it's not in Solaris 10. If someone could suggest an alternative tool, it would be great... Thanks :)
Comment: Have a look at this blog entry. Some people managed to use the previous zfs automatic snapshot implementation on Solaris 10. http://blogs.sun.com/timf/entry/zfs_automatic_snapshots_0_12
Answer: Could it be part of the GNOME file manager package ?
In Solaris 11 express its listed as:
Time Slider ZFS Snapshots management for GNOME
pkg:/desktop/time- slider@...

Automatic ZFS Snapshots on Solaris 10


Profit Maximization problem in linear programming where orderring new raw materials is allowed

Question: My problem is this:
A factory manufactures two types of jewels.

Each one of them consists of gold and two
kinds of
gems- diamonds and pearls.

Every unit of jewel No. 1 consists of 3
diamonds, 5 pearls and 0.3 grams of gold. A
unit of Jewel NO. 1 is sold by the price of
200$, and its demand is 10.

Every unit of jewel No. 2 consists of 1
diamond, 1 pearl and 0.1 grams of gold. A
unit of Jewel NO. 2 is sold by the price of
70$, and its demand is 17.

It takes 15 minutes to set one gem ( Diamond
or pearl ) on a jewel( 1 or 2 ), and it
takes 20 minutes to polish a jewel.

The factory has a total of 80 diamonds, 120
pearls, 30 grams of gold, 400 Working
hours, and has an option of
purchasing extra gems in the price of 30$
per a diamond, and 20$ per a pearl.

Model this problem in terms of linear
programming

Now, without extra gems, this would have been my solution( Where x1 and x2 are the amounts of jewel 1 and jewel 2 to be manufactured ):
Max{200x1+70x2}

s.t

3x1+x2<=80

5x1+x2<=120

[15*(3+5)+20]x1<=400*60
[15*(1+1)+20]x2<=400*60

0.3x1+0.1x2<=30

x1<=10
x<=17

My issue is I can't really figure out how to combine the extra gems part into the constraints. Can sombody give a piece of advice?
Answer: Even without the extra gems, your formulation needs some correction.  Where you have a pair of constraints (one for $x_1$ and one for $x_2$), you should instead have a single constraint (involving both $x_1$ and $x_2$) for the shared resource.  Also, the demands should impose upper bounds (rather than lower bounds) on $x_i$, because you cannot sell more than the demand.
For the extra gems, introduce two more decision variables, say $d$ and $p$, for the number of extra diamonds and pearls, respectively.  Then include $-30d-20p$ in the objective function.  And modify the corrected resource constraints.  For example, the corrected diamond constraint $3x_1+x_2 \le 80$ becomes instead $3x_1+x_2 \le 80+d$.
Comment: Ok, and I guess you don't include the working hours, as two unit of the the two types gems can be processed at the same time.
But still, do you have any idea for the extra gems issue?
Comment: Read your editted reply,
Thanks a lot!


Is it possible to get a TXT record value for a domain that also has an NS record

Question: I'm writing an app that lets a user host our pages on their domains. To do that, they need to configure a couple records in their DNS. One is a TXT record with a unique value just to prove ownership. The other is for directing traffic to our site, and for that we have three options.
A CNAME record would work, but cannot be combined with the TXT record (CNAME needs to be the only record per RFC). An A record would work and would allow a TXT record as well, but we want to avoid using IPs directly because then it's hard to migrate to a different IP.
So we're looking into an NS record that points to our DNS. The problem is that while it's possible to configure a single domain with both an NS record and a TXT record, when you query for the TXT record on the original domain you get nothing, and I think it's because of the NS record. The TXT record query hits the customer's domain which says "My name server is over there", and THAT nameserver has no TXT record.
Is there any way to combine both an NS record and a TXT record on a single domain and still be able to get the value of the TXT record from the original server?
Comment: Why bother with "a TXT record ... to prove ownership"? The user can't actually change the really relevant domain settings unless they can control the DNS. The extra TXT record is redundant.
Comment: Because of subdomains and the possibility that some other user already registered a parent domain.  Say user X sets up x.com with us and does so using an NS record.  The NS record will handle requests to x.com as well as sub.x.com.  I don't want user Y being able to set up sub.x.com as his own just because someone else set up x.com.  But I *do* want different people to be able to use subdomains if they can set up the txt record.
Comment: I've seen this method used in several places, google uses them as an alternative indicator of domain ownership, however, I think you're confused as to what you can do if you have a domain (or subdomain). It's entirely possible to have a separate record say `Iownthis   TXT   some_string_of_text` and another `mikesapp  CNAME mikes.server.com` in either a primary domain or subdomain delegation..  All you really need to do is CNAME to a full TLDR (www.domain.com), not just the domain.com root.
Comment: Right.  I've got several approaches that work.  I can use an A record and a TXT record on the exact same node without issue.  I can use a CNAME (except on the root node) but then I cannot not have a TXT record on the same node as the CNAME (either a sibling or sub-node works fine).  Or I can have an NS record AND I can put a TXT record on a single node, but then I don't appear to be able to be able to query the user's domain for that specific TXT record.  It doesn't come back.  My question is specifically about having a TXT record and an NS record on a single node in DNS and being able to....
Comment: ...query the original server for the TXT record itself and get the value back.  I appreciate the suggestions, but this is a technical question about having a TXT and NS record on the same node and being able to query the server for that TXT record's value.
Comment: @MikeSnare I hope you found a solution because I have the same problem in my VPS and I cannot figure it out yet!
Answer: This is what I ended up doing for Gitlab Pages. Probably works for heroku, and probably your app too @MikeSnare. Necro, but posting it here cuz Gitlab Page's solution was less than ideal and googling leads to nothing helpful.
The Challenge:

TXT Record for Ownership Verification: You need to publish a TXT record on your own subdomain with some expected unique string assigned. In the case of gitlab, something like yourapp.example.com. TXT unique_nonsense_here
Resilient domain lookup: You can't combine a CNAME with a TXT record, and using an ALIAS gives away your entire domain (lame). A records are brittle, and NS records as you pointed out don't propagate your TXT records to the original domain.

Dynamic DNS as a Workaround

Dynamic DNS Setup: Configure a dynamic DNS record for your subdomain.
CI/CD Pipeline or Script: Set up a CI pipeline or script to periodically query the IP of the remote subdomain and update the dynamic DNS record using the ddns credentials.(eg, for yourapp.example.com CNAME yourapp.gitlab.io., you'd do like dig yourapp.gitlab.io A and publish the resulting A record as your ip for yourapp.example.com)
Verification and Testing: Ensure the TXT record remains valid for domain verification and that the subdomain correctly resolves to your hosted content's IP.


Given $x \in \mathbb{R}$ and $N \in \mathbb{N}, N>1,$ find integers $h,k$ with $0 < k \leq N $ that satisfy $\lvert{kx - h\rvert} < 1/N.$

Question: This is a problem from Apostol's $\textit{Mathematical Analysis}$. He provides a hint: Consider the $N+1$ numbers $tx-[tx]$ for $t=0,1,\ldots,N$ and show that some pair differs by at most $1/N$, where $[x]$ is defined as the greatest integer $\leq x$.
I have defined $a_t:= tx-[tx]$. I know $a_t \in [0,1)$ for every $t=0,1,2,\ldots,N$. How can I show that there exists $i,j \in \lbrace{0,1,\ldots,N\rbrace}, i \neq j$ such that $N\lvert{a_i-a_j\rvert}$ < 1? I've been stuck on this problem for a quite a while. A hint would be much appreciated.
Answer: You have $N + 1$ numbers in $[0, 1)$ (one for each $t$ in $\{0, 1, \dots, N\}$). Partition the interval $[0, 1)$ into $N$ subintervals of equal length. Now consider where your $N + 1$ numbers lie with respect to this partition.
Comment: Ah, the pigeonhole principle. Thanks!


Carregar imagem e inserir dentro de uma DIV

Question: Tenho o seguinte layout:

Gostaria de que quando eu clicasse em CARREGAR, abra o explorer para eu escolher a imagem e carregue ao lado a imagem, onde há uma DIV, como acontece em vários sites.
Tem algum plugin para isso?
Comment: somente um preview?
Comment: Pode ser preview, é a primeira vez que me deparo com essa situação.
Answer: Não há necessidade de nenhum plugin para este feitio, você pode simplesmente utilizar o elemento input do html que seria o seguinte:
<input type=file id=teste>

Você logo teria um botão para selecionar um arquivo em seu computador e poderia resgatar o caminho do arquivo da seguinte forma, em javascript:
$('#teste').val();

Logo você pode apenas setar o src do seu elemento  para o resultante arquivo.
var img = $('#teste').val();
$('#id_sua_img').attr('src', img);

Obs:
Isso só funciona se for local, se você quiser que qualquer usuário carregue um arquivo de seu próprio computador para que o mesmo seja carregado em sua aplicação, aí teria de ser feito um upload para o servidor utilizando php e depois bastar utilizar o caminho destino do upload como src da imagem
Comment: Você está a usar jQuery. jQuery serve para isso. @Paulo, atualize a sua resposta utilizando `$("#sua_img").attr("src", $("#teste").val());`
Comment: Perfeito, demorei pra entender, mas compreendi agora.
Comment: Sim, com o `input type=file` eu consigo carregar o arquivo, mas eu quero mostrar a **imagem** em outra div.
Comment: @FelipeStoker se não entender a resposta comente.
Answer: Olá, eu utilizo os componentes da Kendo UI, veja o exemplo deles aqui, mas também tem exemplos na W3Schools. Veja os dois que vai te ajudar.
Answer: Você pode utilizar a classe FileReader para ler a dataurl da imagem e jogar na div, que nesse exemplo meu, é uma tag  mesmo
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};

E o código do HTML para isso:

<input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" />


How can a completed match become a walkover?

Question: During yesterday 2018 World Cup's match between Panama and Tunisia, a Polish-speaking sport commentator said that one of these countries (didn't hear exactly which one) had a football match with Cape Verde team which they lost and which was later ruled out as a walkover.
How can an already played match, lost by one of teams, later be declared walkover?
So far (up until yesterday) I was more than sure that a walkover can only happen when -- as name suggests -- one of the teams don't even show up to play the game.
Side question: About exactly which match Polish commentator was talking about?
Comment: It is quite likely that you are talking about a match in [2014 FIFA World Cup qualification](https://en.wikipedia.org/wiki/2014_FIFA_World_Cup_qualification_%E2%80%93_CAF_Second_Round). You can find more informatin *about this specific decision* in the linked Wikipedia article. The decision was related to [Fernando Varela](https://en.wikipedia.org/wiki/Fernando_Varela_(Cape_Verdean_footballer)) playing for Cape Verde during his suspension.
Comment: Being a walkover has nothing to do with whether the match counts as legitimate or was played. What you're thinking of, is called a *default*.
Answer: Here's what Wikipedia article on the term walkover suggests:

A walkover is the awarding of a victory to a contestant because there
  are no other contestants or the other contestants have been
  disqualified or have forfeited.

So,

How can an already played match, lost by one of teams, later be
  declared walkover?

Easy, if it's later identified that a team fielded an ineligible player, or due to crowd violence, etc.

Side question: About exactly which match Polish commentator was
  talking about?

As @Martin pointed out in the comments, most probably the commentator was referring to the incident of Fernando Varela playing for Cape Verde against Tunisia during his suspension.


Frobenius Norm to L2 norm Problem

Question: Here is the problem: if $v^1$, $v^2$, ..., $v^d$ is an orthonormal basis in $\mathbb{R}^d$, then show that
$$
||A - A\sum_{i = 1}^k v^i(v^i)^T ||^2_F = \sum_{i = k+1}^d||Av^i ||_2^2.
$$
I am having trouble understanding this step of a longer proof.  The text that I got this from just says that this holds because $v^1$, $v^2$, ..., $v^d$ is an orthonormal basis of $\mathbb{R}^d$.
Answer: since both norms are invariant under an orthogonal change of coordinates, we may take the $v_i$ to be the standard basis. if we write $e_j$ for the row vector $(e^j)^T$, then the matrix $A'(k)$ defined by:
$$
A'(k)=A' - \sum_{j=1}^k A'e^j e_j
$$
is simply $A'$ with its first $k$ columns set to zero.
for a real, square matrix, the square of the Frobenius norm is the sum of the squared $L_2$ magnitudes of its columns. so in the statement you wish to demonstrate, the $LHS$ is the sum of the squared $L_2$ norms of its columns indexed from $k+1$ to $d$.
on the RHS, the sum $\sum_{j=k+1}^d ||A'e^j||^2$ is the same thing, expressed directly.
Answer: Since $v^i$ is an orthonormal basis, the matrix $V:=[v^1,\ldots,v^d]$ is orthogonal, that is,
$$
VV^T=\sum_{i=1}^d v^i(v^i)^T=I,
$$
where $I$ is the identity matrix. So,
$$
A=AVV^T=A\sum_{i=1}^d v^i(v^i)^T=A\sum_{i=1}^k v^i(v^i)^T+\sum_{i=k+1}^d Av^i(v^i)^T,
$$
which gives
$$
A-A\sum_{i=1}^k v^i(v^i)^T=\sum_{i=k+1}^d Av^i(v^i)^T.
$$
It remains to find the expression for the Frobenius norm of the right-hand side. Set $W:=[v^{k+1},\ldots,v^d]$. Since $v^{k+1},\ldots,v^d$ are orthonormal, $W^TW=I$. Then using $\|X\|_F^2=\mathrm{trace}(XX^T)$, we get
$$
\begin{split}
\left\|\sum_{i=k+1}^d Av^i(v^i)^T\right\|_F^2&=\|AWW^T\|_F^2=\mathrm{trace}[(AWW^T)(AWW^T)^T]\\&=\mathrm{trace}(AWW^TWW^TA^T)=\mathrm{trace}(AWW^TA^T)\\&=\mathrm{trace}[(AW)(AW)^T]=\|AW\|_F^2\\&=\sum_{i=k+1}^d\|Av^i\|_2^2.
\end{split}
$$

Frobenius Norm to L2 norm Problem


Caching repository object or data results selectively

Question: I've been looking into implementing caching at Repository level using the .NET 4.0 Caching features or via a third party abstraction interface like this one and I've just run into an issue where I will have to support two use cases.
My application might be split in multiple areas, for instance the Admin area and the User frontend (website frontend). I don't want any caching to take place in the Admin area, Admins should always have the latest refreshed data displayed to them.
now, do I have to refactor all my repository methods to take in a parameter whether to return the cached results or not? Are there any other options?
Comment: What about have a separate repositories, "front end" if you will that is using caching and admin and then you can have both without parameter, tho i admit that is a not a best solution
Comment: it's actually not that bad of a solution paired with the advanced injection logic that IoC containers provide
Comment: Also you can have parameter injection if you are using Ninject :)
Answer: You could do the caching at the controller level, not at the repositories. This way in the admin area controllers you will always query the repository to get fresh data and in the others you will cache the results. If you absolutely need to do the caching of the objects at the repository layer you need an additional parameter to indicate whether the call is being made from the Admin area or not. Or you could also use a DI framework such as NInject which allows you to pass parameters from the HttpContext to dependencies that are allocated per request lifetime. So you could inject the area RouteData parameter to your repository's constructor.
Comment: Two repositories? Cached and not cached and switch between them via Ninject DI? that's something I just thought of..
Answer: There are various levels of caching that can be applied since you are using ASP.NET. I would not go about re-inventing the wheel if we have it already there.
We have:

ASP.NET server caching
ASP.NET output caching on server (using [OutputCache] on the action)
ASP.NET output caching on client (using [OutputCache] on the action)

Entity Framework or other ORMs can do the caching as well. So I would say use what is already there until you are sure it does not do what you need.

UPDATE
If you have to do it at repository, I would suggest use Dependency injection features to inject the right repository (one with caching or no-caching)
Comment: I am aware of these but my scenario requires caching at the repository level.


nodeaccess configuration problems

Question: I created a view that I called gallery (in Drupal 7) which links to a number of sub galleries (http://quaaoutlodge.com/gallery). The sub galleries are of content type gallery.
So, I installed the nodeaccess module because the galleries and the gallery main page should only be accessible by my GalleryViewer  (and GalleryEditor) so I set the Gallery node type up accordingly (no checks for anonymous user). I saved grants and rebuilt permissions. Now, even tho I did the above, any user caan browse my gallery types that are linked from http://quaaoutlodge.com/gallery. Why is this? What am I doing wrong? :o
Comment: I think you have to set the permission inside the Views `BLOCK SETTINGS > Access`
Comment: @ninjascorner Thanks! That did it for my gallery view, yes! Thank you, copy and paste this answer to answers and you get your check mark... even tho it didn't really address my node access issue - do you also know how I resolve that by any chance?
Answer: You have to set the permission inside the Views BLOCK SETTINGS > Access

nodeaccess configuration problems


How do you delete a content type's URL aliases in bulk?

Question: I have a content type where I want to delete all of its URL aliases in bulk. Currently the pathauto url alias page only has the option to delete all content url aliases regardless of what type it is.
How can you delete url aliases in bulk matching only a specific content type?
Also would it be okay to delete the url_aliases via phpmyadmin? I'm not sure if the url_aliases table is linked to something else.
Comment: is there a particular reason you can't bulk delete all content aliases and bulk regenerate them ? If there is, see https://drupal.org/node/144904
Comment: because I have some manually entered url aliases associated with some of the content.
Answer: I'd do it as an SQL query. Run as a SELECT first, to verify that all is well:
<code> SELECT alias FROM node n JOIN url_alias u ON CONCAT('node/', n.nid) =
 u.source WHERE n.type='my_type'
</code>
then edit it to make it a DELETE:
<code> DELETE u  FROM node n JOIN url_alias u ON CONCAT('node/', n.nid) =
 u.source WHERE n.type='my_type'
</code>
Comment: just what i needed. fyi for those that dont know. run this via drush sqlq ' ' or phpmyadmin. thx.
Answer: I'd go with Views Bulk Operations.

set the pathauto path for the content type to the default you want, but don't bulk update
create simple view for the content type you're interested in
add the field Bulk Opertations: Content
Under Bulk Operations Settings check Enable "Select all items on all pages"
select Update Node Alias
add filters as required

navigate to the view page, select all, uncheck any special cases, and give it a whirl
but maybe backup first
Comment: This works! **NOTE:** do not check the box "Enqueue the operation instead of executing it directly" when configuring the Bulk Opertations options
Comment: This will update the node aliases but not deleting url aliases...


How can I implement connected jcarousel views?

Question: I know drupal has jcarousel and  views slideshow modules and work with each of them some times, I want to create something like this link ( images list below with carousel and when click on each one the big image changed), I know  I can create  a slide show that thumbnail image be below of big image and when click on them the big image changed (but this is not carousel, it means all images listed below big image without next and prev ),
Anybody has idea how can I implement connected-carousels in views?
Answer: You need Views Slideshow JCarousel which provides the same functionality. It will add jcarousel pager in slideshow settings. ;)
Answer: You can use the Views Slideshow JCarousel module, it is a combination of jcarousel and slideshow modules.


SQL : Can't grab values in descending order when using group by

Question: im joining and retrieving values from two tables using the below query. It displays the values in descending order.
Leads
63697       Ben
63698       Ben
63699       Ben
63700       Ben
63701       Ben

log

2   63697       Ben         10%     Qualifying
3   63697       Ben         20%     Qualifying
4   63697       Ben         30%     Qualifying
6   63698       Ben         30%     Qualifying
8   63698       Ben     80%     Quoted
10  63698       Ben         70%     Quoted

I want to display,
63697       Ben         30%     Qualifying
63698       Ben         70%     Quoted
63699       Ben
63700       Ben
63701       Ben

The problem is that when I use the query,
SELECT leads.id,leads.name, log.prob, log.current_stage FROM leads LEFT JOIN log ON log.leadid = leads.id WHERE leads.name = '$name' ORDER BY log.id DESC

It displays all the details for the log table in descending order. But when I try to group them,
SELECT leads.id,leads.name, log.prob, log.current_stage FROM leads LEFT JOIN log ON log.leadid = leads.id WHERE leads.name = '$name' GROUP BY log.leadid ORDER BY log.id DESC

It grabs the values in the ascending order from the logs table
63697       Ben         10%     Qualifying
63698       Ben         30%     Qualifying
63699       Ben
63700       Ben
63701       Ben

Can someone tell me what am I doing wrong here?
Answer: SELECT * FROM (
SELECT leads.id,leads.name, log.prob, log.current_stage, log.id AS logid FROM leads LEFT JOIN log ON log.leadid = leads.id WHERE leads.name = '$name' GROUP BY log.leadid
) ORDER BY logid DESC

Have seen this quite often, just wrap it in a superquery as shown.
Comment: Thanks alot.... but i had to move the group by outside the wrap and order by inside the subquery to get it working... :)
Answer: You are ordering by log.id, which is not a field of your select. You cannot do this as the ORDER BY is evaluated after the SELECT directive.
Change ORDER BY log.id for ORDER BY leads.id, which is the only identifier I see in your SELECT directive.

SQL : Can’t grab values in descending order when using group by


Updating tables with Linq expressions

Question: Most of the examples I've found deal with Linq to entities, which is not what I need. I have a standard DataTable which I need to modify before returning to the caller. I can iterate over the normal Table.Rows collection or do something like this with the new extension methods:
foreach (var x in table.AsEnumerable()) {
    if (x.Field<int>("SomeField") > SomeValue)
        x.SetField<string>("OtherField", "OtherValue");
}

But I'm still manually looping through the entire row collection. Not necessarily a big deal, but I'm wondering if there's a more elegant way to accomplish this with Linq somehow, in the sense that I need to create an expression that iterates over the results of a query and performs an arbitrary action, rather than just select elements from the container being enumerated.
Answer: I think what you're wondering is if there's some sort of extension method like
stuff.ForEach(x => x.Value = "new value");

Unfortunately, there is no such thing. When I began using LINQ to SQL, I wanted the same thing. But unfortunately, you must use a for loop.
Comment: Looks like you get the 'tumbleweed' award, if there's one :D Thanks for the comment... yeah, I pretty much figured there was no way to do that, but my Linq-fu was a bit weaker back then.
Comment: Ha! I just realized this was asked almost a year ago. And MS still hasn't implemented the ForEach method.

Updating tables with Linq expressions


No Schema type for mysql type datetime error while creating view to show webform submissions

Question: I am attempting to display webform submitted data in view. For that I have used Webform MYSQL Views and Data module. And I am referring tutorial from here: http://drupal.org/node/1658784. The problem is when I created MySQL views for given webform, it has created view with Submitted column as datetime field.
Now when I go to Structure > Data Table > Adopt Tables and selects the created view, it is giving error of "no Schema type for mysql type datetime".
I googled for it, but didn't find any solution yet, any suggestion how can I overcome this error.
-- Thanks for your time.
Answer: You likely already resolved this, but I just ran into the same issue.  Here's how I resolved it:
I applied the patches to the Schema module listed here: http://drupal.org/node/1237974.
This got rid of the error, but because i had a db_prefix on my tables, I could not adopt them.  In order to get that working, I tried the patches here (http://drupal.org/node/894074#comment-6459584).  It didn't work for my view, so I logged in via PHPMYAdmin and removed the prefix dr_ from the webform view (instead of dr_webform_myviewname, it's now webform_myviewname).  This allowed me to adopt it.
I'm not saying it was pretty, but it is working now.
KMT


Pegando dados específicos de um "(response.body)"

Question: Tenho esse código:
class _EstabelecimentosPageState extends State<EstabelecimentosPage> {
  final String url = codeUrl;

@override void
 initState() {
  super.initState();
  this.getJsonData();
 }

 Future<String> getJsonData() async {
  var response = await http.get(url);
  print("return " + response.body);
  setState(() {
   var convertDataToJson = json.decode(response.body);
   var data = convertDataToJson['data']['codigo'];
   return data;
  });

 return "Success";
 }
}

Que retorna um
{"status":"success","data":{"codigo":"código"}}

Preciso pegar só o "código" dentro do "data", mas não estou conseguindo, desde já agradeço qualquer ajuda, sou iniciante e isso está me dando me dando nos nervos porque acho que é um erro simples, mas não consigo encontrar.
Answer: Consegui:
Future<String> getJsonData() async {
 var response = await http.get(url);
 if (response.statusCode == 200) {
   var convertDataToJson = json.decode(response.body);
   var data = convertDataToJson['data']['codigo'];
   print(data);
   return data;
 } else {
   throw ('error ${response.statusCode}');
 }
}


Views and Controllers invisible to each other? How can this be?

Question: I have read that Views and Controllers should be invisible to each other.
How does the controller then listen for say a button click in the UI view?
Surely the controller needs to know about the view to addEventListeners or the UI view needs to call functions in the controller, or dispatch events to the controller.
Comment: it's common to use a static dispatcher class for such cases
Comment: ah i see... if i understand correctly that is. so for each view you have a specific static dispatcher, with all the various ui options, triggered by the view ui? that are listened for by the controller or mediator?
Comment: my current mvc is not so pure ^^ we use a static `EventDispatcher` instance so it's possible to broadcast an event that'd be heard by any instance subscribed wherever it is. however imho using `[Bindable]` for things like 'PlayerModel.health changed -> update PlayerHealthBar.value' is a better practice
Answer: My only experience of MVC is with using the robotlegs framework so I'll try explain my approach when using this framework
My views only use native flash events (MouseEvent.CLICK etc) which are listened for in the mediator for the view. When the mediator receives a native event it will then dispatch an application specific event, LoginEvent.LOGIN for example,  which can be mapped to then fire a command using the command map on your context.
Sorry if that doesn't make much sense, but basically your views fire native events and your mediators will listen for these native events and then fire application specific events which in turn run your commands. You use the mediator as the 'ears' for your view and keep any logic out of them. The application context allows you to fire commands whenever certain events occur so your views and commands are seperated.
Comment: I think I understand - but how does the click listener differentiate between the different ui elements? do you use something like e.target.name (login_btn, logout_btn etc)?
Comment: If you had three buttons in your view you could just fire a different custom event for each button and listen for these in the mediator, or you could examine the payload of the native flash event in the medator to decide what you want to do with it.
Comment: The benefit of using native events is that you could take your view and use it in another project and not have to change any of the custom events, your view is 'dumb' to any project specific events and only handles native events. Your mediator is the only thing tied to that specific project. Sorry probably not the best explanation.


Sight reading outside the piano

Question: It is hard for me to practice lately the piano. But i really want to sight read well and keep advancing, even if it is outside of it.

Is it possible to sight read outside the piano by reading piano pieces from books?
How would you suggest to approach such technique that will enable me when getting back to the piano to be able to play it easily?
Can you please recommend me on books for advanced beginner? For example moonlight sonata is the kind of piece that i can read well.

Thank you!!!
Comment: By any chance, can you sight sing?
Comment: I don't see, how you define *sight reading*; if you don't play what you read, how is the successful reading confirmed? (WIth the instrument, your ears would confirm that.)
Comment: Reading sheet music learning to identify notes patterns pitch and the piano pattern. I know it is using imagination and the ability to hear the music.  @dekkadeci i can not sight sing but i am a singer.
Comment: Do you mean that you have some physical pain when playing, currently, or that you don't have access to a piano currently?  If it's the latter, you may want to spend $15 on a melodica, and work with a piano sight reading book or series of books.
Answer: Simple answer - learn how to sight-sing. As you are already a singer, it's a valuable weapon to own. If there's an instrument around to give you pitch, then great, but if not, it doesn't really matter. Not having absolute pitch is no excuse! Look at the dots (one hand at a time), ignore chords - they're much too hard to sing... And get used to identifying intervals - any note following another on the line/space above will be a third. There are two in common use - major and minor. Get used to the difference in sound. Any two notes on lines with another line between are fifths (same for spaces). Get used to how they sound consecutively.
Learn tonic sol-fa, and be able to sing doh>soh, mi>ti, etc. That works in any key, and will help when you are back on keys.
Answer: Even I am a great protagonist of solfege and ear training I would like to complete the other answers and comments telling what I still practice everyday (even independent of the absolute sound and pitch of the notes I'm reading!) Of course the pitch of the note and the question which key you have to press down is the most important aspect aside of the note length and the fingerings. But there are some other things you can practice without out sitting at the piano:

analyzing the piece: parts, motifs, phrases, figures (give them a number, a name, a term (formal analysis)
analyzing the chords: chord names and Roman numbers (harmonic and functional analysis)
analyzing the rhythm:  make a reduction of the rhythmic 8( and also of the melodic motifs, play the rhythm without an instrument (practicing the l. and r. hands just playing with or without fingerings).

In German we have an expression for this kind of training:
"Trocken-Schwimmen" (= "dry swimming", that means swimming without water, as some trainers teach swimming outside of the pool. That's the way I've taught myself crawling at the age of 50!)
You can call this also brain-gym, cross-crawl, mental training, (mind that a good training of your memory also is a condition for sight reading.)
What I'm proposing is what I do everyday - and night! (with and without sheet music ...)
You can imagine that the benefit for sight reading must be great, when you look at the sheet music and you can easily detect the harmony, the chords, the rhythmic patterns, because  you have a term for each element, phenomena  and appearance and you also have the skills to cope the technical problems.

Can you please recommend me on books for advanced beginner? For example moonlight sonata is the kind of piece that i can read well.

The music I am learning or practicing is still the same I was playing when I started piano playing: Bach Inventions and Bela Bartok Mikrokosmos.
At the moment I practice these elements with the invention in a-minor and BWV 999.
(A technique, that helps me to develop my skills is also to transpose these pieces in C-major (as this is to me like a root scale), or changing the #-assignments in flats (parallel key) or playing it through all keys. A-propos scales: of course playing scales and chords in all keys is a very helpful to acquire the skills of sight reading, fingerings and all kind of technical (rhythmical and melodic) problems.
I train first the pattern with the hands, than with the fingers (if possible):
BWV 999 is a good example. (about the voice leading and the chords I still discover new aspects ... after playing this piece for 10 years now! but I know every single new aspect I find out will be a benefit when reading a new piece (transfer of learning!)
What I'm also doing is: I notate the new insight as a memo with the date and  on the sheet or in a booklet. So I get a whole diary of the development of my skills I have got and my discoveries I have got.
Try out the preludes of the WTC (C-major, C-minor, C#-major, D-major, D-minor), the Inventions and sinfonias, and later the fugues. Suddenly you will see that you can sight read Chopin.
Comment: I really enjoyed reading your detailed answer. this is brilliant. will follow. BTW: sight-reading without sheet music? how do you do that?
Comment: by memorizing short puzzles: 2-4 bars and fotocopying in my brain!
I've learnt e.g. the violin-concerto in a-minor BWV 1041 this way by heart (just the solo part but playing on Euphonium). I memorize it  by assigning each bar to a finger and counting to 24 (introduction). Another trick is: I imagine each bar on a carree (field) of a chessboard. Reading without sheet music: The same way I'm training other clefs (tenor and alto clef -> just imagination with closed eyes... so we come to composition: if you try to notate your own music - or any other melody you have in mind - you can read it too!
Comment: brilliant. you sound like a very smart person:). thanks a lot. ( I think I will start with the inventions. as I really love bach and it is more challenging than the bartok)
Answer: I am aware of classical guitarists who are able to "read" a piece of music without their instrument and then later play it.  But these individuals have decades of experience before being able to do this and possibly were geniuses.
Sight reading involves merging multiple skills.  It can be frustrating to get stuck or not make progress but the key to getting good at sight reading is to do it every day, like reading the news paper.
In order to translate what you see to a movement or action in your hands you must have developed some hand technique.  So, without that what you read will not trigger the correct movements.  However these skills can be developed and practiced separately to some extent.  You also want to be able to hear what you are reading even without an instrument.  If you can play by ear and hear what you see on the sheet music then the connection will be triggered in the mind.
I am not a piano player but a guitarist and I can relate some exercises that I think apply.  One is to literally verbalize the note names while reading melodic lines from sheet music.  I have a couple sight reading books for guitar that recommend this.  It's just a way to reinforce one of many neural pathways that get triggered when sight reading.  You can take a line of music from anything and do this.  Read it at a steady pace, read it backwards, turn it upside down and read again, assuming the staff lines are upright (e.g. f is the top line of the Treble clef regardless of orientation).  Some people have a hard time saying the alphabet backwards.  Try identifying descending scale notes by name if this is a problem.  Another exercise (for guitarists) that I've seen is to take simple tetrachord patterns and touching the finger corresponding to each note to your thumb (for the fretting hand).  For example there are 2 basic fingering patterns for the sequence (Do, Re, Mi, Fa) on of which is (2, 4) on the E, A, or D string followed by (1, 2) on the next string.  Simple two finger sequences.  The exercise involves "reading" simple melodic sequences from the tetrachord while tapping the correct finger to he thumb while you read.  There has got to be a way to do this with a virtual piano as well.  In the same exercise you can add the extra dimension of vocalizing the notes as you tap.  This reinforces the pathway of connecting a sound to a body movement.  In time you will notice that when you see sheet music you hear what the notes are in your head, and your hand feels what to do.  In time all this translates to better sight reading skills.
As many have suggested learning to sight sing also helps develop the ear-sheet music connection.  But that won't necessarily develop the hand-ear connection as that is unique to each instrument.
You can also achieve the ability to hear what you read by using ear training software (that helped me but every person is different).  I used Ear Master Pro.  It shows you the notes being played for certain exercises and even when it doesn't it will show you the notes on a staff after you enter your guess for intervals etc, playing the note as it flashes the note on the staff.  Over time you notice that you can hear the note you see without it being played.  (At least I hope that's normal, ;-)).
Answer: I could either give @Tim's answer a significant edit, or write my own answer -- here goes.  I'm going to focus on how to learn to sight sing.
Buy or borrow a sight singing textbook such as what is used in college music programs' sight singing courses.  I think you will be able to do this through self-study if you have a good book to work with.
Here's an Amazon list: https://www.amazon.com/s?k=sightsinging&ref=nb_sb_noss_2
Choose something modern, and choose something that appeals to you.  Don't move too quickly through the book.  You probably won't need to get the whole way through the book to be able to say mission accomplished.
I had to take a one-credit sight singing course for my Bachelor's in music.  I got much more out of that course than most of my non-performance courses.  Working your way through a book of this type will help your musicianship immeasurably.

Adding a bit: as you learn to sight sing, you will also learn to visualize (but with the sense of hearing, rather than the sense of sight). You will learn to hear in your mind's ear what you see on the page. You will be able to look at a phrase of written music and hear it in your head. Learning to do this is a process. Sight singing books walk you through this learning process step by step with lots of exercises for each step in the process.

Sight reading outside the piano


Is there an international color standard for displaying readings

Question: I have an application that shows gauges for several different readings within a system. When the reading goes above scale, the gauge goes red.
My supervisor says the international standard color for when a reading goes below minimum scale is yellow. Is this correct? I was using blue up until this point and blue fits in much better with my color scheme.
If this is the wrong place for this type of question, could someone point me in the right direction? Thanks.
Answer: I'd have thought it would be green...
Certainly, in the UK, on an aircraft, when the temperatures and pressures are within limits, the needle is in the green section on the gauge.
Comment: Sorry, I meant below minimum scale. I've edited the question.
Comment: I'd personally hazard a guess at white, but that's not sourced from any sort of international guidelines unfortunately.


ui problems when changing canvas localScale in coroutine in Unity

Question: I got a problem when I was changing the localScale of Canvas.
First of all, I want to design a function of to buy equipments in a tank war game, so I add a canvas to show the equipments. The structure of the canvas shows as follows:
canvas ui structure
At the beginning of the game, I change the localScale of the canvas from (0,0,0) to (1,1,1) over a period of time in a coroutine. The code shows as follows:
<code>private IEnumerator DampCanvas(){
        float dis = Vector3.Distance (rect.localScale, Vector3.one);
        while (dis >= threshold) {
            rect.localScale =
                Vector3.SmoothDamp (rect.localScale, Vector3.one, ref eqpsSmoothVec, eqpsSmoothTime);
            dis = Vector3.Distance (rect.localScale, Vector3.one);
            yield return null;
        }
        rect.localScale = Vector3.one;
    }
</code>
The coroutine works ok, but I did something as folows before the coroutine:

Add all equipments of default choosen type(Attack here) on the ui.
Add all equipments of the current tank has bought on the ui

But the problems is the equipments had added on the ui do not show, but I do see the ui object in Hierarchy view.
beginning of the game
hierarchy view
I just learn unity for a short time and I don't konw what happened.Can anybody help me?
Comment: I would check that the not shown gamobjects are enabled (enable checkbox at the top left of the inspector) + their render componenets are enabled too. Also that they dont have any parent with scale = (0,0,0) in the scene hierarchy (transform parameters are parent relative, so if a parent has a scale of (0,0,0) this will be passed down to children, so children wont show)
Comment: @RustyBucketBay thank you !!! Just as you said, the localScale of equipments added is (0,0,0), passed down from the canvas. It works well now. Thank you !!!
Comment: I'm glad that helped. You can give that as the accepted anwer if that worked ;)
Answer: I would check that the not shown gamobjects are enabled (enable checkbox at the top left of the inspector) + their render componenets are enabled too. Also that they dont have any parent with scale = (0,0,0) in the scene hierarchy (transform parameters are parent relative, so if a parent has a scale of (0,0,0) this will be passed down to children, so children wont show)


Filter nodes matching user account field [list (text)] using different field names but same key

Question: There is a field of type list (text) [field_list_user] on user accounts and a field of type list (text) [field_list_node] on nodes. Both fields have exactly the same keys but different labels [and field names]. Any content of the site can be authored by users.
Is it possible to create a block with nodes for a currently logged-in user filtered like: value (key) of field_list_user = field_list_node?
Comment: Have a look at [Equi Join](https://www.drupal.org/project/equi_join)
Answer: I don't think there is module to do a filter that compare 2 arbitrary value but you can add a php filter using Views PHP module
Then, you can create a PHP filter in your view.
Someone write an example that is quite similar to what you need : https://drupal.stackexchange.com/a/44100/36824
Comment: I thought so. I've tried to achieve this using relations and contextual filters in Views but couldn't produce a block like that. Thanks for your advice.


How to combine two sets of samples from an unnormalised distribution?

Question: Imagine that I have an unnormalised distribution $P$ with density function $p(x)$ for $x \in \mathbb{R}^d$. $P$ has two well-separated modes and there are two sets of i.i.d. samples with the size $n$ that each of them has been taken from one of the modes. I would like to know how I can combine these samples in an unbiased way.  In other words, let $\hat{\mu}_i$ be the empirical estimation of $\mu_i$, then I would like to find the $w_i$ that minimises the following error:
$\min \quad (\sum_{i}w_i(\hat{\mu}_i-\mu_i))^2$
Thanks for your help.
Cheers
Comment: Please explain more precisely how you can "sample ... from one of the modes." The language sounds like you might have a *mixture*.  This is crucial because the relative amounts of the components in the mixture determine the solution, but you haven't provided any information about those amounts.
Comment: Then it would appear you have insufficient information to combine the results in any objective way.
Comment: If you have *all* of $p$, then there's no question to be asked and your samples aren't needed: simply normalize $p$ to integrate to unity.
Comment: Thanks, consider my problem as a stratified sampling that we do not know the weights of each strata.
Comment: But I have $p(x)$; is not possible to use it to find the weights ?
Comment: $\mu_i$ is the true mean value of the $i^{th}$ mode
Answer: Here is a solution (see section 3.3) which uses the Renyi entropy:
https://arxiv.org/pdf/1806.03816.pdf
According to the paper, assuming that we have the Renyi entropy of the samples from each mode and the $p(x_i)$ for those samples, we can find the weight of each mode and the resulting estimator is asymptotically unbiased.
In practice, however, the problem/challenge is how to find the entropy: The authors suggested to use  the Information Theoretical Estimators package [1] for estimating the entropy.
[1] Szabó, Zoltán. Information theoretical estimators toolbox. Journal of Machine Learning Research,15:283–287, 2014


Can the voice be trained to sound tremulous when singing?

Question: I was inspired to ask this after I've listened to some KALEO, whose lead singer's voice has an interesting tremor that compliments the blues-inspired style.
I'd like to give this live performance as an example (I recommend listening to the whole performance for enjoyment):

with the following timestamps:

2:57-3:15 (3:10 more powerful and highlighted)
4:09
4:15

I'm sorry if it's a very basic technique. I just want to know how's it called, if it's achievable(or just something you're born with), or a throat disease (like the google results say).
Thank you for your time!
Another performance that highlights the style mentioned:
Comment: Trying to catch his tremolo, but can't.
Answer: Tremolo and vibrato
Tremolo deals with change in volume, whereas vibrato deals with change in pitch. For vibrato you have to tense a muscle around the vocal chords periodically, that is easy.
Change in volume: airflow or coarticulation
For a change in volume, maintaining the same vowel, you'd need to vary the airflow through the vocal chords periodically. When you manipulate volume using the mouth, you will get another vowel, which is not appropriate for most songs. I would say it has to be air volume.
..to train them
Stop smoking
For tremolo, e.g. how fast can you say A-A-A-A-A
For vibrato, refer to the video posted in Brian Towers' answer
Making howling, crying or laughing sounds can invoke both tremolo and vibrato.
Answer:
I just want to know how's it called

It is called "vibrato". It is a variation in pitch and, usually also, volume, which, as you note, makes the singing sound more interesting.

if it's achievable

Yes. Most (All?) classically trained singers use vibrato. There are YouTube videos out there which describe the exercises you can do to develop vibrato. Here is one example which explains what vibrato is and then gives exercise which help you develop the variations in first volume then pitch:
Comment: There's an awful lot of (a lot of awful?) opera singers who use so much vibrato it's difficult to decide what the actual note is they're supposed to be singing. Tremolo works better, but I'm convinced there's another sort, which changes tone, somehow.
Comment: I was referring to that crispy almost chocked slide happening at 4:09 when he sings the 2nd part of the word 'shame', or at 4:15 where he sings 'crossed MY MIND'.
Comment: Tremolo deals with change in volume, whereas vibrato deals with change in pitch. For vibrato you have to tense a muscle around the vocal chords periodically, that is easy. For a change in volume, you'd somehow have to vary the airflow through the vocal chords. No idea if that is trained with the same techniques, but there's really a difference. Crying and laughing can involve tremolo *and* vibrato.


how to find out how many meters an object is.

Question: I am making an object and i need to figure out a way to trick the brain in a VR game i am making but i cant figure out this simple problem.
Standing on a ship 18km in length the characters avatar will be 20 m tall since i cannot change the actual dimensions of the character or the room i need to scale everything to make it look to the character that he is 20 m tall. How would i find out the scaling i am going to need for the 18km surface?
more information* edit
A person lets just say is 6 feet is not tall enough for what i need him to be. I need him to be 20 m tall and picture it being a humanoid so he would see from the high of the 20 m or 19.5 m. Because the real person is 6 feet i would need to scale the ship as if the person was 20 m tall.
What is the length of the ship if the avatar was 20 m tall. when the avatar starts at 6 feet tall.
i have no idea how to do this.
Comment: You need to post some more details to get a good answer. In your game what does it mean to be 20m (other than it's about $1/1000$ than the length of the ship)? Are there other objects with heights on the order of 20m? What viewpoint will one view the avatar? From high above? from approximately 20m high? from 1cm high? From 1cm high the surface will look infinitely long and the avatar will be very tall. At 1 end of 18km surface from 20m high avatar will look same height as viewer and  other end of the surface would be similar to a 6ft man looking at end of 1 mile surface (1:1000 ratio)
Comment: How about now is this enough information?
Comment: I still don't understand. You already said ship was 18km, but your edit asks how long ship is. Do you want to know that given an avatar of 6ft and a ship that is 18km, how to scale the ship if you scale the avatar to 20m? If so then it would be $18km * 20m/6ft$
Answer: Your lengths should simply be scaled reciprocally. That is: If your Avatar is ten times as tall as normal, scale everything else down by a factor of $\frac1{10}$.
There are some caveats, though: Be sure to adjust the physics accordingly. If a 2m person drops a ball from the height of his head, the ball will hit the ground after 0.45 seconds, but if a 20m person does the same it takes $\sqrt{10}$ times as long (1.4 seconds), just as if the gravitational acceleration was 0.98 m/s² instead of 9.8 m/s².


Loop over Observable

Question: In my frontend part of application use a method
this.knowledgeMan.getUserAllowedCases(Item.ItemNumber)

which returns Observable. On my backend part, this method returns a List<String>.
My question is: how do I get to loop over the elements of this list of Strings?
Answer: If you have an observable you have to subscribe to it to get the actual value. Within subscribtion its up to you, here you can map or loop over your values.
this.knowledgeMan.getUserAllowedCases(Item.ItemNumber).subscribe(allowedCases => {
  allowedCases.map(allowedCase => {
    // your code here
  });
});

Answer: If you are using this List<String> observable to show on the HTML part you can use a combination of async and *ngFor to get the desired result.
//in your html for example

 {{ item }}

//in your component

//usual angular stuff
export class MyComponent implements OnInit {
  data$: Observable<String[]>;
  constructor(private knowledgeMan: YourServiceInterface){}

  ngOnInit() {
    data$ = this.knowledgeMan.getUserAllowedCases(Item.ItemNumber);
  }
}

If you are just doing this to compute some value you can do this following.
this.knowledgeMan.getUserAllowedCases(Item.ItemNumber).pipe(
  flatMap(),
  map(item => //do something with item here)
).subscribe();

Answer: If as you say, getUserAllowedCases returns string[] then you can do this:
this.knowledgeMan.getUserAllowedCases(Item.ItemNumber).subscribe(x => {
  // assuming x is string[]
  for (const item of x) {
     // use item
  }
});

Loop over Observable


How to store all outgoing mails from postfix in DB (MYSQL)

Question: I have a postfix setup for my web server and I want to store every outgoing email from the server to a database. Does any one know how I can achieve this. FYI I just use this server to send emails and I use google Apps to receive emails.
Answer: Youre going to have to do several things

Use the always_bcc setting to fork a copy of the emails to an alternate destination (what you use really doesnt matter, this is just for item #3 below)
Set up a pipe transport in your master.cf file which will receive the emails and store them in the database. You are going to have to write this utility/script yourself.
Use transport_maps to redirect mail for that always_bcc address to the transport you defined in master.cf


Running Express route

Question: I have the following snippet of code and when I access the local host I get an error: Cannot GET /
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.send("function has started");
});

express().listen(3001);

module.exports = router;

Comment: You have to hook your router into your Express app object with `app.use(router)`.  That's why all Express apps create an `app` object and hold onto it so that they can register routes in it.
Answer: var express = require('express')
var app = express()
app.get('/', function (req, res) {
  res.send('GET request to the homepage')
})

app.listen(3001)

This should be fine
Comment: There is no need for a router since that is already built into the app. This answer is the simplest and cleanest!!
Answer: If you want to use the router, you need to use the use method example (app.use('/', router):
var express = require('express');
var router = express.Router();

var app = express()

/* GET home page. */
router.get('/', function (req, res, next) {
  res.send("function has started");
});

app.use('/', router)

app.listen(3001);

Running Express route


How to add a comment box in a view so that users can comment on it just like it displays in node

Question: I want to add a comment box in a view so that user can comment there also just like they do in specific node.
Comment: What version of Drupal?
Comment: I am using drupal 7
Comment: Ahh, I don't know how you would do it with D7. Sorry.
Comment: okay. No problem. You know with drupal 8
Answer: You can create a block display of the View, add that block to a node, and activate comments on that node.


Shared Hosting Mysql Quota

Question: Since MySql does not have a built in quota tool, I wonder how the Big Companies like Daddy and Gator and so on manage their limitations for users?
I was thinking about to use some kind of script to check if the db is over a certain size, but if someone imports a huge thing in, then what? Is there a limitations for how big dump can be imported in?
Comment: you don't limit the import, you run a job occasionally, that takes suitable action.
Comment: And if someone imports a dump over 1 GB? Just let them do it? When the script runs, it will get there.... I know the script has to run from cron constantly.
Comment: I have imported databases which are too big for the shared service I was using only to have them limited when the scrip runs.
Answer: Usually it's one of two methods:
1) Limit the disk space using a filesystem quota for the folder where the database file is hosted. This is easily accomplished using <code>/home</code> directories for each user and symbolic links to where MySQL looks for the database files.
2) A cron script runs every x minutes that checks for table sizes and revokes CREATE/INSERT statements for databases over the limit.
The second method won't prevent short-term abuse, but you can minimize impact by ensuring there's plenty of extra space and have policies in place to discourage abuse.
Comment: With Method #1 Have to configure quota for the disk for each folder containing mysql db files. Method #2 would allow users to upload gigantic databases. Is there a way to limit in mysql how big dump file can be imported? Like dump can not be larger than 1 GB ? To upload that over phpmyadmin would be hard anyway, but still... Is there such an option? Because with that It can be useful with the cron script.
Comment: Normally, phpmyadmin is limited by the PHP upload settings so it'd be difficult to accomplish anyway. `max_packet_size` in mysql's config can be tuned too.
Comment: @NathanC Can you write an example for method 1 since symbolic link from database folder to quoted directory will not include the size.

Shared Hosting Mysql Quota


Erro de Visualização na Página com código PHP

Question:
Alguém consegue ajudar-me a perceber o porquê de o código que está em baixo estar errado? Falta alguma parametrização para que este não apareça na página principal?
                <?php } if (isset($_POST['submitBtn'])){
            ?>

Resultado do Login:

            if ($error == "") {
            echo "Benvindo";
            echo "Click aqui para entrar.";
            }
            else echo $error;
            ?>

            <?php }
            ?>

Comment: Pode explicar melhor o problema? O que seria "este não apareça na página principal"? O próprio código PHP está sendo exibido? Se sim, você está executando o arquivo em um servidor com suporte a PHP?
Comment: Adicionei uma fotogradia, em que demonstra o que aparece na página. Supostamente este campo deveria de estar oculto, para quando fizermos um Login errado ele voltar à página inicial.
Comment: Forneça mais detalhes sobre o problema, assim fica complicado ajudar.  Coloque na pergunta uma parte maior do código.
Comment: Já é possível ajudar desta forma?
Comment: Impossível dizer com certeza. Ainda a pergunta não faz sentido. Mas já percebi que você está utilizando aspas duplas dentro da *string* no PHP; isso quebra a *string* e gera o resultado inesperado. Tente alterar para aspas simples: `echo "..."` (perceba as aspas simples no `href` do link).
Comment: Tente isso: `if ($error == "") { echo "Benvindo  Click aqui para entrar.";
            }`
Comment: Ainda não está funcionando.. eu vou colocar uma imagem mais nitida, pode ser que ajude.. o código é muito extenso para o poder colocar aqui
Comment: O problema que surge a seguir é que depois de fazer o login , a página não vai para a pretendida, mas se clicar onde diz "Click aqui para entrar.! aí já entra..
Comment: que começo é esse   `<?php }`
Answer: Adicione as tags do php, <?php e ?> para este trecho do código:
if ($error == "") {
 echo "Benvindo";
 echo "Click aqui para entrar.";
}
 else echo $error;

Comment: O problema que surge a seguir é que depois de fazer o login , a página não vai para a pretendida, mas se clicar onde diz "Click aqui para entrar.! aí já entra..
Answer: Estrutura do código está com um pequeno erro, o correto séria:
<?php } if (isset($_POST['submitBtn'])){ ?>

Resultado do Login:

       <?php
          if ($error == ""){
            echo "Benvindo";
            echo "Click aqui para entrar.";
          }else
            echo $error;
        ?>

        <?php } ?>


How to get maximum/minimum duration of all DagRun instances in Airflow?

Question: Is there a way to find the maximum/minimum or even an average duration of all DagRun instances in Airflow? - That is all dagruns from all dags not just one single dag.
I can't find anywhere to do this on the UI or even a page with a programmatic/command line example.
Answer: You can use airflow- api to get all dag_runs for dag and calculate statistics.
An example to get all dag_runs per dag and calc total time :
import datetime
import requests
from requests.auth import HTTPBasicAuth

airflow_server = "http://localhost:8080/api/v1/"
auth = HTTPBasicAuth("airflow", "airflow")

get_dags_url = f"{airflow_server}dags"
get_dag_params = {
    "limit": 100,
    "only_active": "true"
}

response = requests.get(get_dags_url, params=get_dag_params, auth=auth)
dags = response.json()["dags"]

get_dag_run_params = {
    "limit": 100,
}
for dag in dags:
    dag_id = dag["dag_id"]
    dag_run_url = f"{airflow_server}/dags/{dag_id}/dagRuns?limit=100&state=success"
    response = requests.get(dag_run_url, auth=auth)
    dag_runs = response.json()["dag_runs"]
    for dag_run in dag_runs:
        execution_date = datetime.datetime.fromisoformat(dag_run['execution_date'])
        end_date = datetime.datetime.fromisoformat(dag_run['end_date'])
        duration = end_date - execution_date
        duration_in_s = duration.total_seconds()
        print(duration_in_s)

Comment: I've been testing with this and it doesn't seem correct (you used start_date for end_date but I get what you meant). Using `dag_run.start_date` seems to get the datetime of the first ever dag run and for `dag_run.end_date` getting the latest dagrun datetime then calculates a duration between those two datetimes. So for example a dag that was created 5 days ago ends up having a duration of 5 days + whatever time difference in hours, minutes, seconds - rather than producing x seconds of the actual dagrun duration.
Comment: @pragmaticlearner, you are right, you should use execution_date instead of start_date (i fixed my answer). 10x
Answer: The easiest way will be to query your Airflow metastore. All the scheduling, DAG runs, and task instances are stored there and Airflow can't operate without it. I do recommend filtering on DAG/execution date if your use-case allows. It's not obvious to me what one can do with just these three overarching numbers alone.
select
    min(runtime_seconds) min_runtime,
    max(runtime_seconds) max_runtime,
    avg(runtime_seconds) avg_runtime
from (
    select extract(epoch from (d.end_date - d.start_date)) runtime_seconds
    from public.dag_run d
    where d.execution_date between '2022-01-01' and '2022-06-30' and d.state = 'success'
)

You might also consider joining to the task_instance table to get some task-level data, and perhaps use the min start and max end times for DAG tasks within a DAG run for your timestamps.


Why would anyone say that it is problematic to notate this chant like this instead of using the standard notation for gregorian chant?

Question: I hear many people saying that notating Gregorian chant like this is problematic. Why would anyone say that it is problematic to notate this chant like this instead of using the standard notation for Gregorian chant?
Where is the problem?
Answer: This notation has no concept of main and side notes, of the central tones of a phrase and its subdivision and suggests a rigidity of note length and weight not matching the fluid character of chant.
Notation is always an abstraction of a performance.  Square notation abstracts in different categories to modern notation.  I find it easier to create a performance matching my understanding of chant using square notation.
Answer: That is an extremely simple example with no accidentals. That system was applied in the Swedish Catholic hymn book with unfortunate results.

Standard notation results in a loss of information and the difference is clearly audible.

Gregorian notation provides a graphic representation of the phrasing in a very clear way.

Four lines are easier to read than five and can be made larger without taking up more space. This is an important consideration especially in poorly lit situations and for older singers.

Gregorian notation gives relative pitch. Choirs choose the pitch to suit themselves and the celebrant.

It is unnecessary. The complete body of Gregorian chant is available on line, copyright-free. The entire exercise of transcribing chant into standard notation is a waste of time.

Many singers in church choirs cannot read standard musical notation anyway. The pictorial representation of Gregorian notation is easier to understand. Gregorian notation is quite a good way of introducing singers to standard notation.

Above is the same piece of music in Gregorian notation (Agnus Dei Mass 17). Someone who cannot read standard notation will not find Gregorian chant notation any more difficult. Anyone who has only used standard notation should not have any difficulty in making the transition. Anyone singing in a Catholic choir will eventually have to learn the Gregorian notation. If you are familiar with Gregorian notation, transcription to five line is just a confusing irritation. This innovation is pointless and degrades the quality of the performance.
Comment: Do you at least see the benefit of standard notation for many, many people who can get the gist of the melody without needing to study Gregorian notation?
Comment: I hear you, @MichaelCurtis but I have to agree with this answer.  As someone with a solid background in standard notation, Gregorian chant notation is not difficult to learn.
Comment: I wonder how you arrived at your conclusions in point 6. How broadly have you surveyed church choir singers? Also, how specifically is Gregorian notation easier or more pictorial than standard?
Comment: Also, regarding point 1: I agree that the specific example of standard notation given in the question has lost information, as also pointed out in the earlier answer by @user62910, but certainly a more careful effort with standard notation could retain it.
Comment: I sang in Catholic church choirs and as solo cantor in England and Sweden for about 45 years. Gregorian chant places the note groups directly over the syllables.The current settings and notation system was developed by the monks of Solemnes in the 19th and 20th centuries, following the tradition established by Guido d'Arezzo. If they had thought it was worth dropping they would have done so. As a matter of fact, Liber Usualis was available in standard notation, but not that show in the example; the notes are grouped in beams and the standard length note is indicated by a quaver.
Comment: The Gregorian Chant notation itself led to a loss of information. Earlier texts used a system of signs, similar to those in Byzantine Chant and Hebrew texts. Students would learn the melodies by heart from an elder, and pick them up by singing in the community. The four line system of d'Arezzo indicates relative pitch, but loses subtleties like microtones, which probably survived for a while. The older form of neum notation is given in the Graduale Triplex alongside the latest four-line notation. This was the work of the Solemnes researchers. Every choir leader should have a copy.


Definir um campo padrão select html

Question: Gostaria de saber como deixar a primeira opção de um combobox(em html) com a opção "Selecione"
E obrigar o usuário a selecionar pelo menos 1 campo na caixa de seleção.
Exemplo:

<select name="endereco_estado">
  <option value="AC">Acre</option>
  <option value="AL">Alagoas</option>
  <option value="AP">Amapá</option>

Obrigado
Answer: Para obrigar o usuário a selecionar pelo menos um valor em inputs do HTML, você precisa usar o atributo required, da seguinte maneira:

<select name="endereco_estado" required="required">
  <option value="AC">Acre</option>
  <option value="AL">Alagoas</option>
  <option value="AP">Amapá</option>
</select>

Uma solução para adicionar essa primeira opção, usando apenas HTML (sem CSS nem JavaScript) seria usar uma option com os atributos disabled e selected. Isso faria com que ela aparecesse no topo, já que o atributo selected faz com que ela seja selecionada automaticamente, e não poderia ser selecionada pelo usuário devido ao atributo disabled:"

<select name="endereco_estado" required="required">
  <option value="" disabled selected>Selecione</option>
  <option value="AC">Acre</option>
  <option value="AL">Alagoas</option>
  <option value="AP">Amapá</option>
</select>

Veja funcionando no repl.it
Comment: Muito obrigado João!

Definir um campo padrão select html


General Content Search of Content type Exposed form

Question: Is there a method of giving a user the ability to search any term within all content of a particular node through an exposed form. For example you have the content type of, say - Business, with the fields of - CEO and Base of Operations. Could you give them a simple search that looks for a match in both those fields?
Answer: This is certainly possible and there can be many approaches to this, but it would require some effort in any case.
Taxonomy terms are not indexed by core search, therefore you would need to rely on a third party module. Such popular modules are Search API and Apache Solr.
My preferred method, in short, is to use the Search API in combination with Views:

Install the modules Search API, Search API DB, Views, Ctools.
Create server and index, add the taxonomy fields in the index.
Create a view for the search page based on the index
Filter by eg. "Search: Fulltext search", exposed
Add any fields to view, such as "Rendered entity" (for teasers etc.)
Sort by any field, such as "Search: Relevance".
Comment: You can use search_api in combination with search_api_solr, as well https://drupal.org/project/search_api_solr
Comment: I've never used taxonomy (or at least not that I was aware of). How does taxonomy have anything to do with searching content. Doesn't taxonomy just apply 'tags' to content?
Comment: Sure. You can use for example a simple view from the Views module to present content classified by tags. But in your question you ask about searching in an exposed form.
Comment: So your answer doesn't require the use of taxonomy?
Comment: My answer *assumes* that you already use taxonomy. You need to have a taxonomy field in your content type in order for the search index to include it, and obviously for it to have some values if you need to search for them in the exposed field.
Comment: Excuse my ignorance but does this mean your searching for the taxonomy values, rather than the content's value? How interchangeable are the two?
Comment: You can specify in the search index any fields that you wish to search for, including the taxonomy value or its parent term value or content body and so on. You can even specify the weight each one will have in your search result.


determine the weight of a new attribute

Question: I have a dataset about the automobile credits. This data set contains information that I care about when giving credit. For instance age, year of experience, income etc. And my database includes values of them and i can use multiple regression analysis to give weight for each attribute. My formula can interpret them because i have their history.
My question is here.
I want to add new attribute to dataset. Let we say it to X. But my dataset doesn't include any history of X and i want to add it. X represents any emergency situation. So it can not give any coefficient for it. But i want to new equation with X.  How can i solve it ? How can i give coefficient for X ?
Comment: Do you have any data containing X that can possibly be used for regression?
Answer: It sounds as if you want to quantify the effect of X without having any data on X.  Perhaps these ideas will help.
Option 1:  Are you looking to include in the equation some estimate of the effect of X?  If so, you could, for a small portion of the dataset, simulate each case's X value, inserting values that would be plausible given the corresponding values of all the other variables.  If X is unrelated to the other predictors, then compute X as some function of the outcome. Then run the regression. You'll obtain a simulated X coefficient as well as simulated coefficients for the other predictors.  (You'll probably want to do this many times to see how much results can vary, how sensitive they are to your choice of simulated values.)
Option 2:  Do you already have an idea of the magnitude of the effect of X?  If so, leave the regression as it is, but allow for X's role as a source of uncertainty by increasing the confidence intervals around each predicted value (prediction intervals), by an amount that seems appropriate to you.  Then, to evaluate results, study and plot these prediction intervals rather than focusing on coefficients.
Option 3:  Do you believe you have no knowledge of X?  If so, you're wrong in the sense that with your regression equation X's effect is present in the residuals--the error terms for each case.  Studying these may give you some clues as to X's role.  You may even want to suppose that any case with a large residual, or a large positive one, is a case for which X takes a certain value.  It's possible this could move your analysis forward in some way.

determine the weight of a new attribute


Auto image resize for iPhone/iPad gallery in portrait & landscape mode

Question: I have to optimize a small website for iPhone and iPad. Thanks to media queries, I'm using two css files, one for iPhone portrait & landscape mode, and a second for iPad portrait & landscape + all others. There is a picture gallery on the website and I wanted the images to use the maximum available area depending on which device they are beeing displayed on, plus the orientation mode.
I ended up using 4 nivo sliders on the same page, where I hide 3 of 4 using css (display:none). The images are resized by TimThumb. This is definitely a bad solution (e.g. all 4 nivo sliders are beeing loaded and run on the iPhone even only one is displayed) and I was wondering if there is any other solution to this problem?
Comment: I just read your question and I understand you're using nivo, which is a jQuery library, right? Try tagging your question jQuery and nivo. jQuery is a popular tag with lots of followers. Nivo is a tag that's not used a lot, but I guess it helps specify what you're working on.
Comment: FYI: It's not possible to tell that you're asking about web development from reading the title or looking at the tags. I would say it's likely that this question doesn't attract the attention of the right people.
Comment: Any idea for better tags/title? Unfortunately I couldnt think of any better. :/ (I think you're right though.) - I changed it now but no idea if its any better than before.
Comment: you still don't use any words or tags that I associate with web development. All words and tags are perfectly valid for a question about app development in objective-c.
Comment: @Erik B - That was my problem while searching for a solution because most of the answers are app development related whereas I'm looking for a website gallery. Thanks anyway for trying to point me in the right direction.
Answer: I had a similar problem for ipad app and i simply used this:

img.homepg {     width:920px; } @media screen and (max-width:910px)  {
<code>img.homepg {
    width:670px;  } } img {
transition:all .2s linear;
-o-transition:all .2s linear;
-moz-transition:all .2s linear;
-webkit-transition:all .2s linear; }
</code>

with .homepg being the img class, 920 being the largest image width, 910 being the max screen width that triggers the image resize (aka when the orientation is changed), and 670 being the min img width!
Comment: That does not seem to solve the OP issue which is : how to avoid the waste of bandwidth of 4 concurrent images on the same page ?


React.js transpile issue. Babel build commands not working

Question: I have been following the react: up and running book by stoyan stephanov. Chapter 5. I am stuck at the command:
babel --presets react,es2015 js/source -d js/build
result: es2015 does not exist.
But when I try:
babel --presets react js/source -d js/build
it works as expected in the book.
And then I write:
babel --presets react,es2015 js/source -d js/build
result: Syntax error at app.js. Unexpected token before h1 tag.
App.js code
'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import Logo from './components/Logo';

ReactDOM.render(

    Welcome to the  app!

,
  document.getElementById('app')
);

Answer: All optional presets must be installed manually, as far as I know:
npm install --save-dev babel-preset-es2015

P.S. Here are some additional data on issue.
Comment: You'd want to --saveDev in this instance as it's purely a dev tool to transpile back to old skool JS.
Comment: Thank you for the quick response fellows. I tried the command mentioned by @ankhzet but later tried the command: babel --presets react,es2015 js/source -d js/build. Unfortunately the same message. Am i missing something?
Comment: @ZahirJunejo, only suggestion I can give, try reverse order for presets: `babel --presets es2015,react js/source -d js/build`. The order in which transformations are applied is actually important when `.babelrc` is used, maybe it's also applies to cli


Access user profile data

Question: I have a field on a user profile called field_certified_tap. When this is equal to 1 or true on user update/create, I want to send an email.
Currently, I do not see this field in the Condition->Entity Has Value->[data select].
I am using the 3x-dev version of Rules and the 1x version of token.

What am I doing wrong? Is there currently a way to accomplish this with Rules UI or should I make my own Rule or implement in the user save hook?
Thanks!
Answer: In your image, you are configuring the "Entity" parameter of the "Entity has field" condition. That parameter should be set to just "user" in the data selector - it would be wrong to specify a field here since it is calling for the entity that you want to check.
The SECOND parameter should be "Field", and it is there that you would want to enter "field_certified_tap" using direct input (not data selector).
Note that the "Entity has field" condition cannot be used to check the value of the field - that has to be done in a separate "Data comparison" condition.
But you are right that even when you properly configure the "Entity has field" condition, your custom field does not show up in the data selector for subsequent actions. I'm not sure why, but there's an open bug report for that in the Rules issue queue:  "Entity has field" doesn't actually give access to the field
Instead, use the "Entity is of bundle" condition to get access to the field. Here's an example using a boolean field called "field_certified_tap" which I added to the user entity. If you import this Rule and examine it in your UI you will see that after adding the "Entity is of bundle" condition to the rule, the data selector in the "Data comparison" condition and the "Show a system message" action DOES now give you an option of "user.field_certified_tap". You can then add a "Data comparison" condition to show the message only when field_certified_tap is true.
I'm using "Show a system message" here because it's much easier to use for debugging than "Send mail". You should use this action to test the tokens you plan to use for your email, then when you are sure you have the values you need you can add a "Send mail" action.
langcode: en
status: true
dependencies: {  }
id: access_certified_tap_field
label: 'Access user certified tap field'
events:
  -
    event_name: 'rules_entity_update:user'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: 137a6a57-2d1a-467d-80e6-68091de5eb11
  conditions:
    id: rules_and
    uuid: 098bb2b1-3e95-4efa-9328-07b651591e63
    conditions:
      -
        id: rules_condition
        uuid: 3b23a038-ac0c-4461-b14b-6db518c3261a
        context_values:
          type: user
          bundle: user
        context_mapping:
          entity: user
        context_processors:
          type:
            rules_tokens: {  }
          bundle:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_entity_is_of_bundle
        negate: false
      -
        id: rules_condition
        uuid: fbcdef7b-9681-47a2-bcac-94d49c86d7fa
        context_values:
          data: '{{ user.field_certified_tap }}'
          operation: '=='
          value: '1'
        context_mapping: {  }
        context_processors:
          data:
            rules_tokens: {  }
          operation:
            rules_tokens: {  }
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_data_comparison
        negate: false
  actions:
    id: rules_action_set
    uuid: d6d904a0-007a-4f7f-97be-ac7c1f64edd2
    actions:
      -
        id: rules_action
        uuid: c5d31406-7355-4d91-b623-2c55dc3d57cb
        context_values:
          message: 'User is certifiable!'
          type: warning
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message

Access user profile data


PHP sorting of multi-dimensional array by price value

Question: Say I have a multi-dimensional array set up as follows:
$matrix[1][1]=4.54;        $matrix[2][1]="apples";  $matrix[3][1]="coles";
$matrix[1][2]=7.2140230;   $matrix[2][2]="apples";  $matrix[3][2]="safeway";
$matrix[1][3]=15.56;       $matrix[2][3]="oranges"; $matrix[3][3]="coles";
$matrix[1][4]=2.34;        $matrix[2][4]="bananas"; $matrix[3][4]="safeway";
$matrix[1][5]=27.98;       $matrix[2][5]="grapes";  $matrix[3][5]="coles";
$matrix[1][6]=17.68493403; $matrix[2][6]="oranges"; $matrix[3][6]="safeway";

And I wish to re-arrange by the pricing information which I've stored under the first 1st column, so that the new order of $matrix would be:
$matrix[1][1]=2.34;        $matrix[2][1]="bananas"; $matrix[3][1]="safeway";
$matrix[1][2]=4.54;        $matrix[2][2]="apples";  $matrix[3][2]="coles";
$matrix[1][3]=7.2140230;   $matrix[2][3]="apples";  $matrix[3][3]="safeway";
$matrix[1][4]=15.56;       $matrix[2][4]="oranges"; $matrix[3][4]="coles";
$matrix[1][5]=17.68493403; $matrix[2][5]="oranges"; $matrix[3][5]="safeway";
$matrix[1][6]=27.98;       $matrix[2][6]="grapes";  $matrix[3][6]="coles";

What would be the best way to achieve this? I've read other questions about sorting multi-dimensional arrays but have had trouble implementing because those examples seemed to have associative arrays with keys and elements, whereas I am just using the different numbers to store each piece of data. I would prefer not to change the way I am storing data in the array as the actual script is quite long and complex and so this would involve a lot of re-work.
I am completely new to PHP so my apologies if I am missing something obvious here. Thanks for your help.
EDIT: Thanks everyone for your advice, scessors code is exactly what I needed. Halfer - to your 1st question - Yes, 2nd post - good point, I will implement this. Thanks again everyone!
Comment: Is the first index 1=price, 2=product, 3=store, for both input and output arrays? Thanks @kapep for a much better formatting, that makes it clearer!
Comment: Can you change the data format? This would be much easier if the first number was the "product ID" and the last number was the price/name/supplier index.
Comment: I appreciate you don't want to change your approach, but just for the record it might be better if you were to swap your [X][Y] ordering to [Y][X]. That way an array in `$matrix[1]` would contain the price, product and store, and thus is an 'object' that can be more easily sorted.
Comment: @user2037290 First question here, please read what to do [when you get answers](http://stackoverflow.com/faq#howtoask).
Answer: If it's no problem that the sorted array begins with zero, you can use array_multisort:
array_multisort(
    $matrix[1], SORT_ASC, SORT_NUMERIC,
    $matrix[2], SORT_ASC, SORT_STRING,
    $matrix[3], SORT_ASC, SORT_STRING
);

Also see my example.
Comment: What if you want to leave the original array intact? Just make a copy?
Answer: I believe that phps array_multisort will do it for you:
Heres an example from docs:
<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

In this example, after sorting, the first array will contain 0, 10, 100, 100. The second array will contain 4, 1, 2, 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well.
From: http://php.net/manual/en/function.array-multisort.php
Comment: Sorry that my answer would mean splitting your arrays :-(
Comment: No problem, glad you got an answer.
Answer: Using my_uksort provided by Adam Backstrom
<?php
function my_uksort($a, $b) {
    global $matrix;
    asort($matrix[1]);
    return $matrix[1][$a] < $matrix[1][$b] ? -1 : 1;
}

uksort($matrix[2], 'my_uksort');
uksort($matrix[3], 'my_uksort');

print_r($matrix);
?>

DEMO


VBO showing error when using Drupal Commerce

Question: I am getting the following error on a white page after using VBO and Drupal Commerce -

*Call to a member function aggregate() on a non-object in
  .../sites/all/modules/contrib/views_bulk_operations/views_bulk_operations.module
  on line 764*

I upgraded to Drupal Commerce 7.x-1.x-dev and am running the latest version VBO and Commerce Stock
Whenever I try to perform any Bulk operation, like deleting a bunch of products or changing the order status, I get the error
I have looked at the issue, which discusses an issue with Commerce Stock and empty fields, but the solution found doesn't apply because all the stock levels have values.
Does anybody have any suggestions?
PS: I am not sure if this is a red herring, but I also am occasionally getting this message on the module admin page:

*Notice: Undefined index: step in
  views_bulk_operations_form_validate() (line 621 of
  /var/www/html/nidadev/sites/all/modules/contrib/views_bulk_operations/views_bulk_operations.module).
  Notice: Undefined index: step in views_bulk_operations_form_submit()
  (line 664 of
  /var/www/html/nidadev/sites/all/modules/contrib/views_bulk_operations/views_bulk_operations.module).
  Notice: Undefined index: select_all_pages in
  views_bulk_operations_form_submit() (line 711 of
  /var/www/html/nidadev/sites/all/modules/contrib/views_bulk_operations/views_bulk_operations.module).
  Notice: Undefined index: operation in
  views_bulk_operations_form_submit() (line 713 of
  /var/www/html/nidadev/sites/all/modules/contrib/views_bulk_operations/views_bulk_operations.module).*
Comment: That's in _views_bulk_operations_execute():

      "if ($operation->aggregate()) {"

You'll have to tell us what you're trying to do. (What action are you trying to take?). But I just tried to recreate this with latest VBO and commerce and had no trouble deleting products. Normally I'd say file an issue, but unless you can recreate it in a test environment (a simple Commerce Kickstart install) that won't do much good. Sounds like you have a bad VBO install. I'd rm -rf the current VBO and replace it with the latest and drush updatedb. If that didn't work, uninstall and reinstall.
Comment: Thanks Randy, I tried to do what you said, but it didn't seem to work. The interesting thing is that I have no problems on views that I have created after the update, I just have the problem on views created before the update
Comment: Look like I was mistaken ( I think) What I ended up doing after messing around with it for an hour was restoring the database from the night before. I had the a fresh version of VBO installed and now it works - (sort of) I do have to re-input the selected operations, but that is better than rebuilding all the views
Comment: There's an open VBO issue for this. Each person having the problem in the end had a misconfigured drupal install (a wrong cache in settings.php, etc). I've yet to find anyone with an actual bug (and I've looked at several actual installations with that problem).
Answer: I flushed out the database, and started with a new fresh version of VBO.


Recuperar dinamicamente todos os GET da URL

Question: Estou carregando dinamicamente minhas views com ajax utilizando:
view = getUrlParameter('view') ? getUrlParameter('view') : window.location.href+="?view=newusers";

$.ajax({
  method: "post",
  url: "views/empregador/" + view + ".php",
  data: {
    auth: 'ajaxrequest'
  }
}).done(function(data) {
  $('#viewa').html(data);
});

Isso funciona perfeitamente para casos em que acesso uma página que não precisa de parâmetros GET. Porém, em algumas requisições preciso preciso que minha url seja "views/empregador/" + view + ".php?meuGet=123&meuOutroGetAleatorio=123&...".
A minha função getUrlParameter recupera parâmetros específicos da URL, forçando uma verificação se 1 por 1 existe, que seria totalmente inviável para o nível de complexidade aplicação.
Existe algum método de capturar de forma dinamica todos os GETs passados pela URL com javascript?
Answer: você pode usar a função location.search para pegar a query completa:
 var query = location.search;

Caso queira manipula-lás, já existe uma resposta em tópico respondendo isso:
Como capturar parâmetros passados pela URL usando javascript?