Is it possible to estimate the time needed to train a machine learning model given a size of data and hardware specification?

Question: I am planning to make small Tensor Flow image classification project, which is expected to run on machines with low processing power, and one of the concerns I was asked about was the time needed to train the model.
The project is still in the conception stage and no clear boundary is made.
But assuming that we will use Tensor flow for Python, with a simple Neural Network for say n images data set, is there a way to estimate or predict the time required to train the model before performing the training given the hardware in use?
I have asked one of my colleagues who works in NN and he said that maybe we could calculate the time needed by measuring the time for the first epoch and making an estimation how many epochs needed afterwards. Is this is a valid way? If yes then is it even possible to estimate the number of epochs needed? And either cases is there a way to calculate it before performing any training?
Answer: There is no definite way of finding the number of epochs to which the model converges. It is one of the hyperparameter.
Apart from the type of model you are training, convergence also depends on the distribution of data, and the optimizer you are using.
The rough estimate you can make by looking at the number of parameters you have in your model, check time for one epoch, and get a rough idea from "experience" on the number of epochs. BUT you always have to look at the training and validation loss curves to check for the convergence.
Comment: IDK why, but by your name, you appear to be a teenager. I'm impressed you're into machine learning at such an early age... There are only few who actually nail it!


Determine if a graph with partial 2D distances has a ~single embedding in $R^2$

Question: I've stumbled upon an interesting topic, and am wondering if any relevant formal
research took place, perhaps under different terminology than mine.
Definition
Looking at a graph G=(V,E) with weighted-edges indicating known distances between vertices,
where not all distances are known - a (partial) distance-graph,
define it to be "stable" if there exists at least one valid embedding of the vertices
in $R^2$, and any two valid embeddings are the same up to rotations, translations
and mirroring along an arbitrary axis.
Going forward, assume there's always at least one valid embedding.
Claim
The following are equivalent, assuming there is at least one set of three vertices holding the assumption in (3):

G is stable.
We can calculate the distance between any two vertices based on the known distances, regardless of any embedding.
We can determine all vertices' positions in $R^2$ given the positions of any three of them which are not on the same line and have known distances between them.

Examples
In the following examples, the vertices are embeddable in their depicted locations in $R^2$, and the edge-lengths stem from those locations.
For starters, consider (pardon my ascii):
<code>v1 --------------- v2
 | |                |
 |    |             |
 |       |          |
 |          |       |
 |             |    |
 |                | |
v3 --------------- v4
</code>
This graph isn't stable, as v3 can be mirrored along the v1->v4 axis
(the same goes for v2). Adding the v2->v3 edge stabilizes the graph,
but that's a trivially-stable graph (all edges are known,
so (2) holds by definition).
For a non-trivial example, consider:
<code>    v1 ----- v2
   |  |       | |
  |    |     |   |
 |     |     |    |
v3 -------------- v5
   |    |   |    |
     |  |   |  |
       | | | |
          v4
</code>
One can prove that this graph holds (3),
although it doesn't supply all possible edges.
Replace (v3, v5) with (v1, v5) and this will no longer be the case,
as v3 could be mirrored along the v1->v4 axis.
(In general, any vertex with 2 or less neighbors breaks stability.)
Proving the equivalences, if you're interested:
Given (2) and three positioned vertices, use triangulation to find all others - (2) implies (3).
Given (3) and two valid embeddings, find the single
affine linear transform from the known vertices
as mapped in embedding 1 to their positions in embedding 2.
Apply the transform to all vertex-locations in embedding 1 to get a new, valid embedding.
From the assumption, this new embedding should be the same as embedding 2.
(3) implies (1).
Given (1), take an arbitrary embedding and calculate all distances,
any embedding yields the same results, (1) implies (2).
Question
The main question is, how does one determine algorithmically whether or not
a partial distance-graph is stable?
I've devised a gradient-descent-based algorithm for estimating locations given a distance-graph
and a few known points (again, is there a known method for doing this which I am unaware of?),
so a simple heuristic would be to set fixed locations for three points with known distances
between them, run the algo a few times with random initial guesses,
and see if G.D. converges each time to the same locations
(when it indeed converges to the same minimum price) -
giving a strong indication of a single embedding.
However, I'm looking for some provable criteria, if one is already known -
perhaps from other fields like construction/architecture.
Comment: What you are asking is when an abstract metric space can be embedded in Euclidean space of dimension $d=2$. This is a well-studied and largely solved problem. Try googling "Euclidean embeddings of metric spaces" and the "multidimensional scaling (MDS)" algorithm.
Comment: Awesome! Thanks.
Comment: @ElchananSolomon Looks promising. Mind posting this as an answer for me to accept?
Answer: This question can be rephrased as "when can an abstract metric space be embedded in $\mathbb{R}^d$?" (for $d=2$, in your case). This is a well-studied question.
The most useful place to look is the Wikipedia page on Euclidean distance matrices. There you will find the Schoenberg criterion, which is an if and only if characterization of Euclidean embeddability. I'll summarize it here:

Let $D$ be the matrix of distances.
We need the diagonal of $D$ to be zero (this is called being hollow), as will always be the case for your graphs.
The entries of $D$ must be real numbers, which again will always be the case for your graphs.
You need to turn $D$ into the Gram-matrix $G$ using the formula $G_{ij} = \frac{1}{2}(D_{1i} + D_{1j} - D_{ij})$. The Gram matrix can be interpreted as containing dot-product, rather than distance, information.
If $G$ is positive semi-definite and has rank at most $k$, the metric space can be embedded into $\mathbb{R}^k$.
To find the embedding, we assume $G = X^{T}X$, where $X$ is the matrix containing the embedding coordinates. This formula indeed asserts that $G$ consists of dot products. The question then becomes: how to compute $X$ given $G = X^{T}X$? What we do is perform an eigen-decomposition of the symmetric matrix $G = U \Lambda U^{T}$. Since $G$ is positive semi-definite, the entries of the diagonal matrix $\Lambda$ are positive, so it makes sense to define $\sqrt{\Lambda}$. Then if we set $X = \sqrt{\Lambda}U^{T}$, we see that $X^{T}X = U\sqrt{\Lambda}\sqrt{\Lambda}U^{T} = U \Lambda U^{T} = G$, satisfying the necessary equation. Thus $\sqrt{\Lambda}U^{T}$ contains the vectors of the desired Euclidean embedding.
Comment: Still looking into the source materials, thanks for the great references! MDS seems like a good alternative to the gradient-descent-based algo I mentioned. As for the Euclidean distance matrices page and Schoenberg, they assume that the full clique distance-graph is known (and is exact). Cayley-Menger determinants have the same requirement, so both approaches don't help me much. My interest is in a criteria for the uniqueness of X given a partial graph. Uniqueness given all edges is trivial. The GPS mention on the Distance Geometry page seems to be a good lead. Thanks again!
Answer: This falls under "rigidity theory", and is specifically categorized as "global rigidity". To simplify analyzing the problem, and avoid rigidity classifications which are highly-dependent of the exact edge lengths given (as noise should be taken into account), we discuss "generic global rigidity" instead, which considers the graph's structure and "well-behaved" edge-lengths, ignoring any given edge lengths.
Google's results for "rigidity theory" might not be what you want - a lecture MIT published on generic local rigidity, which is a solved problem specifically in $R^2$:
https://www.youtube.com/watch?v=k2jKCJ8fhj0
Google's useful result for "global rigidity":
https://www.cs.harvard.edu/~sjg/papers/ggr.pdf
("CHARACTERIZING GENERIC GLOBAL RIGIDITY" by Gortler, Healy & Thurston, 2007.)

a generic framework is globally rigid if and only if it has a stress
matrix with kernel of dimension d + 1, the minimum possible.
[...]
We also show that this condition is efficiently checkable with a randomized algorithm

As for finding an approximate embedding in $R^2$, as pointed out by @ElchananSolomon
in the question's comments, we use MDS.


What does scaffolding files for drupal/core do when I do a composer require ?

Question: I noticed that default.settings.php files gets copied to scaffold folder:
Copy [web-root]/sites/default/default.settings.php from assets/scaffold/files/default.settings.php
Why is it copying this file to scaffold and what is it the purpose of this?
Comment: So that boilerplate files stay updated with Drupal core releases (they do sometimes change) and or are replaced if they are deleted by mistake. You can configure this behavior in composer.json.
Comment: https://github.com/drupal/core-composer-scaffold explains itself.
Answer:
The purpose of scaffolding files is to allow Drupal sites to be fully
managed by Composer, and still allow individual asset files to be
placed in arbitrary locations.

From: https://github.com/drupal/core-composer-scaffold
The reason that default.settings.php is copied across is that this file is not part of the Drupal core (the contents of /web/core), nor is it part of a module, theme, or distribution. But it's part of a base Drupal installation, so Composer copies it to the correct location upon install.


Missing Custom Modules

