String equivalent of =+ but existing string as appended rather than prepended to new string

Question: I'm using PyCharm (version 4.0.3) and getting a style warning Assignment can be replaced with augmented assignment  on the second line of the following code*:
abc = 'and cheese'
abc = 'ham' + abc

* - My code is not really this code but it generates the same error. I am programmatically generating two strings and I have to / would like to generate the first line (second part of the English syntax) before the second line (the first part of the English syntax).
But I don't know what augmented assignment could do this.  If the code were like this (where the first part of the desired final string could be generated first in execution order)
abc = 'ham'
abc = abc + 'and cheese'

then I believe the problem is trivially resolved with the += operator:
abc = 'ham'
abc += 'and cheese'

But in the context of my problem (where the 'and cheese' part is declared before 'ham'), is there a way to satisfy this warning?
Comment: @BhargavRao: do you mean the problem with string concatenation is that it isn't commutative, or the problem with string concatenation is that PyCharm doesn't understand it? ;-)
Comment: This sounds like a bug in PyCharm, but that seems unlikely - could you post your actual code so we can be sure?
Comment: The code I provide generates the same warning in PyCharm
Comment: I'm at a loss to explain it then, my best guess is a bug in PyCharm. Hopefully someone else has a better answer :-(
Comment: Bro, this is the problem with string concatenation. Use `format` always.... The problem is (I think, it considers you are doin arithmetic `+` and not concat and so the problem)
Comment: @BhargavRao - `format` doesn't do in-place operations. And string concatenation is generally acceptable.
Comment: @tdelaney What about `abc = 'ham {}'.format(abc)`
Comment: @BhargavRao - pycharm says the operation can be replaced with augmented assignment, that's what the question is about. OP is already doing concatenation, which is fine.
Comment: @SteveJessop I am with you on the second point.
Comment: Presumably PyCharm doesn't get equally confused by `x = y / x` and claim you could replace that with augmented assignment, since it doesn't expect `/` to be commutative.
Comment: @tdelaney Yeah, That's what I meant to say. The prob is with PyCharm
Comment: @SteveJessop Ok. Then why on earth is it gettin confused with `+`? Is it bcoz arithmetic `+` is commutative?
Comment: I'm using PyCharm 4.0.1 and I do not get this warning.
Comment: @BhargavRao: that's my guess, but I don't use PyCharm so I can't check for myself what tickles it (still less in what versions of PyCharm). The hint is clearly wrong in this case, so I'm guessing that it's over-eager about the properties of `+` since that makes at least *some* kind of sense. It could just as well be a complete facepalm bug due to a typo in the PyCharm source or whatever :-)
Comment: @SteveJessop Yeah, Perhaps we may get a clue in bug reports of PyCharm (if any) ...
Comment: But then if Pycharm has to consider the fact that any operator may be overloaded and loose any commutative property it may have had (as I think it should), this type of inspection is definitely broken, isn't it ? Especially since there are also reflected operators
Comment: I am still getting this in 4.0.4
Answer: There are more than one way to skin a cat (or to concatenate strings).
You can concatenate using str.join but it may be marginally less efficient for small lists:
abc = " ".join((abc, 'and cheese'))

Or using format:
abc = "{} {}".format(abc, 'and cheese')

But really, the correct way to silence the warning is to submit a bug report for the IDE, because it looks like there is nothing wrong with your code (someone in the comments already pointed out it is not reproducible on the last version).
Comment: Oh, if your version is newer then it looks like a regression on their Python linter.


Capturar id do datagrid

Question: Se eu quero capturar o valor da coluna ID da linha selecionada, eu preciso necessariamente usar o vento SelectionChanged, que é para ser disparado a cada troca de linha no datagrid? Ou só com o dataGridView1.CurrentRow.Cells[0].Value, eu ja consigo isso?
Esse é meu método, caso queiram entender o contexto:
private void EfetuarPedido()
        {
            int id_Posicao_Selecionada = 0;
            int quantidade_Posicao = 0;

            tratarErro.Clear();

            quantidade_Posicao = Convert.ToInt32(dgvPosicoesParaPedido.CurrentRow.Cells[3].Value);
            id_Posicao_Selecionada = Convert.ToInt32(dgvPosicoesParaPedido.CurrentRow.Cells[0].Value);

            if (Convert.ToDouble(txtPedidoCodigo.Text) < 999999999999)
            {
                tratarErro.SetError(txtPedidoCodigo, "Código inválido");
            }

            if (Convert.ToInt32(txtPedidoQuantidade.Text) <= 0)
            {
                tratarErro.SetError(txtPedidoQuantidade, "Quantidade não pode ser nula");
            }
            else if (quantidade_Posicao > (Convert.ToInt32(txtPedidoQuantidade.Text)))
            {
                tratarErro.SetError(txtPedidoQuantidade, "Não há unidades necessárias na posição escolhida");
            }
            else if(Convert.ToDouble(txtPedidoCodigo.Text) > 999999999999)
            {
                validar.Validacao_FazerPedido(Convert.ToDouble(txtPedidoCodigo.Text), Convert.ToInt32(txtPedidoQuantidade.Text), id_Posicao_Selecionada, txtReorganizarDescricao.Text);
            }
        }

Answer: O evento só seria útil no seu caso se você precisar atualizar outros campos sempre que o usuário efetuar uma troca na linha selecionada, se não for por isso só pegar o id direto da tabela já deve resolver.
Comment: Ah obrigado, no caso, não vai atualizar nenhum campo, esse método eu vou atribuir ao evento click de um botão, então não tem como ele selecionar outra linha depois de disparar o evento click, obrigado por ter me esclarecido essa dúvida. Eu tava achando que funcionava só com o Evento manja, tipo os valores em pixels dos Axis X e Y dos Chart que só funciona no Evento Paint

Capturar id do datagrid


Soma em TextView

Question: Tenho um Json que retorna os valores de positivo e negativo, e que setam o texto nos meus TextView. Esse é o calculo que eu tento fazer, mas que retorna um erro de invalid double:
public double num1,num2,resultado;

saldo = (TextView) findViewById(R.id.saldouser);
negativo = (TextView) findViewById(R.id.vendaliv);
positivo = (TextView) findViewById(R.id.compraliv);
date = (TextView) findViewById(R.id.datatrans);

num1 = Double.parseDouble(positivo.getText().toString());
num2 = Double.parseDouble(negativo.getText().toString());
resultado = num1-num2;
System.out.println(resultado);
saldo.setText(resultado);

O erro é:

Caused by: java.lang.NumberFormatException: Invalid double: ""
Comment: Teria como você deixar o erro completo na pergunta? É melhor para quem for responder, entender o que está acontecendo.
Comment: Fiz a edição , inseri o erro ..
Answer: Das duas uma:
1) Você usa no texto um valor como 12,9 ou 10,0com virgula, como usamos no Brasil. Mas o Double usa . como é usado nos EUA, logo ele nao consegue interpretar que 12,9 é 12.9 e explode.
2) Voce tenta dar parse em um String vazio, o que é invalido tb pois ele nao converte automatico pra 0.
Sugestao, use um bloco try catch pra tratar essa exception e/ou uma funcao pra converter sua virgula pra ponto se for esse o problema.
Comment: Provavelmente é a String vazia mesmo..
Comment: @Thiago pelo seu erro é a String vazia, se resolveu o seu problema aceite a resposta ;)

Soma em TextView


How to publish vmware VDI though Citrix Web Interface

Question: I have a VMWARE Lab and CITRIX Lab and they work just fine, But is there a way I could
publish VMWARE VDI Through Citrix Web Interface.
I've XENAPP 6.5 and vSphere 5.1 and vmware stuff in place
I'm trying to build a solution where VMWARE VDI could be access via Citrix Web Interface
Thanks in Advance!!!
Answer: You will not be able to directly publish VMWare VDI through the Citrix Web Interface.
The only way I could see this work, is if you install and publish the VMware VDI client on XenApp.
You'll then depend on both systems, in order to access VDI. Accessing your virtual desktop, you'll also be subject to additional latency, protocol overhead and possibly multimedia quality degradation, from running the VMWare PCoIP protocol inside Citrix ICA/HDX.
Comment: I see where you're coming from. But I've seen this pulled off with some good results. But I agree with the Quality degradation....lets see....
Answer: Finally firgured it out, You can pull this off with XenDesktop and XenApp 7.5 where it give the option to choose the hypervisor...
Thanks.
Comment: Yes, you can run both XenApp or XenDesktop on VMWare, Hyper-V or XenServer, but that was not what you asked - you wanted to access a VMWare VDI via XenApp, right?


CSS applied to bootstrap Jumbotron works inline, but not externally

Question: Im trying to apply a background to a jumbotron. It works fine if I use inline styling but not when using an external stylesheet. I have linked the external stylesheet correctly and i can change other attributes of the jumbotron in it but not the background image. Any help would be appreciated. Thanks
html with inline styling:

        <link rel="stylesheet" href="CSS/bootstrap.min.css">
        <link rel="stylesheet" href="CSS/homepage.css">

Welcome.

Text

css: (height works, background image doesnt)
.jumbotron {

    height: 400px;
    background-image: url('Images/background.jpg');
    background-size: 100% 100%;

}

Answer: I imagine your folder structure looks something like the following:
- index.html
- CSS/
    -- homepage.css
    -- bootstrap.min.css
- Images/
    -- background.jpg

The path to the Images/ folder from your HTML file will be different than from within the homepage.css file. You need to use relative paths to get to the Images folder, which should be one level higher. You can use .. to go up one level in the folder structure within the CSS url() property.
CSS
.jumbotron {
    height: 400px;
    background-image: url('../Images/background.jpg');
    background-size: 100% 100%;
}

Comment: This works thatnks. Just moved the image to different directory
Answer: One possible fix might be that your file directory isn't configured properly.
As good practice, follow this:
root
|
index.html
<other html files>
CSS Folder/
    |
     <CSS files>
Images Folder/
    |
     <image files>

As for the solution:
try this:
.jumbotron {
height: 400px;
background-image: url('../Images/background.jpg');
background-size: 100% 100%;
}


$\frac{d^2x}{dt^2} =3.$ Separation of variables

Question: Can someone show the steps to desperate the values and do the integration for the following: $$\frac{d^2x}{dt^2} =3\quad?$$
What I have is
$$d^2x=3dt^2$$
Integrate
$$dx=3t^2 + c$$
$$x=t^3+ct +d$$
Is that right?
Answer: Note that your initial right-hand side is better expressed by $$3(dt)^2 = (3\,dt)(dt)$$ and not by $3d(t^2)$. (I.e. $3dt^2$ is not three times the derivative of $t^2$!)
$$\frac{d^2x}{dt^2} =3 \iff d(dx) = (3\,dt)\,dt$$
You should end up with, after first integration is $$dx = (3t + c)\,dt$$
Then
$$\int dx = \int (3t + c), dt \implies x(t) = \frac{3t^2}{2} + ct + d$$