Question: I ran into a database problem that required me to reinstall Drupal on my Localhost.  In the process, I've noticed that the custom modules I installed previously are no longer listed. They still reside in sites/all/modules and I assumed that they would show up again in my module listing after I reinstalled.
That's not the case.  I cleared cache assuming that would help, but, it didn't. I ran update.php and that did not help.  Is there a way to force Drupal to recognize all of the previously installed modules?  Is there a database/table I need to rebuild?
Comment: Could you expand on what you mean by "reinstall"? As in what's the process you've followed to do that? If you've just installed a new version of Drupal from scratch (I.e. run through the usual installer), then you just have a fresh version of Drupal and no, it couldn't know about the modules you used to have enabled in a previous installation. It's a blank database with core Drupal in it, nothing else. If you've followed some sort of config backup/migration process, it's important to know what that was to be able to advise
Comment: @Clive First, I uninstalled Drupal using the provided uninstaller (Windows).  Then, I went to the [Bitnami Drupal Stack](https://bitnami.com/stack/drupal) and downloaded the latest Windows Installer and ran it.  It installed without errors.  I should also note that the uninstaller asked to make a backup of the previous Drupal database.  I did make a backup.
Comment: I'm not familiar with the Bitnami stack, but I assume it contains an SQL server of some sort (probably MySQL), you didn't connect it up to an external db server? If so then that server, along with all its data, would almost certainly be removed during an uninstall. That's the usual way of things when one of these bundled things gets removed. That's probably why it suggested a backup, knowing it was going to delete everything. Your best course of action would be to restore the db backup to the newly installed server. Not sure what tools Bitnami gives you for that, but MySQL/drush will do
Comment: @Clive would that also explain why the custom modules I wrote are not showing up? They are not listed in the modules screen even though they are in the correct folders.
Answer: I have resolved this issue.  My problem was caused by reinstalling the Bitnami stack.  I had assumed that it would install into the previous location.  However, that was not the case, as I learned, because it was a newer version.  Bitnami installed into an entirely separate folder.  This meant that Drupal was no longer aware of my custom modules, or, the modules I had installed.  My resolution was to copy my custom modules from their prior folder location to the new Bitnami reinstall location (folder).  I also had to reinstall the other custom Drupal modules.

Missing Custom Modules


Tubular neighborhood: compact support for the pullback of a form with compact supoprt

Question: As I have pointed out here:
Projection formula, Bott and Tu
The integral projection formula given in Bott and Tu is incorrect. This is used later in the book, on page 67 to prove that Poincare dual of a closed oriented submanifold in an oriented manifold and the Thom class of the normal bundle of the submanifold can be represented by the same forms. The proof is on page 67 here:
http://www.maths.ed.ac.uk/~aar/papers/botttu.pdf
As was pointed out in the answer by Eric Wofsey, the solution would be for the pullback to be a proper map. This is not available. But, since the proof uses a tubular neighborhood which can  "shrink", could we use the shrinkage to find a compact form approximating the pullback with arbitrary accuracy? Or any other way of going around the error in Bott and Tu?
Answer: There is nothing wrong here.  The projection formula is perfectly correct as long as you change the definition of $\Omega^*_{cv}$ (to require the support to be proper over the base).  That is, you should consider the definition of $\Omega^*_{cv}$ to be changed in this way throughout the entire text.  The Thom class $\Phi$ to which the projection formula is applied on page 67 is by definition an element of $H^{n-k}_{cv}(T)$ and so, assuming you have corrected the definition of $\Omega^*_{cv}$ from earlier, the projection formula does apply to it.
In fact, more strongly, you need to change the definition of $\Omega^*_{cv}$ or else you can't even define the Thom isomorphism at all.  The reason is that integration along the fiber isn't even well-defined if your forms don't have compact vertical support in the stronger sense.  You can integrate a form pointwise along the fiber, but the result may not be a smooth (or even continuous) differential form on the base (the counterexample I gave in the other question works again here).
(Of course, you have to check that everything else in the text works with this changed definition, but this should be straightforward.  The only step that actually involves constructing any specific forms that you might have to worry about having proper support is in the (omitted) proof of Proposition 6.16.  In that proof, an inverse to $\pi_*$ is constructed using a map $e_*$ as on page 38, and this $e_*$ does give forms which have proper support because the support on each fiber is contained in the support of $e$, which is a fixed compact set.)
Comment: The Thom class is defined in terms of the Thom isomorphism, and the Thom isomorphism only exists if you make this extra assumption (see my edit).  Alternatively, the explicit construction of the Thom class via the $e_*$ map defined on page 38 (as alluded to on page 63) manifestly gives a form whose support is proper over the base, since its support is restricted to a fixed compact subset of the fiber (the support of $e$).  This will continue to be true when you patch Thom classes together with a partition of unity in the general case.
Comment: Of course I see that. But I was wondering if in case of tubular neighborhoods, we could avoid this extra assumption. There is no reason to really believe the support of the Tom class form on page 67 is compact when restricted on the pullback in this case. I do not think your fix would work in this case.
Comment: The more I think about it, I see no way around changing the definition. To require that pullbacks of compact sets from the base intersect into compact sets with the support of the vertically compact forms as you said.


Protractor: get Element's Id

Question: I have had it with this asynchronous calls all over the place in protractor and javascript in general.  What used to take 2 lines of code now takes 10.  here's an example:
I am writing a protractor utility method to simply check for certain DOM properties on a group of related divs and input text boxes. This is for a validation framework I am working on.  The idea is to pass a protractor element to this method and then based on that element's id check for certain DOM properties on related divs and input text boxes.  This is how I got it to work:
/**
 * Checks for error in a NUAF field
 * @param {String or Element} field .
 * @param {string} errorText expected validation error text to appear in tooltip
 */
exports.checkForError = function (field, errorText) {

    var innerCheck = function(fieldId) {
        expect(fieldId).not.toBe(undefined);
        var elmntd = element(by.id('divInput.'+fieldId));
        expect(elmntd).not.toBe(null);
        expect(elmntd.getAttribute('tooltip')).toContain(errorText);
        expect(exports.hasClass(element(by.id('prnt.'+fieldId)), 'has-error')).toBe(true);
    };

    // this unbelievably complex block of code gets the id of the
    // field argument.  If string was passed, the fieldid is just that .
    if (typeof field === 'string') {
        innerCheck(field);
    } else {
        //what used to be field.id now needs 6 lines of code?
        field.getAttribute('id').then(
            function(idAttribute) {
                console.log( "*********: "+idAttribute );
                innerCheck(idAttribute);
            }
        );
    }
};

Question is: Is there a better, less verbose way to write the field.getAttribute('id').then block of code.  It's just a shame to write all this just to get the Id of the element.
Comment: You can make the class check more readable - instead of a hasClass helper, make a [custom toHaveClass matcher](http://stackoverflow.com/a/32699366/771848).
Answer: This is not that verbose for an asynchronous code... Especially if you take into account that you can directly pass the function innerCheck to a promise:
// this unbelievably complex block of code gets the id of the
// field argument.  If string was passed, the fieldid is just that .
if (typeof field === 'string') {
    innerCheck(field);
} else {
    field.getAttribute('id').then(innerCheck);
}

Should be just that easy

Protractor: get Element's Id


netstat reports UDP ports with no owning process

Question: When I run netstat -avp udp I get a slowly growing number of ports. It grows about 100 an hour but the rate varies considerably.
When I close the process, the ports do not disappear from the list. Similarly when I kill the process. Restarting the machine obviously resets the list but it just grows again. I have multiple machines showing the same symptom.
The majority of the ports listed are associated with mDNSResponder, but I think that is irrelevant as the issue is also associated with Chrome, Outlook and other programs.
After some time network access becomes compromised, presumably due to the exhaustion of ports in the 49000-65000 range where most of the UDP ports are allocated.
Running lsof -iUDP -n shows a mere 30 UDP ports, when netstat is reporting thousands.
The machines are iMac's running MacOS Monterey 12.0.1 and report that they are fully up to date with patches.
This is what the first few lines of netstat's output looks like:
Active Internet connections (including servers)
Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)     rhiwat shiwat    pid   epid  state    options
udp4       0      0  *.55317                *.*                                786896   9216    238  62261 0x0103 0x00010000
udp4       0      0  *.62074                *.*                                786896   9216    238    577 0x0103 0x00010000
udp4       0      0  *.51635                *.*                                786896   9216    238    301 0x0103 0x00010000
udp4       0      0  *.54799                *.*                                786896   9216    238    301 0x0103 0x00010000
udp4       0      0  *.57143                *.*                                786896   9216    238    301 0x0103 0x00010000
udp4       0      0  *.56933                *.*                                786896   9216    238    301 0x0103 0x00010000
udp4       0      0  *.51250                *.*                                786896   9216    238  63527 0x0103 0x00010000
udp4       0      0  *.61138                *.*                                786896   9216    238  63527 0x0103 0x00010000

The man page for netstat does not tell me what the right hand columns refer to I can guess that pid is "process ID", epid is "effective process ID" but what are rhiwat, shiwat, state and options and are they useful in resolving this issue?
I would appreciate any suggestion on how to proceed with investigating why these mac's appear to have an ever growing number of UDP sockets.
Comment: I have the exact same issue, a shame that there is no answer @simon-g did you solve this?
Comment: @AlexanderStolz - I did not solve it. One day it just stopped happening. I assumed that the issue had been patched by an automatic update.
Answer: I am seeing the same thing (Monterey 12.1).  The problem went away after upgrading to Montery 12.2.1.
Using 12.1, netstat -n -p udp | wc -l grows by 30 lines every minute.  After four days my system becomes slow and I start getting isc_socket_bind: address not available errors.  sudo lsof -nP -iUDP | wc -l does not grow.
After about four days:
nslookup www.ibm.com
nslookup: isc_socket_bind: address not available

Discussion on Reddit speculates Cisco AnyConnect is to blame.  I am running Cisco AnyConnect.

https://www.reddit.com/r/applehelp/comments/sbsduv/macos_121_dns_issues/
https://www.reddit.com/r/mac/comments/rfut2n/dns_issues_still_with_121/hpchija/

I am still running Cisco AnyConnect with 12.2.1 and the problem seems to be resolved.
Answer: There is speculation that this problem was introduced by Apple with Monterey.
My personal experience is uninstalling the socket filter for Cisco Anyconnect is an effective work around until Apple releases a fix. It does not appear to impact the operation of the VPN, however you will want to check with your companies security folks before making such a change.
Note: After a reboot the Anyconnect socket filter will be re-installed, so you will need to remove after any reboots.


Olá pessoal, estou começando um curso de vuejs, quando rodo os comandos npm install -g @vue/cli e vue serve, acontecem alguns erros

Question: inserir a descrição da imagem aqui
inserir a descrição da imagem aqui
Possuo um arquivo nessa pasta chamado App.vue com o seguinte conteúdo:
<template:
 Hello World
Answer: Pelo que notei nas imagens você executou o comando vue serve logo após rodar o npm install.
O @vue/cli é um pacote urilizado para facilitar o fluxo de desenvolvimento com o Vue, e uma das suas funcionalidades é justamente a criação de projetos. Então, após instala-lo é preciso executar o comando vue create para gerar um novo projeto. Ex:
vue create my-awesome-project

Com isto será gerado um projeto chamado my-awesome-project, no seu terminal navegue até esta pasta, e apenas em seguida execute o projeto:
 cd my-awesome-project
 npm run serve

Atualizações do Vue
Importante notar que o Vue recebeu algumas atualizações e inclusive alterou a forma "padrão" para se criar novos projetos, inclusive adicionaram este pacote @vue/cli em modo de manutenção, dê uma olhada na documentação aqui para aprender mais sobre como criar projetos com o Vue.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Calculate sum $\sum_{n=1}^\infty {n\over3^{n-1}}$

Question: Calculate sum $$\sum_{n=1}^\infty {n\over3^{n-1}}$$The result is $9\over 4$ but I don't know how to get that.
Comment: The idea is to take derivatives :) in your case you need the derivative of $x^n$ at the point $x=1/3$.
Comment: To start you should write $$\sum\limits_{n=1}^{\infty} n\cdot \left( \frac13 \right)^{n-1}$$
Answer: We'll differentiate a geometric series. Suppose $|x|<1$; since $\sum_{n\ge 1}x^n=\frac{x}{1-x}$, $\sum_n nx^{n-1}=\frac{1}{(1-x)^2}$. Now take $x=\frac{1}{3}$.


java: ArrayList how order

Question: I have this class:
public class Media {
double supporto;
double i_m;
String idSentence;

public Media(double supporto,double i_m,String idSent){
    this.supporto=supporto;
    this.i_m=i_m;
    this.idSentence=idSent;
}

public double getSupporto(){
    return this.supporto;
}

public double getI_m(){
    return this.i_m;
}

public String getIdSentence(){
    return this.idSentence;
}

public String toString(){
    return this.supporto+" - "+this.i_m+" - "+this.idSentence;
}
}

and add in an ArrayList text these values:
ArrayList<Media> m=new ArrayList<Media>();
m.add(new Media(0.2545,0.2365,"id002"));
m.add(new Media(0.8745,0.4658,"id005"));
m.add(new Media(0.1599,0.6580,"id0010"));

How do I sort this array in descending order of the value of the first class Media?
I want to get this order:
 0.1599,0.6580,"id0010"
 0.2545,0.2365,"id002"
 0.8745,0.4658,"id005"

EDIT
I solved this way:
public class Media implements Comparable<Object>{
double supporto;
double i_m;
String idSentence;

public Media(double supporto,double i_m,String idSent){
this.supporto=supporto;
this.i_m=i_m;
this.idSentence=idSent;
}
public double getSupporto(){
return this.supporto;
}
public double getI_m(){
return this.i_m;
}
public String getIdSentence(){
return this.idSentence;
}
public String toString(){
return this.supporto+" - "+this.i_m+" - "+this.idSentence;
}
@Override
public int compareTo(Object arg0) {
    if(this.supporto==((Media) arg0).getSupporto()) return 0;
    else if((this.supporto)>((Media)arg0).getSupporto()) return 1;
    else return -1;
}
}

In the main method I order the m ArrayList:
    Collections.sort(m);

Comment: Show us the code you have tried to implement the sorting.
Comment: Use Comparable or Comparator to sort Object
Comment: Implement Comparable or Comparator and use Collections.sort() method
Comment: Follow the link http://www.javacreed.com/sorting-objects-using-comparator/
Answer: You need to make Fruit Comparable
public class Media implements Comparable<Fruit> {
    public int compareTo(Fruit compareFruit) {

        int compareQuantity = ((Media) compareFruit).getSupporto();

        //ascending order
        return this.supporto - compareQuantity;

        //descending order
        //return compareQuantity - this.supporto;
    }
...
}

Arrays.sort(m);
Some more info :
http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
Answer: You can sort it with your own comparator
    m.sort(new Comparator<Media>() {

        @Override
        public int compare(Media o1, Media o2) {
            return Double.compare(o1.getSupporto(), o2.getSupporto());
        }
    });

this will sort it the way you like. If you need this in many pleaces, i would suggest however creating static comparator like:
private static Comparator<Media> supportoComparator = new Comparator<Media>() {

    @Override
    public int compare(Media o1, Media o2) {
        if (o1 != null && o2 != null) {
            return Double.compare(o1.getSupporto(), o2.getSupporto());
        } else {
            throw new IllegalArgumentException();
        }
    }
};

Above code is in class Media, and then you use it like:
    m.sort(Media.GET_SUPPORTO_COMPARATOR());

and its done

java: ArrayList how order


Erro ao tentar exibir uma imageView vetorial (SVG)!

Question: Bom galera, nesse app pretendo fazer um teste inserindo uma imagem vetorial na activity principal.
Fiz o processo de integração todo certinho, como podem ver:

Mas mesmo tendo seguido todo o tutorial, o seguinte erro que aparece, de forma que não dá nem para executar o app:

MainActivity:

package genesysgeneration.ruleoftree;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;

public class Main01Activity extends AppCompatActivity implements View.OnClickListener{

    private EditText et01, et02, et03;
    private TextView tv01, tvTest;
    private double l01, l02, l03, equalizer, lxx;
    private Button btnChange01, btnCompras, btnMoeda;
    private ImageView logo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main01);

        logo.setBackgroundColor(Color.WHITE);
        SVG svg = SVGParser.getSVGFromAsset(getResources(), R.raw.tree);
        logo.setImageDrawable(svg.createPictureDrawable());
        setContentView(logo);

        tvTest=(TextView)findViewById(R.id.tvTest);
        tv01=(TextView)findViewById(R.id.tv01);
        tvTest.setText(String.valueOf(0));
        tv01.setText(String.valueOf(0));

    }

}

OBS - Não transcrevi todo o código como devem ter percebido, pois não há necessidade, já que o restante está funfando liso.
Tutorial em questão (vídeo) => Integrate SVG => (site) Android Coffe
Answer: Provavelmente esse erro se de porque voce etá tentando pegar o arquivo como um item do assets "SVG svg = SVGParser.getSVGFromAsset(getResources(), R.raw.tree);",mas provavelmente a pasta assets não tenha sido definida, para criar ela, clique com o direito do mouse em project e escolha new/folder/assets folder.
tenta assim ó:
//...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main01);

    logo.setBackgroundColor(Color.WHITE);
    // SVG svg = SVGParser.getSVGFromAsset(getResources(), R.raw.tree);
    // melhor voce criar uma pasta assets, copiar o arquivo para ela e usar
    final SVG svg = SVGParser.getSVGFromAsset(getAssets(), "tree.svg");
    logo.setImageDrawable(svg.createPictureDrawable());
    //setContentView(logo);
    // desnecessario essa linha
}
//...

e nunca é recomendado ter o nome de uma activity com numero ou letras maiusculas, assim, se possivel, renomeie a mesma para outro nome que contenha somente letras.
Comment: se vc manja de ingles, vai aqui ó: http://blog.fordemobile.com/2013/01/display-svg-inside-imageview.html
Comment: mudei, errei. era para ser SVG svg = **SVGParser.getSVGFromResource(getResources(), R.raw.tree);** agora dá para executar, mas o app para do nada. olharei o android monitor
Comment: deu uma exceção com oq vc me indicou fazer, irei colocá-la
Answer: Nas versões mais recentes do Android Studio é possível usar arquivos SVG sem recorrer a bibliotecas externas.
Clique com o botão direito do rato em cima da pasta drawable e no menu que abre, escolha new->Vector Asset.
Na janela escolha Local file (SVG, PSD), indique o caminho para o arquivo, clique next e depois finish na janela seguinte.

Fonte: documentação android
Este procedimento cria um arquivo xml(VectorDrawable) que pode ser usado como qualquer outro icon.

Nota 1:
Para usar VectorDrawable em versões inferiores ao Android 5.0 (API level 21) é necessário a Support Library 23.2.0 e configurar o build.gradle da seguinte forma:
//For Gradle Plugin 2.0+
 android {
   defaultConfig {
     vectorDrawables.useSupportLibrary = true
    }
 }

e em vez de android:src deverá usar android:srcCompat.
Veja a documentação para informação mais completa.
Conforme salientado pelo @rsicarelli, a partir da versão 23.4.0 da Support Library é necessário explicitamente fazer o enable da funcionalidade colocando
static {
    AppCompatDelegate.setCompatVectorFromSourcesEnabled(true);
}