Note that you can test your solution for yourself - taking the second derivative of your posted solution. If you do, you'll see that you end up with $\dfrac{d^2x}{dt^2} = 6t$, which is not what you started with.
However, if you take the second derivative of the solution you find here, you obtain $$\frac{d^2x}{dt^2} = \frac d{dt}\left(\frac d{dt}\left(\frac{3t^2}{2} + ct + d\right)\right) = \frac d{dt}\left( 3t + c\right) = 3$$ as desired.
Answer: I assume you mean
\begin{align}
\frac{d^2x(t)}{dt^2}=3
\end{align}
You don't really need seperation of variables. Simply integrate twice.
First integration yields
\begin{align}
\frac{dx(t)}{dt}=\int3\,dt = 3t+c
\end{align}
Integrate again to obtain
\begin{align}
x(t) = \int 3t+c\, dt = \frac32t^2+ct+d
\end{align}
Your error was, that from $d^2x = 3dt^2$ it follows $dx = (3t+c)dt$ and not $dx=3t^2+c$.


Distance from a compact subset need not be attained in a metric space?

Question: Suppose we have a metric space $(X,d)$. Let $S$ be a compact subset of $X$. Provide me with an example of $X$, and $S$ (closed and bounded in $X$) such that $$\min \{d(p_0,p): p \in S\}$$ does not exist, where $p_0 \in X$.
Comment: Instead of telling people what to do, tell them what your problem is.
Comment: The question is not very well formulated. Since this is a question for a an example, it should start with asking for that, not with "Suppose" and "Let" (which would be appropriate for a question about a proof).
Comment: Is $p_0$ fixed or not?
Comment: @MarcvanLeeuwen This is interesting (to me, anyway). How would you word a question like this?
Comment: Just start with: "Can anybody give me an example of the following situation" and then describe the conditions that you would like to have satisfied. With "suppose" or "let" one usually introduces a situation that is given and one is not allowed to tamper with; here it is the opposite.
Comment: This question seems to be related: [For any point $ a $ of a compact subset $ S $ of a metric space, prove that there exists a nearest point $ c $ to $ a $.](http://math.stackexchange.com/questions/333479/for-any-point-a-of-a-compact-subset-s-of-a-metric-space-prove-that-ther) (It was in the list of related questions on the right.)
Answer: I'll assume $S$ not empty.
Since the function $f\colon S\to\mathbb{R}$, $f(p)=d(p_0,p)$ is continuous, when $S$ is compact its image is compact, hence closed and bounded; therefore the image of $f$ contains its minimum.
If $S$ is only assumed to be closed and bounded, but not compact, the statement is not generally true. Consider $X=\{0\}\cup (1,2]$, with the metric induced by $\mathbb{R}$. Then $S=(1,2]$ is closed and bounded, but
$$
\inf_{p\in S} d(0,p)=1
$$
and there's no $p\in S$ such that $d(0,p)=1$.
Comment: This is slick! Actually I've been having a hard time looking for a counterexample in $\ell^2$ but  apparently I've gone the troublesome way.
Answer: The function $x\mapsto d(p_0,x)$ is continuous on $X$, hence attains its minimum on $S$ since $S$ is compact.
Comment: No. $S$ isn't necessarily compact. And the min may not be attained either. See egreg or Antitheos answers for simple counterexamples.
Comment: @Vim: The question says $S$ is compact, does it not?
Comment: what I saw was "bounded and closed". But the OP seemed to have confused the two.


Construction of a poset from infnitely many finite antichains

Question: The question is about a solution to the following exercise:
Find an infinite partial order that has no infinite antichain but is not a union of finitely many chains.
Let's take infinitely many finite antichains and make some order out of them. Let the first antichain be a single element one and each successive antichain to be bigger than the previous in size by $1$. Additionally, for every element in antichain $n$, there is an element in antichain $n + 1$ with which the two are related. So the diagram of this order should look like a tree divided into levels by antichains, like in a boolean lattice, but infinite and without the top half.
But does this order have an infinite antichain?
On one hand, each successive antichain is finite by definition, so there should not be any infinite antichains, yet their composition can be infinite. Similarly to infinite series of natural numbers where each partial sum is finite but the whole series is infinite.
But, on the other hand, we know that the size of given antichain is greater or equal to the size of the longest chain at its level. And it is a fact that infinite partial order must contain either an infinite chain or infinite antichain. So, since they are always equal, they should be both infinite.
Answer: The construction does not work in the stated level of generality. For instance, take an infinite complete binary tree. You obviously get infinite anti-chains there. Your levels are of size n rather than $2^n$, but you can use a single branch at each level to make it still fail.
There's no reason to connect the levels so arbitrarily though. Just model them off of complete bipartite graphs and it obviously works.
A more natural example is furnished by Dickson's lemma.


Can not install plugins in jenkins

Question: Gues,please help me.I can't not install anything in jenkins.
I don't have problems with iternet.
I try istall plugins and appear next error:
`
<code>java.net.SocketTimeoutException: connect timed out at java.base/sun.net.www.http.HttpClient.privilegedOpenServer(HttpClient.java:559)  at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:600)    at java.base/sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:265)    at java.base/sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:372)   at </code>
How can I fix this error?
Answer: i see that there was issue with artifactory 29h ago https://status.jenkins.io/issues/2023-08-02-artifactory-central-brownount/
there was bug in jenkins, see ticket/workaround here
and jenkins dev said that they have already reverted this change link
also check that your jenkins server has access to NET

Can not install plugins in jenkins


How to fill report using JSON datasource without getting null values?

Question: I'm using Jasper Reports to build a simple report pdf. I have a JSON file that looks like this:
{"employees": [
    {"firstName" : "John", "lastName" : "Doe"},
    {"firstName" : "Anna", "lastName" : "Smith"},
    {"firstName" : "Peter", "lastName" : "Jones"}
]}

And I'm trying to read it in like this:
File file = new File("E:/Workspaces/jasperPDFreport/src/main/resources/emp.json");
JsonDataSource datasource = new JsonDataSource(file);

JasperDesign jasperDesign = JRXmlLoader.load("E:/Workspaces/jasperPDFreport/src/main/resources/jsonTemplate.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
Map parameters = new HashMap();
JasperPrint jasperPrint;
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, datasource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "BasicReport.pdf");
JasperViewer.viewReport(jasperPrint);

However my the values from the JSON file are not passed to my pdf.
This is my Template:
<?xml version="1.0" encoding="UTF-8"?>

<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Blank_A4_2" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="9e494ebe-c1fb-4448-bcee-38994e9720f7">

    <queryString language="json">
        <![CDATA[employees]]>
    </queryString>
    <field name="firstName" class="java.lang.String">
        <fieldDescription><![CDATA[firstName]]></fieldDescription>
    </field>
    <field name="lastName" class="java.lang.String">
        <fieldDescription><![CDATA[lastName]]></fieldDescription>
    </field>
    <background>
        <band splitType="Stretch"/>
    </background>
    <detail>
        <band height="125" splitType="Stretch">
            <textField>
                <reportElement x="100" y="0" width="100" height="30" uuid="02b279da-3795-4655-8571-5a36a3ef378c"/>
                <textFieldExpression><![CDATA[$F{firstName}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="0" y="0" width="100" height="30" uuid="671e61ad-8d8f-48cb-969f-78c05a516398"/>
                <text><![CDATA[firstName]]></text>
            </staticText>
            <textField>
                <reportElement x="100" y="30" width="100" height="30" uuid="9d53f46f-a252-48b3-9213-8c3092c29f49"/>
                <textFieldExpression><![CDATA[$F{lastName}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="0" y="30" width="100" height="30" uuid="3b49affb-685a-4df2-a872-c0e6fdcab94b"/>
                <text><![CDATA[lastName]]></text>
            </staticText>
        </band>
    </detail>
</jasperReport>

Now you see the commented out line

property name="net.sf.jasperreports.json.source" value="emp.json"

If I comment this in, everything works as intended, I don't want to hard code my JSON values into the template, because later on I want to get them from a rest service, that's not ready yet. I do not understand, why the values are not getting parsed into the report, instead i just get two null values.
Answer: From JasperReports - JSON Data Source Sample (version 6.4.3)

The built-in JSON query executer (see the JsonQueryExecuter class) is a tool that uses the query string to produce a JsonDataSource instance, based on specific built-in parameters (or equivalent report properties). This query executer is registered via JsonQueryExecuterFactory factory class.
  In order to prepare the data source, the JSON query executer looks for the JSON_INPUT_STREAM parameter that contains the JSON source objects in the form of an java.io.InputStream. If no JSON_INPUT_STREAM parameter is provided, then the query executer looks for the alternate net.sf.jasperreports.json.source String parameter or report property that stores the path to the location of the JSON source file.
  JsonQueryExecuter runs the query over the input source and stores the result in an in-memory JsonDataSource object.

So if you do not want to use:
<property name="net.sf.jasperreports.json.source" value="emp.json"/>

You need to pass the file as java.io.InputStream in the parameter JSON_INPUT_STREAM
Hence you are currently passing it as datasource you should try something like this
params.put(JsonQueryExecuterFactory.JSON_INPUT_STREAM, new FileInputStream(file));
JasperFillManager.fillReportToFile(jasperReport, params);

If you instead like to use the new JsonQLQueryExecuterFactory JSONQL Data Source
params.put(JsonQLQueryExecuterFactory.JSON_INPUT_STREAM, new FileInputStream(file));
JasperFillManager.fillReportToFile(jasperReport, params);

Answer: If you pass your json string as InputStream then it will works.
String reportContents = "{}" //your json
InputStream is = new ByteArrayInputStream(reportContent.getBytes());
Map params = new HashMap();
params.put(JsonQueryExecuterFactory.JSON_INPUT_STREAM, is);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params);

Answer: Take a look here for data source implementation that wraps a collection of JavaBean objects.
List<YourClass> yourBeanCollection = queryDataFromJSON();

JRDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(yourBeanCollection);

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,
                reportParams, beanCollectionDataSource);

and in the report template import java.util and declare the collection which you "injected" in the report
<import value="java.util.*"/>
<field name="yourBeanCollection" class="java.util.List"/>

also take a look here for an example


Getting JSF-defined component with Javascript

Question: I'm creating an interface using JSF, and I'd like the value of one text field to provide the default for a second if the second hasn't yet been set.  The crucial code will look something like this:
<h:outputScript>
function suggestValue2() {
    var value2 = document.getElementById('value2').value;
    if (value2 == "") {
        document.getElementById('value2').value = document.getElementById('value1').value;
    }
}
</h:outputScript>

<h:inputText
    id="value1"
    onblur="suggestValue2();" />

<h:inputText
    id="value2" />

The problem is this doesn't actually work.  The actual IDs of those two input elements get prefixed with some JSF-generated values, which tanks the getElementById calls.  What's the best way for me to accomplish what I'm trying to accomplish here?

Edit:  I should note that this is going to appear inside a composite component, which could wind up appearing multiple times on a single page.  JSF dynamically setting the actual ID represents desired behavior.
Comment: The easiest way to solve this issue would be using [`prependId="false"`](http://stackoverflow.com/q/3972653/1065197) in the form. Another way would be finding it using the form id and the component id, like `myFormId:value1`, as suggested [here](http://stackoverflow.com/a/6045342/1065197).
Answer: Bind the component to the view,
<h:inputText binding="#{input1}" ... />

so that you can just print its client ID elsewhere in the view by UIComponent#getClientId().
<h:outputScript>
    var input1 = document.getElementById('#{input1.clientId}');
    // ...
</h:outputScript>

As you mentioned that you're inside a composite component, it may be good to know that composite component's own client ID is already available via #{cc.clientId}. So the more recommended alternative would be:
<cc:implementation>
    <h:outputScript>
        var input1 = document.getElementById('#{cc.clientId}:input1');
        // ...
    </h:outputScript>
    ...
    <h:inputText id="input1" ... />
    ...
</cc:implementation>

See also:

Integrate JavaScript in JSF composite component, the clean way
Comment: The #{cc.clientId}: prefix is precisely the unobtrusive solution I was looking for.  Thank you!
Answer: Jsf uses a concept "naming containers" which says the id need not be unique within a provided container. Provided the container has an Id. So if you are not giving an Id to the container jsf appends the unpredictable values before the element. With id for container it becomes containerid:elements id. And this can be used in JavaScript reliably
Comment: See my edit above (sorry I didn't make this clearer).  The dynamic ID allocation represents desired behavior -- the page won't work without it.


Different Definitions of Tensor product, Halmos, Formal Sums, Universal Property

Question: In the classic Finite-Dimensional Vector Spaces by P. Halmos he defines the Tensor product as

The tensor product $U \otimes V$ of two finite-dimensional vector spaces $U$ and $V$ (over the same field) is the dual of the vector space of all bilinear forms on $U \oplus V$ [remark, by this he means all bilinear maps $\omega : U \times V \to \mathbb F$]. For each pair $x$ and $y$, with $x$ in $U$ and $y$ in $V$, the tensor product $z = x \otimes y$ of $x$ and $y$ is the element of $U \oplus V$ defined by $z(w) = w(x,y)$ for every bilinear form $w$.

Another construction, for example here or on Wikipedia, the tensor product is defined as the set of all formal sums on $U \times V$ modulo certain (''bilinear'') identities. This is equivalent to the set of all formal sums on $\{ u_i \}_{i\in I} \times \{ v_j \}_{j \in J}$ for bases $u_i$ and $v_j$ of $U$ and $V$.
According to my first reference, the set of all multilinear maps $V_1 \times \ldots \times V_k \to \mathbb F$ could be identified with $V_1^* \otimes \ldots \otimes V_k^*$, this seems always possible (not requiring finite dimensions), so in particular the set of all bilinear maps $U \times V \to \mathbb F$ could be identified with $V^* \otimes U^*$, so in Halmos definition the tensor product equals $(V^* \otimes U^*)^*$, where the tensor product is defined as the set of formals sums as above.
But to make sense, this definition must equal the definition by formal sums, so we must have $(V^* \otimes U^*)^* \cong V \otimes U$ to bring Halmos definition and the definition by formal sums in harmony.
But I guess here seems to be some sort of reflexivity involved, so he might used the finite-dimensionality of the vector spaces, or could Halmos definiton further extended, does I got it right?
Still another construction I found is by the following universal property (see also Wikipedia), i.e. the tensor product of two vector spaces $U$ and $V$ is such that for each bilinear map $U \times V \to W$ there exists exactly one linear map $U \otimes V \to W$, and this correspondence is linear, i.e. we have
$$
 \mbox{Bil}(U, V; W) \cong \mbox{Hom}(U\otimes V, W).
$$
In our case $W = \mathbb F$ the ground field, then
$$
 \mbox{Bil}(U, V; \mathbb F) \cong (U\otimes V)^*
$$
But by Halmos definition the tensor product equals $\mbox{Bil}(U, V; \mathbb F)^*$, so again this seems require some sort of reflexivity, i.e. $((U \otimes V)^*)^* \cong (U\otimes V)$.
But here the property to bring the definitions together reads still a little bit different, to make them all the same we need $(U^* \otimes V^*) \cong (U\otimes V)^*$, but this holds in general vector spaces, as $(U^* \otimes V^*) \cong \mbox{Bil}(U, V; F) \cong (U \otimes V)^*$.
So my questions again: 1) does I got everything right?, 2) am I right that Halmos definition is limited, and how far could we go with it, is reflexivity the right property to demand?
Answer: Yes, you've got it right. Remember the title of Halmos's book is Finite dimensional vector spaces! My guess is he probably thought the definition as the dual of bilinear forms was less abstract that either the quotient or the universal property definitions and used that one.
As you've realized Halmos's definition only agrees with the others when the spaces are reflexive, and since here we are talking about the algebraic dual (i.e., we don't have some norm and take dual to consist of bounded linear functionals, rather we are talking about all linear functionals), reflexive spaces are exactly the finite dimensional ones.
Comment: I think something different is the issue. In differential geoemtry people makes use of both maps $V \otimes V \to \mathbb{R}$ and elements of $V \otimes V$. The first are called 2-tensors (there are also $k$-tensors for all $k$) and the second are called bivectors (and for larger $k$, polyvectors). These tow spaces, $(V \otimes V)^\ast \cong V^\ast \otimes V^\ast$ (for finite dimensional $V$, which is the case that arises for finite dimensional manifolds), and $V \otimes V$ depend on $V$ with different variance. (to be cont'd)
Comment: Thanks for the answer, so now I am more sure about the concepts and their relations. But one question left, when he has no problem using reflexivity, why not defining it as the space of all bilinear forms on $U\times V$ from the start, thus avoiding the extra dual, keeping it still simpler?
Comment: Taking just bilinear forms gives a functor of the wrong variance, @Stefan: given linear maps $U \to U'$ and $V \to V'$, what you naturally get is a linear map $\mathrm{Bil}(U',V';\mathbb{F}) \to \mathrm{Bil}(U,V; \mathbb{F})$. This is contravariant, but you want the tensor product to be a covariant functor.
Comment: Now looking through my literatur I found that for example Spivak in *Calculus on Manifolds* defines tensors directly as multilinear maps, thus defining the space of all $2$-tensors as the set of all bilinear forms on $V\times V$, and proceeding to show that this set is exactly $V^* \oplus V^*$, where $V^* \oplus V^* := \{ \varphi(u)\cdot \psi(v) : \varphi, \psi \in V^* \} \subseteq \mathcal I^2(V) := \{ \varphi : V\times V \to \mathbb K \mbox{ is bilinear } \}$. So here he uses also reflexivity in some sort, but defines $2$-tensors as the space of all bilinear forms...
Comment: ... the approach (from Spivak, and which I mentioned in my first comment) you said is inadequate. Unluckily I am not that used to co-/contravariance, still learning, but in view of Spivaks approach in the finite-dimensional setting is this co-/contravariance thing not a big issue, i.e. it collapses?
Comment: ah, I guess I got it, as he defined it he could associate to two element $x \in U, y \in V$ quite naturally an element of the dual of all bilinear form, simply set $(x \otimes y)(w) = w(x,y)$ for $w$ bilinear. When setting it equal the space of all bilinear form, the question is how to associate to $x,y$ a bilinear form, then he has to regard $x, y$ as element of $U^{**}$ and $V^{**}$, i.e. maps $x : U^* \to K, y : V^* \to K$ as $x(f) := f(x), y(g) := g(x)$ for linear maps $f,g$ on $U$ and $V$, then we could associate the bilinear map $w : U^* \times V^* \to K$ with $w(f,g) = f(x)\cdot g(x)$
Comment: .. by which he has to use reflexity again, is this the issue you meant by bringing co-/contravariance into the discussion? That it makes the definition of the tensor product of two elements more involved?
Comment: I already mentioned one way to say what the variance is, but what you say is also related: given $x,y \in V$, you get an $x \otimes y$ of $V \otimes V$ (as you said, if you defined $V \otimes V$ as $\mathrm{Bil}(V,V;\mathbb{R})$, this element would be $w \mapsto w(x,y)$); but you don't canonically get an element of $(V \otimes V)^\ast$. If you *pick* an isomorphism $V \cong V^\ast$, you get a corresponding isomorphism $(V \otimes V)^\ast \cong (V^\ast \otimes V^\ast)^\ast$, and you can get an element of the latter space from $x$ and $y$: $\alpha \otimes \beta \mapsto \alpha(x) \beta(y)$.
Comment: In your first comment: you mean maps $V \oplus V \to \mathbb R$ and elements $V \otimes V$, and also $(V\otimes V)^* \cong V^* \otimes V^*$ holds in general, not just for finite-dimensional spaces?
Comment: I did mean $V \otimes V \to \mathbb{R}$, that is, **bi**linear maps $V \oplus V \to \mathbb{R}$. Also, $(V \otimes W)^\ast \cong V^\ast \otimes W^\ast$ is true for infnite dimensional spaces, but for cardinal arithmetic reasons, not in any natural way. The map $V^\ast \otimes W^\ast \to (V \otimes W)^\ast$ given by $\alpha \otimes \beta \mapsto (v \otimes w \mapsto \alpha(v) \beta(w))$ is an isomorphisms when $V$ and $W$ are finite dimensional but not in general.


Structure of a set whose image through continuous convex functions is an interval

Question: What can be said about a subset $S$ of a Banach space $X$ with the property that $f(S)$ is an interval, for every convex lower semi-continuous function $f:X\to\overline{\mathbb{R}}$ that has at least one continuity point (equivalently the domain of $f$ has a non-empty interior) and such that $S$ is a subset of the domain of $f$?
For example if $S$ is connected then $f(S)$ is an interval whenever $f$ is convex defined everywhere because in this case $f$ is continuous. So I expected something similar for the general question.
Comment: Do you really mean that $f(S)$ must be an interval for _every_ c.l.s.c $f\colon X\longrightarrow\bar{\mathbb{R}}$? Because this seems like a very strong condition...
Comment: Yes, every lsc convex function that is continuous on the interior of their domains. If it make things easier you can take all continuous convex functions defined on the whole space. Any idea would be appreciated.
Answer: Without getting into any particularly deep analysis, here are my thoughts: (let's assume, like you say, for simplicity we run over all convex $f$s that are continuous and defined on all of $X$)
First I would start with thinking about what it would mean for $f(S)$ to not be an interval: this means there is some $x\in\mathbb{R}$ that "separates" $f(S)$ (i.e., $x\not\in f(S)$ but there exist $a<x<b$ with $a,b\in f(S)$). Thus, the level set $f^{-1}(x)$ is obviously disjoint from $S$ (is $f^{-1}(x)$ unbounded?). Thus for the $S$ to have the desired property, it cannot be separated by the level set of any such $f$. Obviously like you said if $S$ is connected then obviously cannot be separated by any such level set.
Second, to get your hands on what this really means, I would think about how to prove/generalize the following pictures: set $X=\mathbb{R}^2$, and this is the picture of what I was describing.

EDIT: Let me explain the figure a little more: if a set $S$ in $\mathbb{R}^2$ can be separated by the level set of a convex function, then we should be able to draw what looks like the graph of a convex function $\mathbb{R}\mapsto \mathbb{R}$ separating the graph.
Comment: Actually I reached at that formulation from a more general property applied for the level sets of a continuous convex function. It's the other problem I had a bounty for http://math.stackexchange.com/questions/1514768/segment-ordered-density-conjecture-revisited


trying to get left right arrows to stick on edges of large image.

Question: I have a image the scales to the screen size. I'm trying to get a left, right and close buttons to stay on the image but I can only get them to stay on the edges of the screen.
JSFIDDLE
#full_image ul{
  margin:0;
  padding:0;
  list-style:none;
  width:100%;
  white-space: nowrap;
  overflow:hidden;
 }
#full_image li{
  display:block;
  margin:0;
  padding:0;
}
#full_image li a {display:block}
#full_image ul li img{ margin:0 auto; max-width:100%}

#full_image .full_close{
  background-color: red;
  top: 10px;
  cursor: pointer;
  height: 29px;
  opacity: 1;
  position: absolute;
  width: 29px;
  z-index: 999;
  right: 10px;
 }
#full_image .next_big{
  background-color: red;
  top: 50%;
  cursor: pointer;
  height: 29px;
  opacity: 1;
  position: absolute;
  width: 29px;
  z-index: 999;
  right: 0px;
}

#full_image .prev_big{
  background-color: red;
  top: 50%;
  cursor: pointer;
  height: 29px;
  opacity: 1;
  position: absolute;
  width: 29px;
  z-index: 999;
  left: 0px;
  color: #222;
   }

Answer: When you use display:block on the parent containers they will stretch the full width. You will have to either use display:inline-block or float the element.
If you have to support older browsers this trick may work:
#full_image{
     display:inline-block;
     *display:inline;/* For IE7*/
     *zoom:1/* For IE7*/
     text-align:left;
    }

You will have to remove the display block on the li a.
You have to also add position relative to the #full_image div to make sure the absolutely positioned items are positioned inside that div rather than the screen.
Here is an updated fiddle:
http://jsfiddle.net/kvE96/15/
Answer: Format your container with display:inline-block (so that it is only as wide as the image actually), and position:relative to make it the point of reference for the absolute positioning of children.
See http://jsfiddle.net/kvE96/11/
Comment: thank you a million but the image no longer scales with you make the window smaller


Johnson SU distribution parameters values from R/rugarch

Question: I have fit a GARCH model where I set the distribution to the Johnson's SU. I don't fully understand the distribution parameters returned by the model.
To begin with, from Wikipedia, Johnson's SU is defined as:
\begin{equation}
z = \gamma + \delta \sinh^{-1}\left( \frac{x - \xi}{\lambda} \right)
\end{equation}
where $x \sim N(0,1)$.
The parameters of the distribution are $\gamma, \xi, \delta, \lambda$.  My model outputs the following where the skew and shape parameters are the distribution parameters and the rest ($\alpha, \beta, \omega$ are GARCH parameters).
<code>            Estimate   Std. Error       t value     Pr(>|t|)
mu     -1.747010e-17 0.0009983114 -1.749965e-14 1.000000e+00
alpha1  5.015195e-02 0.0090862109  5.519567e+00 3.398366e-08
beta1   8.999928e-01 0.0160119111  5.620771e+01 0.000000e+00
skew    3.265134e-02 0.0503597628  6.483618e-01 5.167510e-01
shape   1.008973e+00 0.0292731396  3.446753e+01 0.000000e+00
omega   8.894715e-05
</code>
First, the model suggests that the skew is 0 (p-value is 0.5). If skew here means 3rd moment then I'm even more confused because I know that the data has a negative skew.
Second, I am struggling to understand how the skew and shape parameters fit with the parameters of the distribution. As I understand it, under the hood, rugarch uses GAMLSS which defines distributions in terms of 4 paremeters: µ, σ, ν, τ.
So overall, I don't know what skew and shape mean here and how to interpret them.
Comment: [Here](https://www.gamlss.com/wp-content/uploads/2018/01/DistributionsForModellingLocationScaleandShape.pdf) is a document (PDF) from the authors of GAMLSS in which they detail the arametrization of the distributions. Maybe you'll find your answers in there.
Comment: **Wikipedia seems to have a typographical error:** it is $z$ that is supposed to have a standard Normal distribution.  The description of random variable generation [makes this clear](https://en.wikipedia.org/wiki/Johnson%27s_SU-distribution#Generation_of_random_variables). That would make $\lambda$ a scale parameter and $\xi$ a location parameter for $x.$  The Wikipedia example, which varies $\gamma$ while fixing the other parameters, clearly shows a regular change in skewness, whence we might infer $\gamma$ is a "skew" parameter and $\delta$ a "shape" parameter.
Answer: I think rugarch uses the gamlss JSU(mu, sigma,nu,tau) parameterisation,
in which mu is the mean, sigma is the standard deviation, nu is a skewness parameter and tau is a kurtosis parameter.
The parameterisation is given on page 391 of
'Distributions for Modeling Location, Scale, and Shape: Using GAMLSS in R'
R. A. Rigby, M. D. Stasinopoulos, G. Z. Heller and F. De Bastiani.
Chapman and Hall/CRC, Boca Raton, 2019
Paperback (2021)
www.routledge.com//9780367278847
I think perhaps (mu,omega,skew,shape) = (mu, sigma, nu, tau).
The JSU parameterisation is different from the gamlss JSUo parameterisation. JSUo is the original Johnson (1947) parameterisation and is defined by your Wikipedia formula.
The reason you don't get skewness, could be that JSU is modelling the conditional distribution of the response, not the marginal distribution.


How to make the background of a fullscreencover transparent?

Question: This is what I want to achieve:
This is what I got:
I tried embeding the VStack in another VStack with a .background(.gray.opacity(90)) but it didn't do anything. I am using a fullScreenCover:
let width = UIScreen.main.bounds.width
.fullScreenCover(isPresented: $showCover) {
BuyWithPointsView(type: type).frame(width: (width * (91.733 / 100)), height: (width * (66.667 / 100)))
}

EDIT:
I tried implementing this answer: SwiftUI: Translucent background for fullScreenCover
.fullScreenCover(isPresented: $showCover) {
                    ZStack {
                        ZStack {
                            Color.gray.opacity(0.1).edgesIgnoringSafeArea(.all)
                        }.background(BackgroundBlurView())
                        BuyWithPointsView(type: type).frame(width: (width * (91.733 / 100)), height: (width * (66.667 / 100)))
                    }
                }
struct BackgroundBlurView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        let view = UIVisualEffectView(effect: UIBlurEffect(style: .light))
        DispatchQueue.main.async {
            view.superview?.superview?.backgroundColor = .clear
        }
        return view
    }
    func updateUIView(_ uiView: UIView, context: Context) {}
}

This lead to this result:  However this result does not really make the background see through like I want it to be. Changing the opacity and color didn't do much.
Comment: Does this answer your question? [Is there a way to set a fullScreenCover background opacity?](https://stackoverflow.com/questions/65295388/is-there-a-way-to-set-a-fullscreencover-background-opacity)
Answer: I found this cleaner solution for the transparent background without any flicker issues.
struct ClearBackgroundView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        return InnerView()
    }

    func updateUIView(_ uiView: UIView, context: Context) {
    }

    private class InnerView: UIView {
        override func didMoveToWindow() {
            super.didMoveToWindow()

            superview?.superview?.backgroundColor = .clear
        }

    }
}

Usage
PresenterView()
    .fullScreenCover(isPresented: $isPresented) {
        PresentedView()
            .background(ClearBackgroundView())
    }

Comment: I had been searching for the fix to the flickering issue, which caused other exceptions downstream and found this by chance. Thanks @ahmed
Answer: iOS 16.4 provides .presentationBackground to modify your modal backgrounds. Yay to yoinking UIViewRepresentable workarounds :)
Usage
.fullScreenCover(isPresented: $isPresented) {
    YourView()
        .presentationBackground(.clear)
}


Quadratic convergence misunderstanding

Question: I struggle to understand the concept of quadratic convergence.
It is said that it implies linear convergence but let's say we have:
$$|x_{n+1}-x_*|<C|x_{n}-x_*|^2$$
and $$C=1$$
If $  |x_{n}-x_*|$ = 2 , then $|x_{n+1}-x_*|\leq 4$ and we get reclusively
$$\forall k\in N ,|x_{n+1+k}-x_*|<4^{2*k}$$
Which does not seem to imply something good for our error.
We do have the assumption that $x_n \to x_*$
then at some point $|x_{n+1+k}-x_*|<1$ but still it does not seem good considering the boundness we got before this happening.
How could you assume it does not take centuries to get to $|x_{n+1+k}-x_*|<1 $
I am probably missing something here
Answer: There is no misunderstanding. When we are discussing the order of convergence, the baseline assumption is that the sequence converges... So, as you say, $|x_n-x^*| < 1$, for large enough $n$.
In the situation you describe, you could control $|x_n-x^*|$ using other estimates, until the quadratic inequality becomes effective. For instance
$$
|x_n-x^*|\leq \frac{L}{1-L}|x_n-x_{n-1}|,
$$
where $L$ is the Lipschitz constant for the iterating function.

Quadratic convergence misunderstanding


TSQL Query From SQL Server 2012 Database, two different tables, One Parent, One Child

Question: I have two tables, TableA and TableB.  TableB has a FK to TableA.  This is a SQL Server 2012 database, with primary keys on both tables called Id.  No other indexes exists yet.
The first table as TableA holds who has access to a folder with the following columns:

Id (RowId, Primary Key)
Path (full path of folder / directory, nvarchar(255))
GroupName (Active Directory Group, nvarchar(255))
Guid (Guid of Group, nvarchar(128))

The second table as TableB holds permissions to that folder or directory:

Id (RowId, Primary Key)
TableARowId (FK, RowId from TableA)
Permission (nvarchar(128), 12 different possible values)

What I've been asked to do is to query Path, GroupName, Guid, and Permissions for all the folders.  No big deal.
The problem is if the groups and permissions from a particular folder in the path (example: \\FolderA\FolderB\FolderC\) is the same all the way down to its lowest level (\\FolderA\FolderB\FolderC\....\Folder[N]), they only want to see up to the first folder that has the same Groups and Permissions.
So, if FolderB has different Groups and Permissions than FolderA then all the needed fields will be in the dataset for that path.  If FolderC has different  groups and permissions than FolderB, then all needed fields will be in the dataset for that path.
But If FolderC has the same number of Groups and Permissions all the way down to FolderW, then the last folder in the dataset for that path will be FolderC.  That is the part that I can't figure out.
I guessed the answer should include a recursive CTE with the anchor being the root directory.  But I thought the recursion should compare the last folder's groups and permissions to the previous record, and if it is different, add it to the dataset, otherwise, skip it.
But there is something I couldn't get past while trying to answer my first question.  How do you code for scenario of FolderA - FolderC being different, then FolderC to FolderP being the same, then, FolderP to FolderZ are different?  In this case, I still want so show all folders up to FolderP.  This is the part that hurts my head.
The code I wrote didn't get me very far.  I wrote:
        (SELECT
           [Path]
          ,[GroupName]
          ,[Guid]
          ,PermissionAsOneRow
      FROM [TableA] TA INNER JOIN
            (  SELECT [TableARowId], PermissionAsOneRow FROM (
            SELECT  [Id], TBL1.[TableARowId],
                 ( SELECT [Permission] + ', '
                  FROM [TableB] TBL2
                  WHERE TBL2.[TableARowId] = TBL1.[TableARowId]
                    FOR XML PATH('')) AS PermissionAsOneRow
                FROM [TableB] TBL1
                GROUP BY  [Id], TBL1.[TableARowId]) AS MYDATA
        GROUP BY [TableARowId], PermissionAsOneRow) AS MD ON TA.Id = MD.[TableARowId])

This gives me data that looks like this:
      Id          Path                                   GroupName           Guid                          Permission
-----------------------------------------------------------------------------------------------------------------------
1           \\FolderA\FolderB\                           SomeGroupNameA     [RandomGuidValueHereA]         PermissionA,PermissionB,PermissionC,PermissionD
2           \\FolderA\FolderB\FolderC\                   SomeGroupNameB     [RandomGuidValueHereB]         PermissionA,PermissionB,PermissionC,PermissionD
3           \\FolderA\FolderB\FolderC\...Folder[N]       SomeGroupNameC     [RandomGuidValueHereC]         PermissionA,PermissionB,PermissionC

I organized the data this way because I thought it would be easy to compare row after row on the permissions field as I discussed above, using the Recursive CTE.  But the honestly, I didn't know how to do the next step and started to think it wouldn't work.
Any and all help is appreciated.
For those that can answer, please explain so I can learn from it.
See below for example of data, please excuse my formatting
Example of data in TableA
Id          Path                                         GroupName        Guid
------------------------------------------------------------------------------------
1           \\FolderA\FolderB\                           SomeGroupNameA     [RandomGuidValueHereA]
2           \\FolderA\FolderB\FolderC\                   SomeGroupNameB     [RandomGuidValueHereB]
3           \\FolderA\FolderB\FolderC\...Folder[N]       SomeGroupNameC     [RandomGuidValueHereC]
4           \\FolderAA\FolderBB\FolderCC\                SomeGroupNameD     [RandomGuidValueHereD]
5           \\FolderAA\FolderBB\FolderCC\...Folder[N]    SomeGroupNameE     [RandomGuidValueHereE]

Example of Data in TableB
Id         TableARowId    Permission
--------------------------
1               1         PermissionA
2               1         PermissionB
3               1         PermissionC
4               1         PermissionD
5               2         PermissionA
6               2         PermissionB
7               2         PermissionC

Comment: *my employer screens for code* isn't our problem. You can provide sample data without posting code, and sample results, without an issue. I'm quite certain you can also figure out a way to post what you've attempted so far that isn't working for you. We're not a code writing service; we expect you to have made an effort to solve the problem yourself before posting here, and to include that effort in your post. Your employer apparently has no difficulties with your posting tables and volumes of text here.
Comment: You may want to format your sample data using `{ }` code blocks and present them differently (like databases do). Also, consider adding your approach - query which you have tried.
Comment: I updated the sample data @ConsiderMe, Thanks.
Comment: You should really show the sample data formatted as **tables** - much easier to read and understand !
Comment: Dude, "pivot" your text. Don't start a paragraph for each new row - draw a table (isn't it obvious when you are talking about a table) with rows and cols. And the best one is to give a ready to execute code that will create a sample table with those rows. And provide a result you want to achieve.
Comment: Thank you for formatting @marc_s
Comment: I'm still not seeing a complete set of input and desired output, just some unrelated sample rows. Perhaps if `TableA` _had_ an `Id` column and the expected output was included that provides samples of the various cases to be handled we could be of more help. Please read [this](http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/) for some tips on improving your question.
Comment: @HABO, both tables have id columns, if you look towards the top of the page, there is a description of each table. In that description, the first field of each table are Id columns as the primary key that is auto generated.  In TableB, there is a FK to tableA as `TableARowId`.  I'll make it clearer so you and others understand.
Answer: I'm still a little perplexed by what you want, but there may be something of use in this:
-- Sample data.
declare @Folders as Table ( FolderId Int Identity, Folder VarChar(16) );
insert into @Folders ( Folder ) values
  ( '\\A0\' ), ( '\\A0\A1\' ), ( '\\A0\A1\A2\' ), ( '\\A0\A1\A2\A3\' ),
  ( '\\B0\' ), ( '\\B0\B1\' ), ( '\\B0\B1\B2\' ), ( '\\B0\B1\B2\B3\' ),
  ( '\\C0\' ), ( '\\C0\C1\' ), ( '\\C0\C1\C2\' ), ( '\\C0\C1\C2\C3\' ),
  ( '\\D0\' ), ( '\\D0\D1\' ), ( '\\D0\D1\D2\' ), ( '\\D0\D1\D2\D3\' );

declare @Permissions as Table ( PermissionId Int Identity, Permission VarChar(32) );
insert into @Permissions ( Permission ) values
  ( 'Create' ), ( 'Delete' ), ( 'Read' ), ( 'Write' ), ( 'Corrupt' );

select * from @Folders;
select * from @Permissions;

-- It is assumed that all root folders have permissions explicitly specified.
declare @FolderPermissions as Table ( FolderId Int, PermissionId Int );
insert into @FolderPermissions ( FolderId, PermissionId ) values
  ( 1, 3 ), ( 1, 4 ),
  ( 3, 3 ), ( 3, 4 ),
  ( 5, 3 ), ( 5, 4 ),
  ( 6, 3 ), ( 6, 4 ), ( 6, 1 ), ( 6, 2 ),
  ( 9, 3 ), ( 9, 4 ), ( 9, 1 ), ( 9, 2 ),
  ( 11, 3 ), ( 11, 4 ),
  ( 13, 1 ), ( 13, 2 ),
  ( 14, 3 ), ( 14, 4 ),
  ( 16, 5 );

-- Dump the sample data.
select Folder,
  Stuff( ( select ',' + Permission from @Permissions as P inner join @FolderPermissions as FP on FP.PermissionId = P.PermissionId where FP.FolderId = F.FolderId order by P.PermissionId asc for XML path(''), type).value('.[1]', 'VarChar(max)' ), 1, 1, '' ) as Permissions
  from @Folders as F
  order by Folder;

-- Generate a folder tree with inherited permissions.
with FoldersWithDepths as (
  -- Depth   is zero for root folders, 1 for children of roots, ... .
  select FolderId, Folder, Len( Folder ) - Len( Replace( Folder, '\', '' ) ) - 3 as Depth,
    Stuff( ( select ',' + Permission from @Permissions as P inner join @FolderPermissions as FP on FP.PermissionId = P.PermissionId where FP.FolderId = F.FolderId order by P.PermissionId asc for XML path(''), type).value('.[1]', 'VarChar(max)' ), 1, 1, '' ) as Permissions
    from @Folders as F ),
  FolderTree as (
    -- Start with root folders.
    select FolderId, Folder, Depth, Permissions, Cast( 1 as Bit ) as PermissionsChanged, Cast( NULL as Int ) as ParentFolderId
      from FoldersWithDepths
      where Depth = 0
    union all
    -- Add children on the way down while inheriting permissions from their parents if no permissions are explicitly specified.
    select Child.FolderId, Child.Folder, Child.Depth, Coalesce( Child.Permissions, Parent.Permissions ),
      Cast( case when Coalesce( Child.Permissions, Parent.Permissions ) = Parent.Permissions then 0 else 1 end as Bit ), Parent.FolderId
      from FolderTree as Parent inner join
        FoldersWithDepths as Child on Child.Depth = Parent.Depth + 1 and Child.Folder like Parent.Folder + '_%\' )
  select FolderId, Depth, ParentFolderId, Replicate( ' ', Depth * 2 ) + Folder as Folder,
    PermissionsChanged, Permissions
    from FolderTree
--    where PermissionsChanged = 1 -- Controls whether all folders are shown or only those which have permissions not matching their parents'.
    order by FolderTree.Folder;

Debugging/comprehension aid: You can change the final select to select * from FoldersWithDepths to see the intermediate results.
Comment: Wow. Thank You @HABO, I've been looking at the code for the last 10mins digesting it.  I'm surprised one CTE can get this off.  Can't wait to get a chance to run it.  I greatly appreciate your help
Comment: @JasonR. Was that _the answer_?
Comment: I couldn't figure it out this way.  This was a table populated by a SSIS job from a C# script.  There was already a script that inserted all differences to a table, which is the source table for this question.  I wrote a second script that populated a second table with the results I was looking for.  As I enumerated through the folders, If there was a difference from the one folder to it's sub-folder, I inserted everything I wanted to know.  If there wasn't, I skipped the insert until there was.  That got me what I was looking for.  I'd still like to try and figure it out in the future though.
Comment: thanks for your help though.  I played with your code for a while until I wrote the script.  I don't think it was far off.  This reminded me I had it and I will play with it again soon just for my own knowledge.


representing sound graphically as wave

Question: I Have created an app that records and plays sound and I am looking for a way of showing a simple wave
representation of the recorded sound, no animation is necessary, just a simple graph.
It would also be nice it is was possible to select a subset of the wave and ofcourrse even more nice
playing that section aswell.
To sum up, what I'm looking for:

A way of graphically represent a recorded sound as a wave (e.g as seen in audacity)
A way of graphically selecting a subset of the wave representation.

And to clarify a bit further of what I'm looking for:

If there is a lib for this I'd be insanely happy :)
A hint on what components to best use for handling the graph drawing.
A tip on how to handle the selection within the graphical component.
Comment: What should the axes of the graph be? Volume vs. time? Time-integrated volume vs. frequency?
Comment: Beta: Yes, Time for x-axis, and whatever gives the best representation(volume?) for the y-axis.
Comment: You already know how to write an app, and I presume you know how to manipulate the sound file, so it's a question of displaying graphics and/or a GUI. I don't know how much you know about those subjects, so I suggest you edit your question to clarify what it is you need help with. (I know very little about iOS graphics, so I probably can't help you.)
Comment: I am mainly looking for help with the graphical stuff, I.e what components to use for this and why. Added a little bit more info to clarify my request, thanks for the feedback, Beta.
Answer: I already did this in another application and have been struggling with it for a while ...
You would divide the number of samples the audio file has by the number of pixels you have to display the graph. This gives you a chunksize.
For all the "buckets" you calculate the min and max value and display them in relation to the sample resolution used.
Can provide further examples if needed.

Regarding the graphics stuff:
(I am not an iOS developer but Mac programming isn't that much different I think.)
Just create a subclass of NSView ( should be UIView in iOS ) and override the drawRect method.
Then just create a function which you pass an array of values for your file and draw a bunch of lines to the screen. It's no black magic here!!
This is really nothing you would need a library for!
And, as another positive aspect : if you keep it generic enough you can always reuse it.
Comment: You have to decode it first to get the actual values. This question seems to be addressing this exact issue http://stackoverflow.com/questions/6902730/when-reading-audio-file-with-extaudiofile-read-is-it-possible-to-read-audio-flo  I was using the mpg123 library because I was using C++ instead of objc
Comment: Thanks, you override-strategy sound like a great way of doing this. I guess that the same class also could catch and store an x-interval representing the selection made by pinching and use those coordinates for drawing and overlay in the drawRect-method aswell. Sorry for the long comment, but I kinda got a bit carried away :)
Comment: I always like to help out!! Especially if it's in my "home territory". I also have a diploma in audio-engineering ;) So hit me up if you need more info. Best
Comment: Started out Implementing the graphing as you proposed and it is excellent. I've only been doing simple playing-taskt with tha AVAudioPlayer before so any help on how to read info about an mp3 that is usable for the graphing would be really appreciated!

representing sound graphically as wave


The closure in the discrete/trivial topology

Question: I want to determine if the two statements below are true or false:

In the discrete topology $\overline{Y} = Y$, for all $Y ⊆ X$.
In the trivial topology $\overline{Y} = X$, for all $Y ⊆ X$.

How does knowing the topology help us here? Doesn't it only tell us what subsets are open, but how does that relate to the closure?
Comment: In the discrete topology, all sets are closed. In the indiscrete topology, only $\emptyset$ and $X$ are closed.
Answer: If you know the open stes, then you know the closed sets, since they are the complements of the open sets.
a) It is true, since every set is open and therefore every set is closed.
b) It is false (unless $X$ turns out to be the empty set), since $\overline\emptyset=\emptyset$.
Comment: @GEdgar But it will work if you assume $Y$ is nonempty.
Comment: no basically because the intersection of all closed sets containing the set is then the set itself (a priori it might be bigger, but since you know the set itself is closed ...)
Comment: b) holds in case $X$ has one point, right?
Comment: @GEdgar No. If $X\neq\emptyset$, $\overline\emptyset=\emptyset\neq X$.
Comment: @JoeJohnson126 Indeed.
Comment: Why does every set being closed mean that the closure of a set is equal to the set? Is it because the intersection of closed sets is closed?


Find the area of the surface obtained

Question: <code>The curve , x^2 , is rotated about the y-axis.
(a) Find the area of the resulting surface.
(b) Find the area of the surface obtained by rotating the curve
in part (a) about the x-axis.
</code>
Okay Part A was easy for me. I just found dy.dx and used the ds formula and put ds in the area formula.
But for part b, it asks the same thing except it wants to rotate about the x-axis. How would I do this?
Thank you,
Comment: Just like how you found the area of $y=x^2$ rotated about the $y$-axis, find the [area](http://tutorial.math.lamar.edu/Classes/CalcII/SurfaceArea.aspx) of $y=x^2$ rotated about the $x$-axis.
Comment: Well, I sorta figured that much. Okay then dy/dx = 2x ... ?
Answer: What we rotate was incompletely specified. Say it is the part of the curve $y=x^2$ from $x=0$ to $x=c$, where $c\gt 0$.
To solve the second problem,  interchange the roles of $x$ and $y$. So our curve is $x=\sqrt{y}$. We have
$$\frac{dx}{dy}=\frac{1}{2\sqrt{y}},$$
so we end up with the integral
$$\int_0^{\sqrt{c}} 2\pi y \sqrt{1+\frac{1}{4y}}\,dy.$$
So we want to integrate $\pi \sqrt{4y^2+y}$. Somewhat unpleasant, but doable by completing the square, and making the appropriate substitution, either a secant or a hyperbolic cosine.
Remark: Slightly more mechanically, we can observe that the surface area (of the curved part) is
$$\int_0^c 2\pi x^2 \sqrt{1+4x^2}\,dx.$$
We get an integral that is not very pleasant. But it yields (after a while) to the substitution $2x=\tan t$ or $2x=\sinh t$.
Comment: You are welcome. I wanted to stress the fact that one can interchange the roles of $x$ and $y$, but will add a second way.
Answer: To rotate a function around an axis you parametrize it correctly, in this case the parametrization is:
$\sigma(\phi,t)=(t,t^2\cos\phi,t^2\sin\phi)$ Where the domain of $t$ is the original domain of $x$, and $0\le\phi\le 2\pi$.
Effectively what happens in this parametrization, is $(t^2\cos\phi,t^2\sin\phi)$ represents a "circle" where the radius varies exactly like the function we wish to rotate. Then the "$(t)$" part is just the $x$ axis, which changes linearly since we are rotating the function around the $x$ axis.

Find the area of the surface obtained


Como é atualizada/incluida uma página em PHP via AJAX?

Question: Comecei a pensar em utilizar AJAX em uma aplicação que estou desenvolvendo, mas encontrei alguns problemas com o mesmo. Gostaria de entender como ele funciona, para aproveitar ao máximo esta "ferramenta".
Não tive problemas ao acrescentar páginas estáticas ou com scripts simples em php.
Tenho, até então, em minha mente que a função envia a requisição para o servidor, armazena a resposta em uma variável e nós decidimos o que fazer com ela.
$('li > a').click(function(evt){

evt.preventDefault();

var href  = $(this).attr('href');
var pages = "includes/pages.php?page=" + href;
$.ajax(pages, {
  beforeSend: function(){
    $('#content').fadeOut();
  },
  success: function(response){
    $('#content').html(response).fadeIn();
  }
});

Minha maior dúvida sobre a inclusão/update de arquivos na página via AJAX é sobre includes e requires.
<?php

$page = @$_GET['page'];

switch ($page) {
    case 'home':
        acoInclude('home.php');
        break;

    case 'ceps':
        acoInclude('ceps.php');
        break;

    case 'clientes':
        acoInclude('clients.php');
        break;

    default:
        acoInclude('home.php');
        break;
}
?>

O arquivo php em questão possui uma função personalizada (acoInclude()) que está dentro do arquivo primfunctions.php, dentro de functions.php que por sua vez está incluído no index.
Basicamente: index.php <-> functions.php <-> primfunctions.php
Ao executar o script, me é retornado um fatal error
Fatal error: Call to undefined function acoInclude() in C:\wamp64\www\gn\sistema\includes\pages.php on line 7

Mas se eu incluir o arquivo primfunctions.phpdiretamente no pages.php — para isso usei a seguinte lógica: isso (AJAX) deve funcionar tipo um iframe, e um script deve ser independente de outro — recebo mais um fatal error
 Fatal error: Cannot redeclare acoInclude() (previously declared in C:\wamp64\www\gn\sistema\includes\primfunctions.php:16) in C:\wamp64\www\gn\sistema\includes\primfunctions.php on line 18

Então ficam as perguntas: como os scripts em PHP são incluídos via AJAX? Por que meu script está com estes erros? Como solucioná-los de maneira proveitosa para a aprendizagem?
EDIT: Função acoInclude
function acoInclude($page){
    include('/pages/'.$page);
}

Answer: script PHP e Ajax não estão relacionados.
Podes pensar no Ajax como uma "visita" do browser, que chama um ficheiro PHP e devolve a resposta que este lhe dá, como se fosse um utilizador.
Portanto os erros de PHP que tens não são relacionados com Ajax e nem podem ser resolvidos por ele.
O que fazer então?
Os erros que tens acontecem porque estás a chamar uma função que não está defenida no PHP. Para a defenir tens de incluir o(s) ficheiro(s) que contêm essa função.
Assim tens de colocar no teu ficheiro PHP, antes desse switch:
require_once('primfunctions.php'); // corrige o caminho se não for este

assim o erro deve desaparecer. Depois disso presumo que essa função acoInclude('home.php'); retorne HTML, nesse caso deves ter um echo antes, para ela de facto mostrar o resultado a quem estiver à procura dele. Um browser ou o Ajax:
echo acoInclude('home.php');


error: 'struct sigevent' has no member named 'sigev_notify_thread_id'

Question: The following "toy" code represents a problem I am having in a larger code base using POSIX timers.
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <iostream>

using namespace std;

int main()
{
    struct sigevent sevp;
    long threadId = 5;

    sevp.sigev_notify = SIGEV_THREAD_ID;
    sevp.sigev_notify_thread_id = threadId;

    return 0;
}

When I try to compile it using g++ on a Linux machine I get the error:
error: 'struct sigevent' has no member named 'sigev_notify_thread_id'

Is there a reason why? This leads me to believe that the sigevent struct has a member called sigev_notify_thread_id.
Comment: Thanks @Duck. `sevp._sigev_un._tid` and line 295 "here - http://lxr.free-electrons.com/source/include/uapi/asm-generic/siginfo.h#L295" fixed my problem. Post that as an answer and I'll accept!
Answer: Changing sevp.sigev_notify_thread_id to sevp._sigev_un._tid fixed my problem. You can see the definition on line 295 here.
Thanks to @Duck for the helpful comment.

error: ‘struct sigevent’ has no member named ‘sigev_notify_thread_id’


dns in a small network with router and AD domain

Question: I have a small office network with router (running OpenWRT), Windows Domain Controller (used to be 2008R2; I just backed it up and upgraded to 2012), about a dozen AD clients (3 server and windows workstation) and several non-AD clients (network printer, PBX).
The problem is that the clients can't access servers by name (only by IP). I tried all kind of permutations. Right now domain controller runs DNS server for all desktops; but unless I put an entry in hosts file - I can only get by IP. I have router as DHCP server (since not all devices are on AD); and except for Domain Controller all IP addresses, including "static", are assigned by the router.
Most frustrating, some servers sometimes just work! for example, I can often get to the Linux box by name (it is part of Domain using Beyond Trust Integration Services); but I can never get to SQL Server box. Seems like non-domain devices see more names than domain members...
This network should be fairly typical; but I couldn't get any guidance about how to set up DNS/DHCP service to make all nodes happy. The closest is this question, but still it's different!
Thanks
Comment: Do the systems successfully resolve the active directory domain's name?  How about the names of domain controllers?  Active Directory won't work without those things, but maybe it's working only due to NetBIOS name resolution.. Can you test what specific responses come back from the domain controller's DNS when you query for the fully-qualified name of an entry in the domain's DNS zone with `nslookup` (or `dig` on the linux box)?
Comment: just wondering what was the reason for downgrading the question... urrgh!
Answer: I'm a little confused by some of your terminology:
"and except for Domain Controller all IP addresses, including "static", are assigned by the router." -- uh... no. If the router is assigning addresses then they're not static.
"I have router as DHCP server (since not all devices are on AD)" -- Not sure why you've done this. Devices do not need to be a member of an Active Directory Domain to use DHCP services provided by a Windows server.
As for "how to set up DNS/DHCP service to make all nodes happy",Ii should be very simple.

A Windows server, probably the domain controller on a small network, should be providing DHCP.
The domain controllers (ideally you'd have more than one?) should have the DNS role installed and configured to support AD, and DNS should forward any requests it cannot resolve to the ISP's DNS servers.
The clients should have their DNS settings configured to point to the DNS server, and their gateway should point to the router.
Local firewall on each windows system (server or client) should either be disabled or, more ideally, should be correctly configured to see the whole of your internal IP address scheme as a workplace network, with an appropriately configured domain profile.
Comment: that's why I put "static" in quotes - it is DHCP, just that it's always the same IP (by MAC address), so I can put it in the hosts file.
So, I started with the simple setup that you described. I think my problem was that DC *didn't* forward requests to ISP's DNS servers. That might have root cause of all my problems - and I didn't have much time, since the users couldn't access Internet. I just gave up and went to more complex route.
Any pointers to setting up **that**?
Comment: @felix - setting up what? DNS Forwarding? Have you looked at http://technet.microsoft.com/en-us/library/cc754941.aspx -- fwiw, tip for the future... if you're editing hosts files just to set up a basic network these days then you're either trying to do something *very* non-standard or you're doing something wrong... that's always time to step back and re-assess what's happening.
Comment: I try to have as standard configuration as I can (it's my wife's business, and while they think I am computer genius, my IS experience was mainly on application development side). I know I am doing something wrong! That's why I am here, stepping back and reassessing :) One other point. The reason I set up the router to provide DHCP services was because some devices (both domain-member laptops and non-domain devices) are wireless, and I couldn't figure out how to set up two DHCP servers without conflict. So, even if I figure out DNS forwarding, wouldn't I need to also configure 2 DHCP servers?
Comment: To summarize - my initial plan was to get DHCP services (IP address) from the router, and DNS services (name resolution) from domain controller with DNS forwarding. Was that a bad idea to begin with?
Comment: You don't need DHCP on the router, you should only have one DHCP server on the network. Actually that's not quite true http://serverfault.com/questions/368512/can-i-have-multiple-dhcp-servers-on-one-network) but for what you're doing lets pretend it is. So you should only configure the router OR the server as DHCP. You've done this by choosing the router but putting DHCP on the server only does simplify things greatly imho.
Comment: if I put DHCP on the server - how would wireless devices get on the network then? Anyway, let's put that aside for a moment; I went back to how I started (DHCP from the router, DNS from domain controller, DNS forwarding). Some nodes work perfectly; others don't resolve *any* names. Let me do more troubleshooting and describe in a separate comment. I think I am 80 per cent there, and with your kind advice I can get to 100% :) Thank you for your help!
Comment: The wireless and wired clients on your network are on *the same* network. Unless your router has specific settings to separate the two networks and you've turned those settings on, the wired and wireless network devices should be able to see one another fine...
Comment: They are and they do! But if router doesn't act as DHCP server, how will wireless devices get IP assigned to them in the first place? Server doesn't have wireless interface.
Comment: The wireless devices will get DHCP addresses from the DHCP server... *Any* DHCP server. If you read the question / answer I linked to a few comments back, I explained there how DHCP actually works, and that might clear a few things up.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/6452/discussion-between-felix-and-robm)
Answer: This is a fairly simple issue to resolve.  Disable the DHCP service on your router or enable the option to forward the DHCP calls to the AD server.  In order to have name lookup work you really need to have two aspects enabled. This is a assuming that you already have a DNS server enabled in the AD (which is required for AD functionality) and it has all of the DNS forwarding setup correctly for DNS inquiries beyond your AD.
First you need to have all of the workstations requesting DHCP addresses get the address requests from a DHCP server which is part of the AD.  The DHCP server once registered in the AD must be first trusted/authorized and then have the option enabled to dynamically update the DNS server as it registers DHCP leases.  This will allow the DNS server to dynamically update the A records for your domain in DNS.  You may want to enable the reverse registration as well as that will update the PRT records as well.  Be sure to make sure you are appending the domain suffix to your hostname in your settings as well.
The second step is the easy step.  You then must use your AD DNS server for all of your DNS queries.  At least it must be the first of your name servers.  You can technically have as many as you want.  However the AD DNS server must be first. You ISP DNS servers I suppose could be the second entry if you need to have one.
In doing this you enable your workstations to lookup local domain hosts using just the NetBIOS address or the FQDN as the DNS server you are working against is dynamically registering the other workstations, printers and other AD assets as they claim DHCP leases.  The dynamic registration is critical so as the DHCP lease expires and a new lease is issued, potentially changing the IP address of the workstation, the new information is updated in to the AD DNS entries.
Good luck.
Answer: What I like to do is to set up DHCP in the wireless router for the wireless client hosts.  I'll run two scopes, each unique to the LAN subnet and each in its own VLAN, one for a private wireless network and another for a guest wireless network.  Then, in the router, I will route the private wireless network to the LAN subnet, and deny the guest wireless network to the LAN subnet, giving guest wireless users only internet access and no access to LAN/domain resources.  This way the wireless networks are on separate segments of the network, giving me greater control over the traffic for security, prioritization, reporting, etc.  I always run DHCP on a Windows domain on the Primary Domain Controller for the LAN, with auto-registering for DNS, as described.
This would create a situation where wireless hosts on the private wireless network would not register in domain DNS, but usually hosts on the LAN do not need to access PC hosts on the LAN with name-based resolution.  Usually this is only needed for server resources, or printers or other hosts that require access by all LAN users/hosts.


How to create schemas for Web service/wcf service

Question: I am new to BizTalk, I wanted to create schemas for Web service/WCF service.
please let me know, what I need to create. I have installed the WCF service in VS 2019.
please share the Microsoft docs link here. so that I can follow
Thank you
Answer: Hope these docs can help you.
https://learn.microsoft.com/en-us/biztalk/core/publish-schemas-as-wcf-services--use-the-biztalk-wcf-service-publishing-wizard
 https://learn.microsoft.com/en-us/biztalk/core/wcf-adapters-property-schema-and-properties
https://learn.microsoft.com/en-us/biztalk/core/using-wcf-services


How is offside determined in football?

Question: The offside rule on the pitch is often unclear and called suddenly. How do I know if a player is offside?
Answer: Wikipedia article on "offside" is very comprehensive and largely based on the official IFAB Laws of the Game.
From the article, what it is:

Offside is a law in football which states that if a player is in an offside position when the ball is touched or played by a teammate, he may not become actively involved in the play. A player is in an offside position if he is closer to the opponent's goal line than both the ball and the second-to-last defender (which is usually the last outfield player), but only if the player is on his opponent's half of the pitch.

How it is officiated:

In enforcing this rule, the referee depends greatly on an assistant referee, who generally keeps in line with the second-to-last defender, the ball, or the halfway line, whichever is closer to the goal line of his relevant end. An assistant referee signals that an offside offence has occurred by first raising his or her flag upright without movement and then, when acknowledged by the referee, by raising his or her flag in a manner that signifies the location of the offence

So in my own simple words, you determine an offside by:

At the time when the ball is played (pass or kick down the field) note where the second last defender (usually the last defender as the goalkeeper is usually furthest back of any, but not always!) of the defending team is and where is the player(s) of the offending team (who are involved in the play*) are further down the field from the ball
Draw a line parallel to the base line (goal line) of the pitch through the said players
If you see that the line going through an offending player who is about to receive the ball is closer to the goal than the line going through the last defender, and that line is in the defending half, then it is an offside.

by "involved in the play" we mean that they are likely to either receive the ball as a result of the pass in question or are able to influence the outcome of the play in some other way. A player would not be considered involved if he is on the other side of the pitch with the ball going away from him.

Refer to the Laws of the Game for more info.

Notice that there are a few exceptions when someone can be or not be offside.

When a ball is brought back into play after it left the pitch, one can never be offside. So, one can never be offside after directly receiving a ball from a throw-in, goal kick, corner kick or a kick off (of which the latter two are rather trivial). From a (indirect) free kick one can be called offside, since the ball had not left the pitch.
Suppose someone shoots for goal while his teammate is in offside position. When the ball then returns from the post, the bar or even the goalkeeper and comes in the possession of the teammate, he is still offside.
Offside is not bounded by the lines of the pitch. So, one can still be offside or prevent an opponent from being offside while being out of play. See gbianchi's answer to this relevant question.
Comment: One other part to it - the person who is to be called offsides must be involved in the play at the time of the pass.  So if the passer is kicking the ball into the right side corner, a player on the far left side can be closer to the goal than two defenders, and would not technically be offside.
Comment: Note that the involvement in the play is now defined quite explicitly in the Laws of the Game (and their official interpretation): Either playing or touching the ball, or preventing an opponent from playing or being able to play the ball by clearly obstructing his vision or movements or making a deceiving or distracting gesture or movement, or playing a rebound ball having been in an offside position. (Your summary is generally correct, but there are those subtle corner cases…)
Comment: Note also that the player on the defending team does not have to be on the pitch to be counted as the last defender. This came up in a Euro 2008 match between the Netherlands and Italy.

http://blogs.reuters.com/soccer/2008/06/10/should-ref-have-called-van-nistelrooy-goal-offside/
Comment: I like Brian Clough's statement on the matter:  "If you're not interfering with play, you shouldn't be on the pitch".
Comment: Great point @MikeHedman. I'll add this to the answer.
Comment: I once was a linesman for a kid's game where the ref called someone offside because they *carried* the ball past the second-last defender.  I made him switch with me at halftime.
Comment: @DmitrySelitskiy Your own interpretation is not completely correct, because there have to be two defenders between the base line and the offending player. Usually the second one is the goalkeeper which usually is near the base line. If the goalkeeper is somewhere else, there have to be two defending fieldplayers between the offending player and the baseline. Quote from wiki: _And third, there must be fewer than two opposing players between him and the opposing goal line, with the goalkeeper counting as an opposing player for these purposes_
Comment: @DmitrySelitskiy - you should perhaps also add that the attacking player is only offside if the part of the body that is offside is a part with which he can score.  That is, an attacker's arm can be past the second-to-last defender but his foot can not.
Comment: Also worth noting that offside doesn't apply from goal kicks and throw-ins.
Answer: A Picture is worth thousand words! Hope this helps you understand
Comment: I don't understand the purpose of the pentagon in this graphic; could you explain it? The information here is good, but one disadvantage of images to text is that images are hard to index/search.
Comment: This picture is nothing but a bunch of words arranged in an unreadable manner, and worse, the words are unsearchable. It would have been better to just list five headings with bullet points as actual text.
Answer: I've noticed that football players often talk about being level with the second last defender; but the FIFA offside rule is now much more precise. At the instant the ball leaves the attacking player the offside vertical plane is fixed at the part of the second defender (other than his arms) which is closest to the goal line. At that instant, if any part of another attacking player has any part of their body (except the arms) beyond that plain they are potentially offside.
Answer: A couple of quick additions, which I have not seen mentioned in previous answers (it's late and I am very tired so I might have missed, if that's the case I'll remove this answer)
There is a scenarios which might be confusing; a player is not off-side if;

beyond the second lass defender but the pass to him comes from a team mate that is further ahead of him i.e. if the pass is backwards (similar to rugby)

There is a pretty nice guide which explains the concept in detail, with illustrations.
Answer: A bit stupid to make this an answer but it's not yet (completely correct) on here. And I can not comment yet, so here goes:
In addition to posdef's answer: you can be in an offside position if a player passes backwards as much as with a forward pass.
As long as the player stays behind his teammate it does not matter in which direction the pass is given. But if he is in front of his teammate and gets the pass played at him in backward direction he is still in an offside position.
Comment: An attacking player is NOT in an offside position when: (1) on his own teams half, or on the half-way line, (2) when further away from the opposition's goalline than the second to last defender & (3) when further away from the opposition's goalline than the ball. These three things are the only ones that count when determining whether or not an attacker is in an offside position (with the exception of throw-ins, goal-kicks and corner kicks).
Comment: Well I explained (3) ;)
Comment: Yeah, I realized that - but my point is that the direction of the pass is irrelevant :) The only thing that matter is whether or not you're in an offside position when the ball is passed/deflected.
Comment: Oops, I realize now that we actually agree. Sorry for that :)
Answer: I used to help ref soccer games when I was younger and the way I was taught to call the off-sides penalty was that if the player on offense was beyond the last defender (goalie doesn't count obviously) before the ball was also beyond the last defender, then the player is off-sides. Some people (myself included) think the way it should be called is that the player on offense needs to be even with the defender, but should be allowed to pursue the ball as soon as it is passed to them, regardless of their position relative to the other teams defensive players. In other words - let one players speed and instinct give them an advantage - rather than a penalty.
Comment: Actually, it's the second-last defender and the keeper does count.
Comment: Yes, but the FIFA Laws of the game apply in youth soccer as well.  FIFA spells out which laws can be changed, and Law 11 (Offside) is not one of them.
Comment: And the rule *is* that they have to be onsides at the kick, not when the ball passes the defender.
Comment: you are correct - I meant in the context of the traditional goalie being in the goalbox and the defensive player being further up the field. I guess if the goalie ever came out far enough to not be the last defender than you would need to take the second-last defender rule into account.

And yes, that *is* the rule - which is why I usually chose to call it that way rather than what I was told I should do. This was just youth soccer games though - I think you guys are talking more about the official FIFA rules.
Comment: The most common case where the keeper is not the last defender is shortly after a corner kick. You can't be offside from the corner kick itself, but if the keeper comes out for it then it's anybody's guess who the last two defenders will end up being. So, players following up on a rebound are vulnerable to being offside when the shot was taken. Of course, some defensive units make this easy for the officials by putting a man on each post, playing everyone onside :-)
Answer: The offside rule states that if the attacking player receiving the ball is behind the last defender (not including the goalkeeper) at the time the ball is played through to them they are deemed offside.
However this rule does not apply in the event of a throw-in and can only be enforced if the player is inside his attacking half.

How is offside determined in football?


No module called pylogit

Question: I am unable to find the pylogit package in python, when I run this "import pylogit as pl", I get back the error saying no module called pylogit. can you please advise.
Answer: pylogit is not a standard Python module. It is not installed by default. You need to install the library on your machine with a package manager like pip or conda.
Answer: Building off of what Code-Apprentice stated, you'll need to run the commands...
pip install pylogit, more info here.
or...
conda install -c timothyb0912 pylogit, more info here.
If you are unsure what command you should run, here is another stack overflow discussion about the differences between the pip and conda.

No module called pylogit


How to get the class reference inside an onClick listener in Android?

Question: I am trying to call this method inside an onClick listener:
        mHelper.launchPurchaseFlow(this,
                SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS,
                RC_REQUEST, mPurchaseFinishedListener, payload);

But because it is inside an onClick listener, the reference to this becomes not the reference to the class, but the onClick listener. Is there a way to pass the class reference if this code is inside the onClick listener?
Thanks!
Comment: try using getApplicationContext() instead of this
Comment: this looks like a similar problem that was already posted here: [http://stackoverflow.com/questions/23676634/use-variable-defined-in-one-event-in-other-event/23677099#23677099](http://stackoverflow.com/questions/23676634/use-variable-defined-in-one-event-in-other-event/23677099#23677099) I hope it helps Kind regards
Answer: If your containing class is called e.g.MyClass then you can just use MyClass.this:
 mHelper.launchPurchaseFlow(MyClass.this,
                SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS,
                RC_REQUEST, mPurchaseFinishedListener, payload);

Answer: Define Context mContext=null; in your activity and in oncreate method of activity make instance of this as
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         mContext = this;
}

and use
mHelper.launchPurchaseFlow(mContext,
                    SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS,
                    RC_REQUEST, mPurchaseFinishedListener, payload);

or directly use
mHelper.launchPurchaseFlow(youractivity.this,
                        SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS,
                        RC_REQUEST, mPurchaseFinishedListener, payload);

Answer: There can be 2 cases
1) If your class extends Context eg. Activity,Service you can do
mHelper.launchPurchaseFlow(getApplicationContext(),SKU_INFINITE_GAS,IabHelper.ITEM_TYPE_SUBS,RC_REQUEST,mPurchaseFinishedListener, payload);

2) If your class does not extend Context then you need to pass an object of Context to that class in some way and call
mHelper.launchPurchaseFlow(mContext.getApplicationContext(),SKU_INFINITE_GAS,IabHelper.ITEM_TYPE_SUBS,RC_REQUEST,mPurchaseFinishedListener, payload);

where mContext is an object of Context class


Problem about response data from Slice to index.js - React redux toolkit

Question: I want to fetch data from API and trying to use in index.js
Error:

TypeError: Cannot read properties of undefined (reading 'icon')

When I console.log it prints

Empty Array of index.js > response data of weatherSlice.js > and finally  response data of index.js as an array

I was getting undefined error and tried this and kinda worked .
{getCity.length !== 0 && (
<Typography variant="h6"  component="div">

Wind : {getCity.current.gust_kph} kph

Pressure: {getCity.current.pressure_in} in

</Typography>
                )}

But this time it gives same error on this block
{getCity.length !== 0 && (
  <Grid item xs={3} sx={{mb:3}}>

{getDate()}

 <img src={`${getCity.forecast.forecastday[1].condition.icon}`} alt="" />
 // Gives undefined (reading"icon")

22 C

  </Grid>)}

Index.js
const dispatch = useDispatch();
const [selectedCity, setSelectedCity] = useState('Ankara');
const getCity  = useSelector((state) => state.weather.item);
const [datee , setDate ] = useState('');

useEffect(() => {
    dispatch(fetchDefault(selectedCity))
    setDate(getDate())
}, [dispatch])

weatherSlice
export const fetchDefault = createAsyncThunk('weather/getWeather', async (selectedCity) => {
const res = await axios(`http://api.weatherapi.com/v1/forecast.json?key=ebb6c0feefc646f6aa6124922211211&q=${selectedCity}&days=10&aqi=no&alerts=no
`)
return res.data});

export const weatherSlice = createSlice({
name: "weather",
initialState : {
    item : [],
},
reducers:{},
extraReducers:{
    [fetchDefault.fulfilled]: (state , action) => {

        state.item = action.payload;

        console.log(state.item)

    },
    [fetchDefault.pending]: (state , action) => {

        console.log("sadsad")
    }
}

Comment: Where are you attempting to read any `name` property in your shared code snippets? What is `getCity`? It looks like you think it's an array, but then a couple lines later start accessing non-array properties. We need more context. https://stackoverflow.com/help/minimal-reproducible-example
Comment: I edited , sorry it is icon not name and i suppose getCity is getting item as array from slice ..
Answer: After the state.weather.item state is populated it's now an object, not an array. The initial condition getCity.length !== 0 works/passes because getCity.length is undefined and undefined !== 0 evaluates true. The issue is occurring after you start accessing into the state.
The fetched city data is an object with location, current, and forecast properties.
// 20211114135700
// https://api.weatherapi.com/v1/forecast.json?key=ebb6c0feefc646f6aa6124922211211&q=seattle&days=10&aqi=no&alerts=no

{
  "location": {
    "name": "Seattle",
    "region": "Washington",
    "country": "United States of America",
    "lat": 47.61,
    "lon": -122.33,
    "tz_id": "America/Los_Angeles",
    "localtime_epoch": 1636927019,
    "localtime": "2021-11-14 13:56"
  },
  "current": {
    "last_updated_epoch": 1636926300,
    "last_updated": "2021-11-14 13:45",
    "temp_c": 16.1,
    "temp_f": 61.0,
    "is_day": 1,
    "condition": {
      "text": "Light rain",
      "icon": "//cdn.weatherapi.com/weather/64x64/day/296.png",
      "code": 1183
    },
    "wind_mph": 13.6,
    "wind_kph": 22.0,
    "wind_degree": 190,
    "wind_dir": "S",
    "pressure_mb": 1014.0,
    "pressure_in": 29.94,
    "precip_mm": 1.0,
    "precip_in": 0.04,
    "humidity": 90,
    "cloud": 100,
    "feelslike_c": 16.1,
    "feelslike_f": 61.0,
    "vis_km": 3.2,
    "vis_miles": 1.0,
    "uv": 4.0,
    "gust_mph": 18.8,
    "gust_kph": 30.2
  },
  "forecast": {
    "forecastday": [
      {
        "date": "2021-11-14",
        "date_epoch": 1636848000,
        "day": {
          "maxtemp_c": 16.2,
          "maxtemp_f": 61.2,
          "mintemp_c": 11.5,
          "mintemp_f": 52.7,
          "avgtemp_c": 14.9,
          "avgtemp_f": 58.8,
          "maxwind_mph": 16.1,
          "maxwind_kph": 25.9,
          "totalprecip_mm": 21.1,
          "totalprecip_in": 0.83,
          "avgvis_km": 9.3,
          "avgvis_miles": 5.0,
          "avghumidity": 93.0,
          "daily_will_it_rain": 1,
          "daily_chance_of_rain": 99,
          "daily_will_it_snow": 0,
          "daily_chance_of_snow": 0,
          "condition": {
            "text": "Heavy rain",
            "icon": "//cdn.weatherapi.com/weather/64x64/day/308.png",
            "code": 1195
          },
          "uv": 1.0
        },
        "astro": {
          ...
        },
        "hour": [
          ...
        ]
      },
      ...
    ]
  }
}

You are attempting to render the forecast, but here's where the code really goes sideways. You're assuming there's at least 2 elements (i.e.  the getCity.forecast.forecastday.length>= 2), and then if there is, assume theres aconditionproperty. When there isn't andgetCity.forecast.forecastday[1].condition` is undefined, this is the error you are seeing.
From what I can tell, the condition property is nested within a day field. Since it's unclear what properties are guaranteed to exist in the response data your best bet is to:

First make sure you are accessing into the correct path
Use null-checks/guard-clauses or Optional Chaining operator to prevent accidental null/undefined accesses

The updated object property path is as follows:
getCity.forecast.forecastday.[1].day.condition.icon

If any of these are potentially undefined or otherwise not returned in the data, the corrected access using the Optional Chaining operator is as follows:
getCity.forecast?.forecastday?.[1]?.day?.condition?.icon

Which is the equivalent null-check/guard-clause version of:
getCity.forecast
  && getCity.forecast.forecastday
  && getCity.forecast.forecastday[1]
  && getCity.forecast.forecastday[1].day
  && getCity.forecast.forecastday[1].day.condition
  && getCity.forecast.forecastday[1].day.condition.icon

Use the same sort of check for the current weather data:
{getCity.current && (
  <Typography variant="h6" component="div">

Wind : {getCity.current.gust_kph} kph

Pressure: {getCity.current.pressure_in} in

  </Typography>
)}

Finally, update the initial state for the weather slice to match the data invariant, it should be an object.
initialState : {
  item : {},
},