no topo da Activity.
Nota 2:
Nas versões mais recentes da Support Library(25.1.1 nesta data), desde que não se preocupe em que a APK tenha mais alguns Kbs, não é necessário aplicar o descrito na nota 1.
O Android Studio gera um PNG por cada VectorDrawable para ser utilizado nas versões inferiores à 21.
Nota 3
A retro-compatibilidade nem sempre é garantida.
Este post explica em forma de diagrama o descrito nas notas.
Comment: @rsicarelli A [documentação/guia](https://developer.android.com/guide/topics/graphics/vector-drawable-resources.html#vector-drawables-backward-solution) não faz referência a isso, no entanto há essa indicação na [Revision 23.4.0](https://developer.android.com/topic/libraries/support-library/rev-archive.html#rev23-4-0). Fiquei sem perceber se `setCompatVectorFromResourcesEnabled(true)` substitui `vectorDrawables.useSupportLibrary = true` ou se é necessário usar os dois.
Comment: A partir da versão `23.4.0` é necessário adicionar a lista `AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);` no topo da sua `Activity` para ter suporte para a API <21. Ref https://goo.gl/HL8wVw
Comment: Realmente a documentação não deixa isso claro, porém os dois métodos são necessários.
Comment: Muito obrigado galera!!! Agora quando tento colocar esse SVG como logo do app aparece uma imagem nada a ver (nativa do android)... Poderia resolver por aqui ou devo fazer uma nova pergunta já que minha questão já foi resolvida?


Kendall's tau for Clayton Copula

Question: When $\theta =-\frac{1}{2}$ the Clayton copula is given by $C(x,y)=(\sqrt{x}+\sqrt{y}-1)^2$. I've been asked to show in this case that Kendall's tau is $-\frac{1}{3}$. Using
$$\rho_{\tau}=4 \int_0^1 \int_0^1 C(x,y)dC(x,y)-1=4 \int_0^1 \int_0^1(\sqrt{x}+\sqrt{y}-1)^2\frac{1}{2 \sqrt{xy}}dxdy-1$$
I find that $\rho_{\tau}=\frac{1}{3}$. I've done the integration twice by hand and once using Mathematica and always get $\frac{1}{3}$. Am I making some kind of mistake or is the question stated wrong?
Comment: Your $C(x,y)$ is not a valid copula.  Try $C(x,y)=\max(0, \sqrt{x}+\sqrt{y}-1)^2$ instead.
Comment: $-\frac{1}{3}$ is correct; the question hasn't made an error there.
Answer: As pointed out by @whuber, the expression for the Copula is
$$C(u,v) = \big[\max \{u^{-\theta}+v^{-\theta}-1,\;0\}\big]^{-1/\theta} , \;\;\theta \in [-1,\infty), \theta\neq 0 $$
When $\theta >0 \Rightarrow u^{-\theta}+v^{-\theta}-1>0$ for the whole joint support, and we can "ignore" the $\max$ operator. But when $\theta<0$ the $\max$ operator becomes effective, and this must be taken into account when performing the integration, since for subsets of the joint support the value of the copula is zero.
An alternative approach could be the following:
Treat the Copula itself as a (univariate) random variable (which in turn is a function of two other random variables):
$$T = C(U,V)$$
Then $T$ has a distribution function called "Kendall distribution function", and it is equal to
$$K_C(t) = t- \frac {\varphi (t)}{\varphi'(t)} \tag{1}$$
where $\varphi(t)$ is the copula's generator function, and the prime denotes the first derivative.
The relation between Kendall's tau and a copula is
$$\tau  = 4 \cdot E[C(U,V)] - 1 \tag{2}$$
and from $(1)$ we have
$$E[C(U,V)] = E(T) = \int_0^1tdK_C(t)$$
Integrating by parts we have
$$\int_0^1tdK_C(t) = tK_C(t)\Big|_0^1 - \int_0^1K_C(t)dt = 1 -\int_0^1K_C(t)dt$$
So Kendall's tau now is
$$\tau = 4\cdot \left(1 -\int_0^1K_C(t)dt\right) - 1 = 3 - 4\int_0^1K_C(t)dt$$
Inserting the expression for $K_C(t)$ we have
$$\tau = 3 - 4\int_0^1\left[t- \frac {\varphi (t)}{\varphi'(t)}\right]dt = 1 + 4\int_0^1\frac {\varphi (t)}{\varphi'(t)}dt$$
which is a general expression for the calculation of Kendall's tau related to a copula.
For Clayton's Copula, its generator function is (for $\theta \neq 0$)
$$\varphi(t) = \frac1{\theta}\left(t^{-\theta}-1\right)$$
Completing the calculations, one arrives at $\tau = \theta / (\theta + 2)$.
Then , for $\theta = -1/2$ we have indeed that $\tau = -1/3$.
Comment: +1 I was considering pointing to a recent answer of yours on math.SE, but I think the present adaptation of it to directly address the question is probably for the better.

Kendall's tau for Clayton Copula


Find $a \in \mathbb{R}$ such that $\int_1^{\infty}\left(\frac{1}{x+2} - \frac{ax}{x^2+1}\right) dx$ converges.

Question: The question goes like this:
'Find $a \in \mathbb{R}$ such that $\int_1^{\infty}\left(\frac{1}{x+2} - \frac{ax}{x^2+1}\right) dx$ converges.'
After computing this integral (maybe in a false way) I end up with the $\lim_  {x\to \infty}\ln(-x-2) + \frac{a\ln\left(\frac{x^2+1}{2}\right)}{2}$, which seems to diverge for all values of a.
Is there something I'm doing wrong?
Comment: compute asymptotics as $x \to \infty$.  This does not requure evaluation of the integrals.
Comment: $a=1\implies$ cancellation...
Comment: May you explain what you mean by cancellation? @BobDobbs
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [here](/help/notation), [here](//math.meta.stackexchange.com/q/5020), [here](//meta.stackexchange.com/a/70559) and [here](//math.meta.stackexchange.com/q/1773).
Comment: $\log(-x-2)$ doesn't make sense as $x\to\infty$.
Answer:
After computing this integral (maybe in a false way) I end up with the $\lim_  {x\to \infty}\ln(-x-2) + \frac{a\ln\left(\frac{x^2+1}{2}\right)}{2}$, which seems to diverge for all values of a.

Some of this is not true. The antiderivative of $f(x) = \dfrac{1}{x+2}-\dfrac{ax}{x^{2}+1}$ is $F(x) = \ln\left(\left|x+2\right|\right)-\dfrac{a\ln\left(x^2+1\right)}{2}$, so using the Fundamental Theorem of Calculus yields
$$\displaystyle \lim_{t\to\infty}F(t) - F(1) = \lim_{t\to\infty}\left(\ln\left(\left|t+2\right|\right)-\frac{a\ln\left(t^{2}+1\right)}{2}\right) - \left(\ln\left(\left|1+2\right|\right)-\frac{a\ln\left(1^{2}+1\right)}{2}\right),$$
which diverges when $a\in \mathbb{R} \backslash \left\{1\right\}$. In fact, we can get rid of the absolute values since we are integrating over the interval $[1,\infty)$ and we can ignore the last expression since it is a constant.
(Answer) To prove $a=1$ is the only value for which this improper integral converges, we can naively evaluate the limit as follows:
$$
\eqalign{
\displaystyle
\lim_{t\to\infty}\left(\ln\left(t+2\right)-\frac{a}{2}\ln\left(t^{2}+1\right)\right) &= \lim_{t\to\infty}\frac{a}{2}\ln\left(t^{2}+1\right)\left(\frac{2}{a}\frac{\ln\left(t+2\right)}{\ln\left(t^{2}+1\right)}-1\right) \cr
&= \lim_{t\to\infty}\frac{a}{2}\ln\left(t^{2}+1\right)\left(\frac{2}{a}\frac{\ln\left(t+2\right)}{\ln\left(1+\frac{1}{t^{2}}\right)+2\ln\left(t\right)}-1\right) \cr
&= \left(\lim_{t\to\infty}\frac{a}{2}\ln\left(t^{2}+1\right)\right) \cdot \left(\lim_{t\to\infty}\frac{2}{a}\frac{\ln\left(t+2\right)}{\ln\left(1+\frac{1}{t^{2}}\right)+2\ln\left(t\right)}-1\right) \cr
&= \left(\lim_{t\to\infty}\frac{a}{2}\ln\left(t^{2}+1\right)\right) \cdot \left(\lim_{t\to\infty}\frac{2}{a}\frac{\ln\left(t+2\right)}{0+2\ln\left(t\right)}-1\right) \cr
&= \left(\lim_{t\to\infty}\frac{a}{2}\ln\left(t^{2}+1\right)\right) \cdot \left(\frac{1}{a}\lim_{t\to\infty}\frac{\frac{d}{dt}\ln\left(t+2\right)}{\frac{d}{dt}\ln\left(t\right)}-1\right) \cr
&= \left(\infty \cdot \dfrac{a}{2}\right) \cdot \left(\dfrac{1}{a}(1)-1\right) \cr
&= \infty \left(\frac{1-a}{2}\right).
}
$$
Notice that any $a \in \mathbb{R} \backslash \left\{1\right\}$ results in the limit diverging. It is only when $a=1$ that we get an indeterminate form $\infty \cdot 0$.
We can go back to evaluating the limit but with $a=1$, yielding
$$
\eqalign{
\displaystyle
\lim_{t\to\infty}
\left(\ln\left(t+2\right)-\frac{1}{2}\ln\left(t^{2}+1\right)\right) &= \ln\left(\lim_{t\to\infty}\frac{t+2}{\sqrt{t^{2}+1}}\right) \cr
&= \ln\left(\lim_{t\to\infty}\frac{t+2}{\left|t\right|\sqrt{1+\frac{1}{t^{2}}}}\right) \cr
&= \ln\left(\lim_{t\to\infty}\frac{t}{\left|t\right|\sqrt{1+\frac{1}{t^{2}}}} + \lim_{t\to\infty}\frac{2}{\left|t\right|\sqrt{1+\frac{1}{t^{2}}}}\right) \cr
&= \ln\left(1+0\right) \cr
&= 0. \cr
}
$$
Since the limit equals $0$, the integral ultimately equals $\ln\left(\sqrt{2}\right)-\ln\left(3\right)$, after some simplifying.
Please do not hesitate to ask any questions if anything is unclear.
Comment: Oh wow! that's quite simpler than then method I did it in, after posting this question, I took a nap and had a "revelation", I noticed that one of the logarithms is multiplied by a over 2, which can be inserted into the logarithm as a power, I then divided both arguments and used some analysis to conclude that a=1 and only 1.
Comment: What is important for us is that there is no mathematical mistake. Explanations can go thousands of years and pages. Lol.
Answer: Combining fractions,
$$\frac1{x+2} - \frac{ax}{x^2 + 1} = \frac{x^2 + 1 - ax(x+2)}{(x+2)(x^2+1)} = \frac{(1-a)x^2-2ax+1}{(x+2)(x^2+1)}$$
The integral converges when the quadratic term in the numerator vanishes.
Answer: Collecting the integrand, we have $\int_1^{\infty}\frac{(1-a)x^2-2ax+1}{(x+2)(x^2+1)}dx$.
Note: The text books everywhere write the limit comparison test for improper integrals with positive integrands: https://services.math.duke.edu/~cbray/Stanford/2003-2004/Math%2042/limitcomp.pdf.
If $a=1$, the integral is $-\int_1^{\infty}\frac{2x-1}{(x+2)(x^2+1)}dx$ and it converges by limit comparison test for improper integrals, comparing $\int_1^{\infty}\frac{2x-1}{(x+2)(x^2+1)}dx$ with the integral $\int_1^{\infty}\frac{2x+2}{(x+2)(x^2+1)}dx$. (The test is simple: Take the ratio of the integrands of the integrals compared, if the limit of this ratio when $x\rightarrow\infty$ is positive real number, the improper integrals have the same character.)
If $a\neq 1$, the integral can be splitted as $\frac{a-2a^2}{1-a}\int_1^{\infty}\frac{1}{(x+2)(x^2+1)}dx+(1-a)\int_1^{\infty}\frac{(x-\frac{a}{1-a})^2+1}{(x+2)(x^2+1)}dx$. The first integral clearly converges. The second integral diveges by limit comparison test, comparing $\int_1^{\infty}\frac{(x-\frac{a}{1-a})^2+1}{(x+2)(x^2+1)}dx$ with $\int_1^{\infty}\frac{x^2+1}{(x+2)(x^2+1)}dx$.


htaccess language rediretion

Question: I have a website, www.thesite.com and an alias www.lesite.com
i need a htaccess redirection:
I would like that, when I go to www.thesite.com/fr, it redirects me to www.lesite.com/fr
Likewise, when I go to www.lesite.com/en, I would like it to redirect me to www.thesite.com/en
I have tried different methods but i only succeed to create infinite loops !----
Options +FollowSymlinks
RewriteRule ^fr$ http://dev.mariage.ch/fr/ [L]
RewriteRule ^de$ http://dev.hortzeit.ch/de/ [L]

OR
RewriteCond %{HTTP_HOST} !^dev\.hortzeit\.ch\/de\/
RewriteRule (.*) http://dev.hortzeit.ch/de$1 [R=301,L]

RewriteCond %{HTTP_HOST} !^dev\.mariage\.ch\/fr\/
RewriteRule (.*) http://dev.mariage.ch/fr$1 [R=301,L]

Comment: already answered here :http://stackoverflow.com/questions/10232722/htaccess-rewrite-based-on-hostname-or-domain-name#10241757 and here : http://stackoverflow.com/questions/6972413/htaccess-rewriterule-two-domains-using-same-server-and-directory
Answer: You can't use path as part of RewriteCond for HTTP_HOST
instead of dev.hortzeit.ch/de  you must use just host part dev.hortzeit.ch
RewriteEngine On
RewriteCond %{HTTP_HOST} !^dev\.hortzeit\.ch  [NC]
RewriteRule ^de(/?.*)$ http://dev.hortzeit.ch/de$1 [R=301,NC,L]

RewriteCond %{HTTP_HOST} !^dev\.mariage\.ch  [NC]
RewriteRule ^fr(/?.*)$ http://dev.mariage.ch/fr$1 [R=301,NC,L]

htaccess language rediretion


How to interpret the overall statistically significant effect of a MANOVA (In words)?

Question: I have the following analysis: I ran a MANOVA with two DVs (both empathy scales) and an IV (gender). Now the $p$-value (.03) tells me that there is a significant difference between men and women. However, I do not know which is higher on which variable. When I then look at the ANOVA table (given with SPSS) output, it tells me that there is no significant difference (all $p$-values larger than .05). How do I interpret this? Had men and women score differently or not?
Also, my supervisor asked me to look at the means, however they are only different by maybe one point, so I cannot see there which one should be larger (and the MANOVA only tells me the joint effect of the two DVs together).
When I ran a t-test to have a look at the individual means, they were also non-significant.
I am a bit lost what to do with this and would highly appreciate some help in regards how to put this interpretation into words.
Comment: What have you looked at?  I searched the obvious on Google and the first link seemed pretty straightforward (it had errors but at least it would put you on the right track). Two things could improve your question. The first is to provide clarification on what all your p-values come from specifically (i.e. what test is 0.03?); and the second is to explain what you have looked at and ask for clarification where you were stuck.
Answer: This answer does not completely address your question about MANOVA and the distinction between univariate and multivariate tests but note that p-values are not all there is to statistical analysis. Looking at the means/plotting them is in any case a good idea.
Thus, it's perfectly possible for a difference to be significantly different from 0 and still very small in some sense. I don't know if "one point" is a lot on your empathy scales but what the test tells you is merely that it would be unlikely to observe it if the rating from men and women were exactly the same. Even if all the tests you performed would reject the null hypothesis, you would still need something else (plots, descriptive statistics, standardized or unstandardized indices of effect size, confidence intervals around these effect sizes, etc.) to fully understand the magnitude of the effect because it's simply not what the test itself is about.
Furthermore, one important point is that "the difference between significant and non-significant is not itself significant". The logic of hypothesis testing requires you to select an error level (often 5%) and stick to it but there is nothing magical about this threshold. Informally, p = .03 is not very strong evidence of a difference and p = .06 is not evidence that the difference is exactly 0. This point is particularly important when comparing different studies or different groups but there is nothing really surprising about two tests producing slightly higher or lower p-values even with the same data and no need to read too much into it.
Answer: The problem you find concerning a statistically significant MANOVA output, but no statistically significant univariate ANOVA's, lies in the very nature of a MANOVA.
A MANOVA differs from several univariate ANOVA's in the fact that you control for mutual relationships. So, you do not only test several 't-tests' or ANOVA's, but there is more to it. This can explain the fact that you do not find seperate significant results, although you're MANOVA is statistically significant. So, apparently gender has an effect on the combination of empathy scales, but not on the empathy scales independently.
For an excellent paper on this difference, check Huberty and Morris' article on the difference between an ANOVA and MANOVA.


Ajax loaded content div class is not applied

Question: I have a page that has a few divs connected in a flowchart via JS-Graph.It. When you click one of the divs, I want it to 1) generate text in a special div 2) generate a popup via click functions attached to the two classes "block" and "channel" in each div. This works when the page is static.
When I add ajax so on click of a button and add more divs, only one of the two classes appears in the HTML source. "Channel" is no longer visible and the function to generate a pop-up on click of a channel class div does not work anymore...
AJAX call:
$("#trace").bind('click', $.proxy(function(event) {
    var button2 = $('#combo').val();
    if(button2 == 'default') {
        var trans = 'Default View';
    }
    if(button2 == 'abc') {
        var trans = 'abc';
    }
    $.ajax({ // ajax call starts
        url: 'serverside.php', // JQuery loads serverside.php
        data: 'button2=' + $('#combo').val(), // Send value of the clicked button
        dataType: 'json', // Choosing a JSON datatype
        success: function(data) // Variable data constains the data we get from serverside
        {
            JSGraphIt.delCanvas('mainCanvas');
            $('.test').html('
' + trans + '
'); // Clear #content div
            $('#mainCanvas').html(''); // Clear #content div
            $('#mainCanvas').append(data);
            JSGraphIt.initPageObjects();
        }
    });
    return false; // keeps the page from not refreshing

}, this));

DIV class: (works in index.php but not transactions.php)
// Boxes
    while($row = sqlsrv_fetch_array($result))
    {
        echo '<div id="'.$row['id'].'_block" class="block channel" style="background:';

Functions:
$(document).on('click', '.block', $.proxy(function(event) {
    var input = $(event.target).attr('id');
    var lines = input.split('_');
    var button = lines[0];
    $.ajax({
        url: 'srv.php',
        data: 'button=' + button,
        dataType: 'json',
        success: function(data)
        {
            $('#content').html('');
            $('#content').append(data);
        }
    });
    return false;
}, this)); // End Application Details

$(".channel").click(function () {
        alert('channel');
    });

Answer: Something about registering with pages, I'm not sure exactly how it works. The fix should be to change your channel click function to be the same as your first and use the .on('click') option.
 found some related reading material. https://learn.jquery.com/events/event-delegation/
Comment: I was playing around and ended up trying that. I think it's taking me in the right direction..


Loop com Oracle

Question: Estou usando a seguinte lógica para um código:
BEGIN
    SELECT * FROM CAT_GRUPO_APRESENTACAO cga WHERE GAPNM_CODIGO_PAI = 8427;
    DECLARE codigos := SELECT * FROM  CAT_GRUPO_APRESENTACAO cga WHERE GAPNM_CODIGO_PAI in(SELECT GAPNM_CODIGO FROM CAT_GRUPO_APRESENTACAO cga WHERE GAPNM_CODIGO_PAI = 8427);
    SELECT * FROM CAT_GRUPO_APRESENTACAO cga WHERE GAPNM_CODIGO_PAI in(codigos)
END;

Em que eu pegaria todos os valores da coluna GAPNM_CODIGO, dadas no primeiro select, salvaria em uma variável, e usaria em um novo select usando o WHERE e o IN. Fazendo isso em forma de loop, ou seja, depois do primeiro SELECT do codigo pai, usaria os valores do GAPNM_CODIGO para a query do where in, e assim sucessivamente, até obter resultado nulo.
Estou com dificuldade em aplicar esta logica com o banco Oracle
Comment: já tentou usar o `FOR`? por exemplo `FOR item in (SELECT ....) LOOP  .. AQUI PODE USAR item.campo e fazer a sua lógica ...  END LOOP`
Answer: BEGIN
  FOR RPAI IN (SELECT *
               FROM CAT_GRUPO_APRESENTACAO cga
               WHERE GAPNM_CODIGO_PAI = 8427)
  LOOP
    FOR RFILHO IN (SELECT *
                   FROM CAT_GRUPO_APRESENTACAO cga
                   WHERE GAPNM_CODIGO_PAI = RPAI.GAPNM_CODIGO)
    LOOP
      /*FAZ ALGUMA COISA*/
    END LOOP;
  END LOOP;
END;

Doc

Loop com Oracle


Precise meaning of the cue-ball being "snookered"

Question: The WPBSA rules define "snookered" as the following:

17. Snookered
The cue-ball is snookered when a direct stroke in a straight line to every ball on is wholly or partially obstructed by a ball or balls not on. If one or more balls on can be hit at both extreme edges free of obstruction by any ball not on, the cue-ball is not snookered.

With this in mind, consider the following scenarios, where the red balls are "on":

Name
Image
Comment

A

The cue ball cannot hit the red ball on the extreme right edge, but the whole ball is "visible" from the point of cue ball.

B

The red ball is partially obscured by the yellow.

C

The "far" red ball is obstructed by the "near" red ball (which is obviously also "on"). If the nearer red ball is removed, the cue ball will not be able to strike the farther red ball on the extreme edge (scenario A).

D

The "far" red ball is obstructed by both the "near" red and the yellow. If the nearer red ball is removed, the yellow red ball would partially obscure the farther (scenario B).

E

The "far" red ball is obstructed only by other red balls. If the middle and nearest red balls are removed, the  "possible angles" would be at least as wide as if the farthest ball was the only one.

My question is: which of these scenarios are considered "snookered" by the rules (resulting in a free ball if encountered after a foul, etc.). Are there any other special cases I overlooked?

This question was inspired by the answers to these two questions which aren't clear in the matter, and also by this image on Wikipedia which states that the red is snookered by the black.
Comment: A-B-C-D seem to be snookered red balls, because they can't "*be hit at both extreme edges free of obstruction by any ball not on*". The angle of the sight must be wider I believe, like on [this image](https://imgur.com/a/Ew6cYlA): the dark lines show the ball is full sight, but light lines show it can't be hit of the right side, because of the yellow ball. As for you last example, we'd have to draw the lines to see if it fits I believe. Added as a comment as I don't know if it's enough for an answer...
Comment: @OldPadawan - images A and C show the "wider" angle of sight, they're included precisely for the reasons you mentioned (the "shadows" touching the red ball in image A represent the cue ball striking the red on the extreme edge). If you're sure that ABCD are all snookers and E is not, ideally with a source, then that would be enough for me to warrant an accepted answer.
Comment: well, I'm conducting more research right now, because that's *my* call, and it isn't 100% positive, and I don't want a tick on a bad answer ;)
Answer: According to the EPA - English Pool Association in their "Foul Snookers and Foul Jaw Snookers" section, your following situations are:

A: This situation IS a "foul snooker" to the player on reds, but not if taking a shot that does not follow a foul.
B: This situation IS a "foul snooker" to the player on reds but not if taking a shot that does not follow a foul.
C: This situation IS a "foul snooker" to the player on reds, but not if taking a shot that does not follow a foul.
D: This situation IS a "foul snooker" to the player on reds but not if taking a shot that does not follow a foul.
E: This situation IS NOT a "foul snooker" to the player on reds, as you cannot be snookered by a ball of your own colour.
Comment: Are you sure about points B and D? After reading through the article you linked, it seems that none of the situations A-D are "total snookers' as defined by the article, since you can  strike the left edge of a red with a straight shot, in all situations.
Comment: it seems this is, *after* a foul, but not before a regular shot.
Comment: After carefully reading the article I'm pretty sure that A-D are all "foul snookers'" (snookers after a foul), and *none* of A-E are "total snookers'" (snookers' after a regular shot) - there's always a straight line to directly hit a red. Since the article has excellent explanations, if you correct your answer I'd be happy to accept it.
Comment: (I noticed I have messed up the "shadow" of yellow ball in D, it's too straight; it should look more like B. I will correct it later)
Comment: Humm... I don't get it the way you see it. After a foul, you need to be able to hit both edges on the finest cut. ABCD should therefore be "foul snookered" balls. B & D are also a regular snookered ones according to image #2 from the link, don't you think?
Comment: I believe B & D are situations similar to image #3 from the link, not #2:
[here](https://i.imgur.com/sSobaGN.png) [are](https://i.imgur.com/v32UJtN.png) [some](https://i.imgur.com/JjmITpC.png) images that show that reds in B & D are directly hittable.
Comment: Maybe you should include/modify the images, either in your question or in the answer, or both?


PHP code contextual filter (arguments)

Question: I try to display a list of content with exposed filter in Drupal 7 and Views 3, I create a page and it works, but I also want to display a map with the filter, so I create a block for the gmap and for get the information about the filter I add a contextual filter with php code like this (where province is the name of the field)
return $_GET["province"];

In Drupal 6 it works this method, but in Drupal 7 I receive this error

Notice: Undefined index: province in eval() (line 1 of /pathtomodule/views/plugins/views_plugin_argument_default_php.inc(49) : eval()'d code).

So where is the error, I return only one argument (I know that I need some control if the code is null, but in this case I )
Comment: Did you check the parameter is passed through the URL? Is AJAX enabled for that view?
Comment: Thanks, i try to enable ajax and disable but there are no change, the same error, the views is a block, because i use data module and for the exposed filter need a page, yes the parameter is passed correct from the url, i also try with this code:

if isset($_GET["distance[search_distance]"]) {
return $_GET["distance[search_distance]"];
} else {
return "100";
}

But i receive:

Notice: Undefined offset: 1 in location_handler_argument_location_proximity->query() (line 119 of ...
Answer:
Notice: Undefined index: province in eval() (line 1 of /pathtomodule/views/plugins/views_plugin_argument_default_php.inc(49) : eval()'d code).

This error occurs when the array key province does not exist. The PHP documentation goes into greater detail - http://www.php.net/manual/en/language.variables.basics.php

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name... E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

Instead of
return $_GET["province"];
Use isset() logic. Also, you shouldn't be directly accessing $_GET, $_POST or $_REQUEST; best practice is to use drupal_get_query_parameters()
$param = drupal_get_query_parameters();
if (isset($param['province'])) {
  return $param['province'];
}
return NULL;

To address the problem in your comment:

But i receive: Notice: Undefined offset: 1 in location_handler_argument_location_proximity->query()

This is (for all intrinsic purposes) the same as the undefined index; location_handler_argument_location_proximity->query() is expecting an array with at least two elements (offset 0 and 1), and that method expected, but did not receive an array with two elements. It might not even be getting an array.

PHP code contextual filter (arguments)


Show/hide working inconsistently on a Jquery imagemap

Question: I'm working on an imagemap that not only is hi-lighted, but also does a show/hide on a some additional information on a Drupal site:
http://dev-wateraid.pantheonsite.io/where-we-work
If you hover over countries like Canada you'll see the DIV show up, but if you hover over the United States the area is hi-lighted but it doesn't trigger the show/hide -- similar with Sierra Leone, South Africa, the UK, Papua New Guinea, and a few others.
The code I'm using to do the show hide is:
$('area').on({
   mouseover : function(e){
   var $this = $(this),
   $office = $('#'+$this.prop('alt'));
   $($office).removeClass("hidden");
},
   mouseout : function(e){
   var $this = $(this),
   $office = $('#'+$this.prop('alt'));
   $($office).addClass("hidden");
}
});

The image map holds the alt tag which is then used to show/hide a div:
<area coords="96,67,97,61,76,40,69,45,55,36,55,-20,-4,-31,-40,-15,-41,-12,-20,0,-23,3,-31,2,-31,-1,-47,5,-39,11,-27,11,-20,9,-19,16,-29,21,-33,19,-39,29,-35,33,-37,36,-29,40,-25,38,-23,41,-23,46,-17,44,-12,47,-5,45,-7,52,-35,68,-33,69,-14,61,9,45,5,43,16,32,14,43,29,38,30,34,34,33,45,38,58,40,59,40,60,41,71,48,79,59,81,57,87,67,90,66" shape="poly" href="/" alt="United States">

This is the div that would be toggled to be show with the United States information.

United States

 The America team helps to coordinate and fund operations across our country programs, with Nicaragua a particular focus.

I keep looking for reasons most of the countries might work but others wouldn't -- spelling is consistent -- I don't believe there are any hidden characters.
I've validated the code as much as I could, but I just can't see it.
Answer: I believe the issue may be the space in the "id", for example
id="United States"

may actually be interpreted as
id="United"

Answer: jQuery selector can't handle "#United States"... It pretty much ignores the "States". So if you really need the ID to be "United States" you can use:
$("[id='"+$this.attr('alt')+"']")

Or you can just change the 'alt' and 'id' to "UnitedStates".


disproving the set is connected

Question: I am looking for a neat prove for If the closure of a set in $R$
is connected
too
Can you help ..
(concise explanition may help me)
Comment: The closure of $\mathbb{Q}^n$ is $\mathbb{R}^n$ which is a counterexample.
Comment: What's the statement you want to disprove? "If $A\subseteq\mathbb R^n$ such that the closure of $A$ is connected, then $A$ is connected for all $n\in\mathbb N$", or is it "There is an $n\in\mathbb N$ such that if $A\subseteq\mathbb R$ has a connected closure, then $A$ is connected"? Because in the former case, it's perfectly fine to give $\mathbb Q\subset\mathbb R=\mathbb R^1$ as a counterexample. If it's the latter, just take $\mathbb Q\times\mathbb R^{n-1}$, the proof is then the same as for $\mathbb Q\subset\mathbb R$.
Comment: How would you do it for $\mathbb Q\subset\mathbb R$? You said that one was easy. For $\mathbb Q\times\mathbb R^{n-1}\subset\mathbb R^n$ it's only a very slight variation.
Comment: The sets $ ( (-\infty,\sqrt{2}) \cup (\sqrt{2},\infty) ) \times \mathbb{R}^{n-1}$ are open, disjoint and contain $ \mathbb{Q}^{n}$.
Comment: Look at the one answer you have by now. It explains exactly that.
Comment: @samuelVAN. You need to do some work yourself. If you can show that the closure of the rations is the reals you can extend this to the $n$ dimensions.
Comment: @samuelVAN. Since for any $x \in \mathbb{R}^n$ there is a sequence $q_k \to x$ where $q_k \in \mathbb{Q}^n$ we see that any closed set containing $ \mathbb{Q}^n$ must contain $\mathbb{R}^n$.
Answer: $\mathbb{Q}^n$ seems good to me.  You just need to show that there's a point with rational coordinates arbitrarily close to any point in $\mathbb{R}^n$.  Let $x=(x_1,x_2,\dots,x_n)\in\mathbb{R}^n$.  Given $\varepsilon>0$, for each $1\leq k\leq n$ there is a $y_k\in\mathbb{Q}$ such that $\mid x_k-y_k\mid<\frac\varepsilon n$.  The let $=(y_1,y_2,\dots,y_n).$  We have $\mid x-y\mid<\varepsilon$.
Comment: @samuelVAN. I don't understand what you are trying to say.  What is supposed to equal $\emptyset$?  Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) so I can read what you're writing.

disproving the set is connected


Calculadora em Java

Question: Estava tudo indo bem até a parte em que deveria aparecer o resultado.
public static void main( String[] args)
    {
        Scanner in = new Scanner(System.in);
        int num1,num2,resul;
         String sinal;
        System.out.println("Olá, entre com o primeiro numero: ");
        num1 = in.nextInt();
        System.out.println("Olá, entre com o segundo numero: ");
        num2 = in.nextInt();
        System.out.println("Soma (s) Menos (m) Vezes (v) Dividir (d): ");
        resul = in.nextInt();
        sinal = in.nextLine();

        if(sinal.equals ("s"))
        {
            resul = num1 + num2;
            System.out.println("Resultado final "+resul);
        }
        else if (sinal.equals ("m"))
        {
            resul = num1 - num2;
            System.out.println("Resultado final "+resul);
        }
        else if (sinal.equals ("v"))
        {
            resul = num1 * num2;
            System.out.println("Resultado final "+resul);
        }
        else if (sinal.equals("d"))
        {
            resul = num1 / num2;
            System.out.println("Resultado final "+resul);
        }
     }

Comment: Não sei não haha, primeira vez em java!
Comment: Luiz, não precisa colocar "resolvido" no título. Só o fato de vc ter aceito a resposta já indica que ela está resolvida.
Comment: Ops haha, foi mal e obrigado pela dica!
Answer: Um dos problemas é esta linha:
resul = in.nextInt();

O valor de resul será calculado com base nos valores já lidos, então não faz sentido você lê-lo do Scanner. Pode remover esta linha.
Em seguida, o nextLine() chamado logo depois de um nextInt() consome a quebra de linha (o ENTER que o usuário digitou após o número), e o sinal ficará vazio (por isso ele não entra em nenhum dos if's depois).
Em vez disso, você pode usar next():
System.out.println("Olá, entre com o primeiro numero: ");
num1 = in.nextInt();
System.out.println("Olá, entre com o segundo numero: ");
num2 = in.nextInt();
System.out.println("Soma (s) Menos (m) Vezes (v) Dividir (d): ");
sinal = in.next();

Outro detalhe é que, ao dividir dois inteiros, o resultado será arredondado (7 / 2 dá 3;  2 / 5 dá zero, etc). Se quiser o resultado mais preciso, com as casas decimais, troque os valores para double:
double num1, num2, resul;
System.out.println("Olá, entre com o primeiro numero: ");
num1 = in.nextDouble();
System.out.println("Olá, entre com o segundo numero: ");
num2 = in.nextDouble();
System.out.println("Soma (s) Menos (m) Vezes (v) Dividir (d): ");
sinal = in.next();

Comment: Muito obrigado!!! Vou tentar aqui.
Answer: Não tive a oportunidade de testar devido a alguns fatores, e ainda não posso comentar (logo considere isso como um comentário) , porém imagino que o a ordem em que você entra com informações aqui possa ser o problema.
Já que pode estar confundindo o que está armazenado nas variáveis
System.out.println("Soma (s) Menos (m) Vezes (v) Dividir (d): ");
sinal = in.nextLine();
resul = in.nextInt();

Comment: Opá, tentei aqui mesmo assim não foi (de qualquer forma obrigado!!)

Calculadora em Java


dynamic query return zero value

Question: i am trying to return some result from my table but my query return none result
here is how i execute my stored procedure
EXEC spLog '145',' ','2531'

and this is my stored procedure example, the concert is the same, return some value from my table
Created Procedure spLog
 @logID nvarchar(400),
 @logAction nvarchar(400),
 @userId nvarchar(400)
AS
Begin
DECLARE @query nvarchar(4000)

if(LEN(@logID)>0)
BEGIN
SET @query = @query + 'Select * From LogTable where logID in ('+@logID+') AND userID = '+@userId + ''
END
if (LEN(@logAction)>0)
BEGIN
SET @query = @query + 'Select * From logAction where logAction in ('+@logAction+') AND userID = '+@userId + ''
END

EXEC sp_executesql @query

END

the column naming and table naming is just an example, ignore it, my 2 table consist of item that i want but my return result was none, it should return me something instead of none =(
my expected result is [logTable result]+[LogAction result] or [logTable result] or [LogAction result]
Comment: Try to replace `logID in ('+@logID+')` with `logID = '+@logID+'`
Comment: @AndreyGordeev my parameter format will be something with comma =) eg '145,156'
Answer: You have declared the @query variable but have never set it's initial value - thus having it being NULL at the beginning.
DECLARE @query nvarchar(4000)

Later you concatenate a string to your variable, and concatenating NULL + 'something' will still make it NULL
SET @query = @query + 'Select * From LogTable where logID in ('+@logID+') AND userID = '+@userId + ''

Just replace it with
 SET @query = 'Select * From LogTable where logID in ('+@logID+') AND userID = '+@userId + ''

or set your variable to blank string earlier up:
DECLARE @query nvarchar(4000)
SET @query = ''

Comment: Just use `SET @query = ''` at the beginning, and leave `SET @query = @query + ' SELECT...'` in your ifs
Comment: And make sure to add space between two queries - or even better - add semi-colon at the end of both queries + '; '
Comment: you are right, but i want to make use of 2 query, i cannot just run for one query
Comment: i just try, it doesnt work, when logid & logaction exist, my logaction result will replaced the logid result, my expected result is logid + logaction

dynamic query return zero value


52 cards are randomly drawn one by one and without replacement. What is the probability that an ace will appear before any of the cards 2 through 10?

Question: From an ordinary deck of 52 cards, cards are randomly drawn one by one and without replacement. What is the probability that an ace will appear before any of the cards 2 through 10?
Consider the sample space Ω to be the set of all possible sequences of 52 cards drawn from the deck
(without replacement). So we do not remove the Jacks, Queens and Kings from the deck.
I am struggling... the correct answer is 0.1 but I can't reach the right solution.. please help me
Comment: Hint:  the face cards have no meaning here, just the $40$ cards that you are watching for, $4$ of which are Aces.
Comment: If you truly insist on using the sample space as all possible sequences of all fifty two cards... consider counting by breaking into cases based on the position of the first ace.  If the first ace is at the front of the deck, choose which ace it is in $4$ ways and then order the remaining $51$ cards, giving $4\cdot 51!$ arrangements.  If the first ace is second from the top, pick which face card appears and then which ace giving $12\cdot 4\cdot 50!$ arrangements, and then $12\cdot 11\cdot 4\cdot 49!$, then $12\cdot 11\cdot 10\cdot 4\cdot 48!$ and so on...
Comment: An important observation however that the other answers are trying to point out is that this is a very poor choice for sample space and there are many more convenient choices that we can make instead while still keeping the elements in the sample space equiprobable.
Answer: Let's look at the first non-face card that appears. There are 40 possible cards, and 4 of these cards are aces. The probability that this card is an ace is 4/40.
(the statement "The first non-face card that appears is an ace" is equivalent to "an ace appears before any of the cards 2 through 10")
Comment: Can you please explain a bit more in detail... I think your solution is shortcut which is better but  do you also know another way to
 Use the following events:
• Ai be the event 'ith card is an ace'.
• Bi be the event 'All cards before the ith card are Jacks, Queens or Kings'.
Comment: See my answer for more details, then accept Air Conditioners.
Answer: You seek the probability that one from the four aces is the first from the $40$ non-royal cards encountered.
There will be $0$ to $12$ royal cards in the deck before the first of the $40$ remaining cards is encountered.   Four of these $40$ cards is an ace, so the probability that an ace is encountered first among the non-royal cards is clearly $1/10$.

Consider the sample space Ω to be the set of all possible sequences of 52 cards drawn from the deck (without replacement). So we do not remove the Jacks, Queens and Kings from the deck.

We do not remove them, but we may safely ignore them.
Still, if we insist on not doing so, there are $52!/40!$ ways to select places in the deck for the 12 royal cards and arrange them.   For each of these arrangements, there are $40!$ ways to arrange the remaining cards.   Among these arrangements there are $4\cdot 39!$ in which one from the four aces are placed before the other thirty nine cards.
Thus there is a total of $52!$ ways to arrange the cards in the deck, among which there are $52!\cdot 4/40$ ways to arrange the cards so an ace occurs before the first non-royal.
Hence the probability that an ace is encountered before any other non-royal is simply $1/10$.
Comment: Thank you guys!!! very clear now!! :)


Delete item for todo app in with $emit 2 level up or 1 level up?

Question: I have 3 .vue here: App.vue (default), Todos.vue and Todoitem.vue. I am following the tutorial from https://www.youtube.com/watch?v=Wy9q22isx3U&t=2458. May I know why the author in TodoItem.vue emit id two level up to App.vue to perform the method to delete? Is it best practice or better coding style? Is it easier to just go up one level for Todos.vue to do the same? Below is my one level up approach for any comment.
Below is my TodoItem.vue code

<template>

      <input type="checkbox" v-on:change="markComplete" />
      {{todoObj.title}}
      <button @click="$emit('del-todo',todoObj.id)" class="del">x</button>

</template>

Below is my Todo.vue code

<template>

Todo List2

      <MyTodoItem v-bind:todoObj="todo" v-on:del-todo="deleteTodo" />

</template>

Below is my App.vue code

<template>
  <MyToDos v-bind:ptodos="todos" />
</template>

Comment: Simple... you should not modify prop values. In fact, there should be a warning shown in your console
Answer: If you can do it with one level up it's better. To have multiple props on each child can be a bad practice called prop drilling.
Vuex is a good alternative to avoid to get props nested.
Comment: You say it's a _"bad practice"_ but link to an article with a section titled [_"Why is prop drilling good?"_](https://kentcdodds.com/blog/prop-drilling#why-is-prop-drilling-good)


How to show a block only if a specific user is logged in?

Question: I have a block which act as a menu. And the block is created dynamically like that:
$menu_block = array(
    'module' => 'menu',
    'delta' => 'clientmenu' . $account->uid, // the id of the block
    'theme' => 'MYTHEME', // the current theme
    'title' => '<none>', // dispaly no title
    'visibility' => 1, // it is displayed only on those pages listed in $block->pages.
    'region' => 'menu',
    'status' => 1,
    'pages' => $onlythispages, // display the menu only for this client
);

drupal_write_record('block', $menu_block);

And content of the variable $onlythispages is:
// page to display the menu
$onlythispages = 'client/' . $account->name . '
client/' . $account->name . '/*' . '
all-products
product/*';

I created one menu for each created user. Each user has personal (only he can access) pages like:
client/' . $account->name
client/' . $account->name . '/*'

And each user has some common pages which share with all users, pages like:
all-products
product/*

So the problem is that when I go to common pages I see all the "menu blocks" from all the users. So is there a way to show a block only if a specific user id, which actually is the currently logged in user?
I use hook_node_access to handle the access to a node but, how can I do it handle the access to block?
Answer: If only a block needs to be shown for each user, then what I would do is to implement the block in a module that changes the content of the block basing on the currently logged-in user. The visibility settings are also used for blocks implemented by third-party modules.
Comment: Agreed, I would definitely not make a new block for each user. I would make one block, and change the content per-user.
Answer: Below is an answer to what I think this question is really about, i.e. "So is there a way to show a block only if a specific user id, which actually is the currently logged in user?".
Part 1: Rules block visibility
You should be able to get this to work using the Rules block visibility module. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

Need to show a block only for users registered more than a month ago?
Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
What about displaying or hiding a block based on current weather conditions?

All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules intercept the actual user who's using the site, i.e. if it is YES or NO (a boolean, right?) the user with a specific uid. What follows details the steps for a block to only be shown to the user with uid = 1 (replace the 1 in it for any other value for uid).
Part 2: Create an appropriate Rules Component
The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

Configuration is done on a per-block basis. To control a block
  visibility using a rule component, go to the block settings page,
  scroll down to the "Rules" tab, and select the Rules component that
  you want to use.
Notice that to be able to be used by this module, a Rules component
  must be constructed in a very specific way. See the next section for
  more information.

This module comes with 2 sample Rules Components. By looking at these samples, I was able to create another Rules Component which looks like so:
{ "rules_block_visibility_show_block_for_user_1" : {
    "LABEL" : "Show block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

You should be able to import this rule in your own environment.
What this Rules Component does is "only" return a boolean (1 or 0), based on the condition if the user's uid is YES or NO equal to 1.
With that, we're coming close to an actual answer to your question.
Part 3:
Head over to the "Block" settings for the block you want to hide for the user with uid = 1. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "Rules". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.".
And guess what, in my case I just selected my Rules Component from Part 2
Note: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.


If $(u_n)\to 0$, find if the quotient of Gagliardo seminorms $\frac{[u_n]^2_{s_1}}{[u_n]^2_{s_2}}$ is $o(1)$

Question: Let $n\ge 2$, $0<s_1<s_2 <1$ and $(u_n)_n$ be a sequence such that
$$u_n\to 0 \text{ in } L^r(\Omega), \ \ r\in [1, 2^*_{s_2})$$
where $2^*_{s_2} = \frac{2n}{n-2s_2}$ is the critical Sobolev exponent for $s_2$ and
$$u_n\to 0 \text{ a.e.}$$
Let $[u_n]_{s_i}$, $i\in\{1, 2\}$ be the Gagliardo seminorm of $u_n$, i.e.
$$ [u_n]^2_{s_i}=\iint_{\mathbb R^{2n}} \frac{|(u_n(x) -u_n(y)|^2}{|x-y|^{n+2s_i}} dx dy.$$
I am trying to prove that (but I am not sure if that's true)
$$\frac{[u_n]^2_{s_1}}{[u_n]^2_{s_2}} = o(1) \quad\text{ as } n\to +\infty.$$
$\textbf{Notation:}$ we say that $f(x) = o(g(x))$ as $x\to x_0$ if $\lim_{x\to x_0} \frac{f(x)}{g(x)} =0.$
The only thing I got in mind so far is to use Proposition 2.2 (with $\Omega =\mathbb{R}^n$) of the paper Hitchhiker's guide to the fractional Sobolev spaces to say that $[u_n]^2_{s_1} \le c [u_n]^2_{s_2}$ where $c=c(n, s_1)$ to say that
$$\frac{[u_n]^2_{s_1}}{[u_n]^2_{s_2}}\le 1,$$
but it does not help me to say or not if $\frac{[u_n]^2_{s_1}}{[u_n]^2_{s_2}} = o(1)$.
I hope someone could help. Thank you.
Comment: In which space is $u_n$ and in what sense does it converge to $0$ ?
Comment: @Gribouillis information added. Thanks.
Answer: As it is currently stated, the conjecture is false.
Take $\phi \in C^\infty_c(\Omega)$ a non-zero smooth function. Let $u_n := \frac{1}{n} \phi$. On the one hand, $u_n \to 0$ in any $L^r(\Omega)$ (and in fact, in any space). On the other hand
$$
\frac{[u_n]_{s_1}^2}{[u_n]_{s_2}^2} = \frac{[\phi]_{s_1}^2}{[\phi]_{s_2}^2} \neq o(1).
$$
You probably want to add another assumption preventing this situation.


Prove a student participates in all 2009 available courses.

Question: In a university there are available 2009 courses in total. Each course has 45 enrolled students. Between every 2 courses there is exactly one student who was enrolled in both. Prove that there is a student who has enrolled in all of the courses.
I tried building a hypergraph where the courses are nodes and the students edges but this did not bring much. Any help is appreciated.
Comment: What's the source of the problem?
Comment: The edges should be connected by the students that are common to the two classes.  Is that what you meant?
Comment: @MishaLavrov i got it from lectures
Comment: @IanJ I am not sure what the representation of the data structure should be. However what is meant is that between any two courses a single common enrolled student exists
Answer: Assume not. Then, we claim that a student can be in at most $45$ courses.
Proof: Take a student $S$ and a course $C$ such that $S$ is not in the course $C$. Let $E$ be the set of courses which contain $S$. Now, for every $E_i$ in $E$, we have $E_i \cap C$ contains exactly one student $e_i$. Note that these students are all distinct. So, if $\lvert E \rvert > 45$, then we would have a contradiction since $C$ contains $45$ students.
Now, let $C$ be a course. Find $n$ courses with at least $1$ student from $C$ ($C$ is not among these). By claim, we know that $n \leq 45 \cdot 44 < 2008$. So, there is a course which does not intersect with $C$, which is a contradiction.
Comment: @saulspatz If not then those courses would both contain that student and $S$.
Comment: "Note that all these students are distinct."  Why is that?


Distribuir valores em coluna, SQL

Question: Estou extraindo dados de uma tabela com a seguinte query:
SELECT
[nu-cpf] as CPF, [nome segurado] as NOME, '' as IdentificacaoCliente,
'' as CodigoBeneficio,
CONCAT([nu-ddd],[nu-telefone]) TelefoneResidencial,
'' as TelefoneCelular,'' as TelefoneAlternativo,cast([dt-nasc] as date) as
DataNascimento, '1' as unidade

FROM
mac_all

e preciso que a coluna 'unidade', a qual atribuo o valor '1' tenha, distribuídos igualmente, 4 valores - digamos, a título de exemplo os valores: 1,41,51,61.
Desta forma, se a minha query acima retornasse 100 linhas, a coluna "unidade" teria as 25 primeiras linhas com o valor '1', as 25 linhas subsequentes o valor '41', depois 51 e assim sucessivamente.
Se fossem apenas 2 valores, eu poderia usar a cláusula "top 50 percent", mas como são 4, desconheço maneiras de fazer isso funcionar. Existe alguma maneira de fazer no próprio código SQL? Ou preciso extrair os dados e fazer isso manualmente via excel, como tenho feito?
Comment: Nugo, a pergunta não está clara, sugiro exemplar com mais detalhes e tb compartilhar o código `sql`
Comment: Obrigado pela ajuda, reformulei minha pergunta, acredito que tenha ficado mais clara agora!
Comment: Qual é o critério para ordenar o resultado da consulta, de modo a gerar valores para a coluna `unidade`?
Answer: Uma opção é o uso da função de classificação NTILE para dividir o resultado da consulta em blocos, numerando-os sequencialmente, e então associando cada valor a um bloco. Como exemplo foi utilizada a coluna nu-cpf como critério de ordenação.
-- código #1 v2
-- informe os valores a distribuir no resultado da consulta
declare @Valores table (Ordem int identity, Valor int);
INSERT into @Valores (Valor) values (1), (41), (51), (61);

-- calcula a quantidade de valores a distribuir
declare @QtdV int;
set @QtdV = (SELECT count(*) from @Valores);

--
with Consulta as (
SELECT [nu-cpf] as CPF, [nome segurado] as NOME,
       '' as IdentificacaoCliente, '' as CodigoBeneficio,
       CONCAT([nu-ddd],[nu-telefone]) as TelefoneResidencial,
       '' as TelefoneCelular,'' as TelefoneAlternativo,
       cast([dt-nasc] as date) as DataNascimento,
       ntile(@QtdV) over (order by [nu-cpf]) as NBloco
  from mac_all
)
SELECT CPF, NOME, IdentificacaoCliente, CodigoBeneficio,
       TelefoneResidencial, TelefoneCelular, TelefoneAlternativo,
       DataNascimento, V.Valor as unidade
  from Consulta as C
       inner join @Valores as V on V.Ordem = C.NBloco;

Na tabela @Valores devem ser informados os números que farão parte da coluna ìdentidade, na ordem em que devem ser distribuídos.

Distribuir valores em coluna, SQL


this.hostContainer is undefined in Acrobat scripting

Question: I have a query. Actually, I am using an acrobat 9 pro to create editable pdf and also have a submit button in pdf itself to submit a form to a backend server. My main concern is to send pdf data to the backend server for further processing. I am using this.hostContainer.postMessage(msg) to communicate between embedded pdf and the browser. The major problem here is this.hostContainer is always undefined in pdf scripting.
Also, I have been searching for this very long time and I could not find any solution though.
Some forums even say that Acrobat 9 pro have a problem with hostContainer.
Looking forward to your help. Thanks
Comment: *"Acrobat 9 pro have a problem with hostContainer"* - where exactly does Adobe specify that `hostContainer` member?
Answer: The HostContainer Object is only available when the PDF is being displayed in IE now, not Edge or any other modern browser. It's also not available at all on macOS or mobile. I suggest not bothering with it at all because you don't actually need to embed the PDF in a browser in order to submit the form data to a server. You just need the submit URL to be fully qualified and the submit button will work.
Comment: I'd suggest you rethink your solution. HostContainer with PDF is just not a reliable long-term solution. In Acrobat / Reader, you can use the Net.HTTP methods to securely submit the data as well as set header values and authentication.
Comment: Thank you so much, Joel Geraci. Actually, I want to submit the pdf to secure API using session token in the request header which is only possible if I could communicate between the browser and embedded pdf.
Comment: Yes, Joel Geraci, I agree with your solution but all my tokens are stored in local Storage in a browser which I cannot access from embedded pdf, acrobat scripting to set request header using Net.HTTP.


unable to get intellisense for knockout.js file

Question: i am working on asp.net website and we are using knockout.js. I am not able to get javascript intellisense for knowkcout.js file. I tried adding the below snippet but still i am not getting any intellisense.
<% if(false){ %>

<% } %>

This is how my head block looks like:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<% if(false){ %>

<% } %>

    <title>Untitled Page</title>

Comment: Try putting it in the head tag as well?
Answer: Put along with the knockoutjs.2.0.0.js file an other one - debug version of kcnockoutjs knockout-2.0.0.debug.js and Visual Studio would be able pick intellisense up. You do not need  including this file using


Client to use the slave when the master is down in MySQL replication

Question: Is it possible for the client to use the slave when the master is down in mysql replication?
I have already set up a simple MySQL replication having a master and a slave.
The client connects to the master to access the database; any changes made to the master server is replicated onto the slave. How shall I configure the client so that when the master server is down, the client automatically connects to the slave server?
I am using MySQL Server 5.1 and MySQL workbench 5.2 CE. I edited the my.ini files for both master and slave.
The client uses a J2EE application.
What additional commands must I input in the master my.ini file to make the changes?
Also is there a way to increase or decrease the time interval between replications?
Answer: Your last question is unclear - and irrelevant to the question posed in the title.
For configuring your client, that depends on the client, not the master database. Often, the change is hidden from the client by using a single IP and having one or the other system take over from the other when necessary.
The set up you are asking about is master fail-over: when the master dies, the slave can be promoted to master status and remain so until the true master returns. Returning the old master back to operations can be a little tricky - the replication needs to be preserved. It may even be easier to return the old master back to operations as a slave instead.
As far as the my.ini file goes, I could be wrong, but I don't think any changes are necessary unless you want the system to retain its master status (during a reboot) after a failover. I believe the changes are all made within MySQL itself.
More on this topic can be had from the book MySQL High Availability published by O'Reilly.