Relation $ (x,y) \in \rho \Leftrightarrow (\exists k \in \mathbb{Z})\mid x- y=3k$

Question: I know that there is a similar question here, but it's about classes of equivalence of this relation. I would like to know how to prove that this is an equivalence relation. It seems simple, but the first part of the definition of the relation confuses me. It says:
The ordered pair $(x, y)$, being in $\rho$ is the same as the difference between the two elements of the ordered pair can be written as $3k$, with  $k$ is a whole number.
Now, considering the definition of binary relation, $\rho$ is a subset of the Cartesian product $X\times Y$ where both $X$ and $Y$ are subsets of the set of whole numbers. We can say that an ordered pair is in this set only if the difference between them is divisible by three. I would like to know if I understood this correctly.
Now, considering all the  above, I will try to prove that this is an equivalence relation:
Reflexivity:
$(\forall x \in \mathbb{Z}) x\rho x \Leftrightarrow x-x=3k$
This is correct since when I subtract the number by itself I will get $0$, which can be written as $3k$ where $k=0$.
Symmetry:
$(\forall x, y \in \mathbb{Z}) x\rho y \Leftrightarrow x-y=3k \Leftrightarrow y -x=-3k \Leftrightarrow y-x = 3k_1, k_1=-k \in \mathbb{Z}$
Transitivity:
$(\forall x, y, z \in \mathbb{Z}) x\rho y \wedge  y\rho z \Leftrightarrow x-y=3k \wedge y-z=3k \Rightarrow x-z=6k $
Now, I am not quite sure how this is transitive. I would appreciate explanation here, and explanation on the classes of equivalence that I mentioned before, since I don't understand that.
Comment: Because $6k=3(2k)$ and $2k \in \mathbb Z$.
Comment: In the transitivity proof, you use $k$ to represent two potentially different values.  Use $k_1$ and $k_2$ instead.
Comment: Ok, i think i know what you guys meant for transitivity, but how can i determine the classes of equivalence?
Comment: Start building equivalence classes. Pick any integer to get started, I'll pick $0$. Now, can we name some numbers that differ with $0$ by a multiple of $3$? Further, can we name them all? Once we've done that, pick something that *wasn't* equivalent to $0$ and do it all again; figure out *exactly* what its equivalence class contains. Repeat until you've covered all the integers; until the classes partition the set of integers.
Comment: FYI, the relation $x\,\rho\, y$ holds *iff* $x$ and $y$ have the same remainder when divided by $3$.
Answer: Your proofs for reflexivity and stymmetry are somewhat correct. I say "somewhat" because you mean to say the right thing, but I'm inclined to say you natation is incorrect. More on the notation at the end of this answer.
To prove transitivity need to do something like this:
$$(x,y)\in \rho\wedge(y,z)\in\rho\implies x-y=3k_1\wedge y-z=3k_2\implies x-z=3(k_1+k_2),$$ where $k_1,k_2\in \mathbb Z$.
This proves transitivity.
The the use of two (possibly different) integers $k_1$ and $k_2$ is vital here.
The classes of equivalence now consist of numbers with the same remainder when divided by $3$. Or in symbols: $x\sim y\iff x\equiv y\bmod 3$.
Now for the notation. As it is, $\rho$ is a subset of $\mathbb Z\times \mathbb Z$ presumably. Though it could also be defined as a subset of $\mathbb R\times \mathbb R$. It gets awkward when you write $x\rho y$. What would this mean? Instead you best stick to writing $(x,y)\in \rho$. Once you've proved that it indeed is an equivalence relation, it is conventional to write $x\sim y$ for equivalent $x$ and $y$, as I did above.
Comment: If there is still something that's not clear to you, please let me know.
Comment: @cdummie Glad to hear it. Might I ask why you did not upvote my answer? Is there perhaps something I can improve? To see why voting is important please [read this.](http://math.stackexchange.com/help/why-vote)
Comment: I am really sorry if i didn't. I thought i did, since i accepted your answer, green check mark appeared, and i meant that i upvoted it, i see now i should click that arrow going upwards in order to upvote your answer, and since it was indeed useful i will do that (i am still new to this forum, so i am not familiar with these voting things and stuff, hope you don't mind).
Comment: @cdummie No worries. Glad I could help familliarise you with the site.


Find all ASP.NET controls matching a predicate?

Question: I need to enumerate over a collection of controls - regardless of their nesting level - that match a given predicate.
Originally the problem occurred, when I needed to set all textbox's in a grids row to ReadOnly, if a column in that row indicated that the record should not be editable.
Later I realized, that I already solved a problem in the past very much like this one, only with a different criteria (find a single control recursively by its ID).
After trying a few alternatives I came up with a general solution that works. But since I will use this method very often, I wanted to gather possible improvements.
This method will return all child controls matching a predicate:

public static IEnumerable<T> FindChildControls<T>(this Control parentControl,
    Predicate<Control> predicate) where T : Control
    {
        foreach (Control item in parentControl.Controls) {
            if (predicate(item))
                yield return (T)item;

            foreach (T child in item.FindChildControls<T>(predicate)) {
                yield return child;
            }
        }
    }

Using this method I can do the following:
var allTxt = Page.FindChildControls<TextBox>(c => c is TextBox);
var submit = Page.FindChildControls<Button>(c => c.ID == "btnSubmit").First();

Comment: I rather like your version! Neat solution.
Answer: You can use a queue to get rid of recursion if you want.
        public static IEnumerable<T> FindChildControls<T>(Control parentControl,
        Predicate<Control> predicate) where T : Control
        {
            Queue<Control> q = new Queue<Control>();

            foreach (Control item in parentControl.Controls)
            {
                q.Enqueue(item);
            }

            while (q.Count > 0)
            {
                Control item = q.Dequeue();
                if (predicate(item))
                    yield return (T)item;

                foreach (Control child in item.Controls)
                {
                    q.Enqueue(child);
                }
            }

        }

Comment: This is actually very neat, In my situation (heavy page control tree and used about 4-5 time each render) do you think this will be optimal?


Efeito show e hide jquery

Question: Como faço pro jquery abrir apenas a box que cliquei, sem abrir as outras. Tentei usar $(this), mas eu não consegui. Não da maneira que quero.

HTML

    Editar

Box editor 1

    Editar

Box editor 2

    Editar

Box editor 2

JQuery

$(document).ready(function(){
    $(".icon-edita").click(function(){
        $(".Box_editor").show("slow", function(){});
    });
});

Não coloquei o css, pois já está correto o problema é no jquery msm. vlw o/
Comment: Cada `Editar` é suposto mostrar mostrar a `Box_editor` que está logo a seguir?
Comment: é sim isac. quando eu clicar no editar 1 a box 1 aparece
Answer: Se quer mostrar a Box_editor a seguir a cada .icon-edita então tem de utilizar next() para chegar ao elemento da frente, que é a box, e nesse fazer show. Da forma que tem com $(".Box_editor").show( acaba por mostrar todos.
Se pretende mostrar e voltar a esconder cada vez que clica então será melhor utilizar toggle em vez de show
Exemplo:

$(document).ready(function(){
    $(".icon-edita").click(function(){
        $(this).next().toggle("slow");
    });
});
.Box_editor {
  display:none;

}

    Editar

Box editor 1

    Editar

Box editor 2

    Editar

Box editor 3

Comment: Eu não sabia sobre o next() estava usando apenas (this), consegui aqui obg o/
Answer: Acho que vc tem que usar assim: $(this).find
$('.icon-edita').click(function(){
    $(this).find('.Box_editor').addClass(".slow");
    return false;
});

Confere o nome das classes. Dessa forma quando vc clica no elemento com a classe .icon-edita ele vai adicionar a classe .slow só ele e não em todos que tem o mesmo nome da classe

Efeito show e hide jquery


Passing parameter to method gotten from another method?

Question: I am new to Java but I know this stuff I'm just having a seerious brain fart. Could you help me. I've been up for 24+ hours writing code and I'm all confused now. Here is the code in question:
    public long getTheLong() {
    Scanner scano = new Scanner(System.in);
    System.out.println ("enter account number");
    acctNum = scano.nextLong();
    return acctNum;
}

public void searchById(long acctNum) {
// do something with acctNum
{

the first method returns acctNum that gotten by user input. I want to take whatever acctNum is now after getTheLong() method was invoked and pass that to the the following method searchById(long acctNum). How can I do something like this? Thank you so much, I know it's stupid but I'm confused at this point.
Comment: Be sure to change the last curly bracket to '}'!
Answer: try this in your java file
import java.util.Scanner;

public class TestProgram
{

    public static void main(String[] args)
    {
        long acctNum = getTheLong();
        searchById(acctNum);
    }

    public static long getTheLong()
    {
        long acctNum = 0;
        Scanner scano = new Scanner(System.in);
        System.out.println ("enter account number");
        acctNum = scano.nextLong();
        return acctNum;
    }

    public static void searchById(long acctNum)
    {
        // do something with acctNum
    }
}

Answer: try this
public void searchById() {
    long acctNum = getTheLong();
    // do something with acctNum
    }

Answer: long acctNum = getTheLong();
searchById(acctNum );

Answer: You can pass the return value of the one function as an arguement to the second as below.
searchById(getTheLong());

Answer: hi place it before return statement
    searchById(scano.nextLong());
Thanks


MySql, CONCAT and NOT IN, string values

Question: I have such query but it doesn't select anything, but it should. So query
SELECT *
FROM _custom_access_call
WHERE CONCAT(type, name) NOT IN ('string1', 'string2', 'string3')

I manually add to table entry with null and '1sfgsg' values but it wasn't selected. Why? I need to select all entries that concat values is not in array. Help to deal with it.
Answer: If one of the values is NULL, then CONCAT() will return NULL. And NULL NOT IN (...) is always NULL. Also NULL IN (...) is always NULL. If you want to use NULL you should explicitally handle it. In this specific case, CONCAT_WS() helps, because it never returns NULL.
SELECT *
FROM _custom_access_call
WHERE CONCAT_WS('', type, name) NOT IN ('string1', 'string2', 'string3');

Also, note that this query cannot use any index.

MySql, CONCAT and NOT IN, string values


Error on Redmine "plugin redmine_git_hosting" : undefined symbol: libssh2_session_init_ex

Question: I get an error when installing the plugin "redmine_git_hosting":
<code>/opt/bitnami/ruby/bin/.ruby.bin: symbol lookup error: /opt/bitnami/apps/redmine/htdocs/vendor/bundle/ruby/2.0.0/gems/rugged-0.21.4/lib/rugged/rugged.so: undefined symbol: libssh2_session_init_ex
</code>
Redmine 3.0.0.stable
<code>Environment:
  Redmine version                3.0.0.stable
  Ruby version                   2.0.0-p598 (2014-11-13) [x86_64-linux]
  Rails version                  4.2.0
  Environment                    production
  Database adapter               Mysql2
SCM:
  Subversion                     1.8.10
  Cvs                            1.12.13
  Git                            1.9.5
  Filesystem
Redmine plugins:
  redmine_bootstrap_kit          0.2.1
  redmine_git_hosting            1.0.2
</code>
Answer: Bitnami installation

As Bitnami override some internal paths needed to build native Ruby
  extension you must compile libgit2 yourself before installing Redmine
  Git Hosting.

http://jbox-web.github.io/redmine_git_hosting/guide/bitnami-installation/


Is it possible to execute a JavaScript function loaded in a WebBrowser control at any moment in AutoHotkey?

Question: I thought InvokeScript may work but it didn't.
strHTML =
(
<!DOCTYPE html>

This is a paragraph. Click here.

)

new WebBrowser(strHTML)

Class WebBrowser
{
    __New(strHTML) {
        static WB
        Gui, New, Resize
        Gui, Add, ActiveX, vWB w780 h580 , Shell.Explorer
        Gui, show, w800 h600

        WB.Navigate("about:blank")
        Loop
           Sleep 10
        Until (WB.readyState=4 && WB.document.readyState="complete" && !WB.busy)

        WB.Document.Write(strHtml)
        ; WB.Document.Close()

        WB.document.InvokeScript("displayDate")
        ; WB.document.parentWindow.document.InvokeScript("displayDate") ; does not work
        return this

        GuiClose:
        ExitApp
    }
}

Answer: There are at least two ways that you can call the function:
WB.document.parentWindow.execScript("displayDate()")
WB.document.parentWindow.displayDate()

All global functions within the script are available as methods of the window object.
The WebBrowser control referred in the article you linked to is part of the .NET Framework, and is not the same as the WebBrowser control you are using. This is why attempting to call InvokeScript raises an "Unknown name" error message.


Is Attestation Verifiable Credentials Type repo demo available in c#?

Question: I have tested successfully idtokenhint demo and I am trying unsucessfully attestation verifiable credentials type , similar to the Woodgrave Employee Onboarding Demo, is this code available in c#?
In my case I need the Authenticator to request the VerifiedCredentialExpert VC first but I don't see how to trigger this on Authenticator, I tried this on issuance_request_config.json file, I also tried adding requestedCredentials to type VerifiedCredentialExpert as you see below to suggest to Authenticator to get this first, but didn't change the error behaviour:
<code>"includeQRCode": false,
"callback": {
  //In this sample code we will overwrite the callback and use the HOSTNAME dynamicall
  //make sure you use ngrok or something like that when running on a local devbox.
  //The MS AAD VC Request service needs to be able to reach the callback URI
  "url": "https://YOURPUBLICREACHABLEHOSTNAME/api/issuer/issuanceCallback",
  "state": "STATEWILLBESETINCODE",
  "headers": {
    "api-key": "OPTIONAL API-KEY for ISSUANCE CALLBACK API"
  }
},
//The Authority is the DID from your MS AAD Verifiable Credential service, you can copy this from the VC page in azure portal
"authority": "did:ion: THIS IS YOUR DID FROM THE VC PAGE IN AZURE PORTAL WHICH IS SET IN THE SAMPLE BY COPYING THE VALUE FROM APPSETTINGS.JSON   ",
"registration": {
  "clientName": "Verifiable Test Register Verifiable Credential"
},
//The type needs to be the same as defined in the rules json definitione. The manifest can be copied after the credential has been
//created in the azure portal
"type": "VerifiedTestRegistration",
"manifest": "CREDENTIAL URL IN THIS SAMPLE WILL BE COPIED FROM APPSETTINGS.JSON",
//Recommendation is to protect issuance payload with a PIN code.
//The pincode is set to a random value in code and will be displayed in the UI to the user
"pin": {
  "value": "123456",
  "length": 4
},
//This is an example payload which will be used in the rules file of the credential.
//The rules files maps information from the ID Token (hint) to the VC
"claims": {
  "country_of_registry": "",
  "registration_number": "",
},
//You can request multiple verifiable credentials at once that's whty the requestCredentials is an array
"requestedCredentials": [
  {
    "type": "VerifiedCredentialExpert",
    "purpose": "Required presentation of verifiable credentials expert to get Test Registration card.",
    //You can trust multiple issuers who might be issuing the same credential type (for example certifications or diplomas)
    //You need to specify at least 1 trusted issuer DID, for this sample code we copy the IssuerAuthority from appsettings to the request
    //"acceptedIssuers": [ "did:ion: copied from your VC portal in this sample the code copies it from APPSETTINGS.JSON" ]
    "acceptedIssuers": [ "theaccepetedidissuer" ]
  }

]
</code>
}
These are the display and rules:
Display definition
<code>      {
    "locale": "en-US",
    "card": {
      "title": "Test Verified Credential",
      "issuedBy": "TheIssuer",
      "backgroundColor": "#000000",
      "textColor": "#ffffff",
      "logo": {
        "uri": "https://example.com/image.png",
        "description": "Test  Verified Credential"
      },
      "description": "Use this card to verify."
    },
    "consent": {
      "title": "Do you want to get your Test Verified Credential?",
      "instructions": "Sign in with your Verified Credential Expert Card to get your card."
    },
    "claims": [
      {
        "claim": "$.vc.country_of_registry",
        "label": "Country of Registry",
        "type": "String"
      },
      {
        "claim": "$.vc.registration_number",
        "label": "Registration Number",
        "type": "String"
      }
    ]
  }
</code>
Rules definition:
<code>{
  "attestations": {
    "presentations": [
      {
        "mapping": [
          {
            "outputClaim": "firstName",
            "required": true,
            "inputClaim": "$.vc.credentialSubject.given_name",
            "indexed": false
          },
          {
            "outputClaim": "lastName",
            "required": true,
            "inputClaim": "$.vc.credentialSubject.family_name",
            "indexed": false
          }
        ],
        "required": true,
        "credentialType": "VerifiedCredentialExpert",
        "contracts": [
          "https://verifiedid.did.msidentity.com/v1.0/tenants/id/verifiableCredentials/contracts/abcd/manifest"
        ],
        "trustedIssuers": [
          "did:ion:thedid"
        ]
      }
    ],
    "idTokenHints": [
      {
        "mapping": [
          {
            "outputClaim": "countryOfRegistry",
            "required": true,
            "inputClaim": "$.country_of_registry",
            "indexed": false
          },
          {
            "outputClaim": "registrationNumber",
            "required": true,
            "inputClaim": "$.registration_number",
            "indexed": true
          }
        ],
        "required": true
      }
    ]
  },
  "validityInterval": 2592000,
  "vc": {
    "type": [
      "VerifiedTestRegistration"
    ]
  }
}

</code>
I am testing on iphone12 pro latest iOS version installed.
Question as posted in this git project but unfortunately got no help.
Thank you for your help, Sergio
Answer: Sergio,
A few things that you should review on the sample:
On the rules file:

For the VC, you can remove the contract but leave the VCType

On the display file:
2. I also added the claims that were obtained from the VC in your case first_name and last_name.
After doing that, my sample worked via Postman directly working with the Request API, try to get that working first and then make it work in C#
One thing that I'm still investigating is that I didn't notice a presentation on the requested VC type being recorded. I believe it should have one, but I'm still following up with the team. Try it and let us know if it works
Comment: Thank you @Juan Camilo Ruiz, unfortunately my post is 3 months old and we moved on, unable to get back to this now.


plugin maxlength no ckeditor não funciona

Question: Preciso limitar a quantidade de caracteres no CKEditor.
Segui o passo a passo deste topico:
Limitar texto no CKEDITOR
Mas não deu certo. Abaixo as alterações feitas no meu codigo:

   <textarea id="desc" name="desc" data-maxlen="10" rows="7" cols="45"</textarea>

O ckeditor funciona, porem o plugin não.
Ps. tentei tambem add a pasta "maxlenght" dentro desta pasta plugin. Também não funcionou.
Algo errado na sua implementação?
Outra questão: como esse plugin funciona? ele não deixa passar os caracteres da quantidade escolhida? ou ele apresenta erro depois de enviar o formulario?
Desde ja agradeço.
Comment: Em vez de `data-maxlen="10"`, tenta `maxlength="10"`
Comment: Nenhum dos dois funcionam.
Answer: Você pode usar este código abaixo. Ele irá pegar o valor em maxlength e limitar a quantidade de caracteres no CKEditor.
Textarea:
<textarea name="editor1" maxlength="10" id="desc" rows="10" cols="80"></textarea>

Código:

Comment: Usei exatamente o seu codigo. Copiei e colei. Ele limita os caracteres, mas a pagina para de reconhecer o ckeditor.
Comment: Veja que na resposta a linha `CKEDITOR.replace('desc');` é apenas um exemplo para iniciar o CKeditor. Se vc já iniciou em algum lugar, não precisa colocar essa linha.
Comment: Retirei a linha,  obtive o mesmo resultado.
Comment: Acho que o jeito vai ser expandir o campo no banco de dados para text e não limitar... Pelo menos com o CKEditor eu ja protejo o input contra invasões. (certo?)
Comment: Veja o teste que fiz funcionando: http://dvdteste.hospedagemdesites.ws/ckeditor/teste.html
Comment: Estou usando o ckeditor 4
Comment: Na linha ''CKEDITOR.instances.desc.on('key',function(event){" um parentese esta sendo aberto, e fechado so ao fim do codigo. Isso esta correto?
Comment: : não. parentese. Era esse o erro. O codigo está assim: "CKEDITOR.instances.desc.on('key',function(event){". Deveria estar assim: "CKEDITOR.instances.desc.on('key'),function(event){".
Comment: Mas resolveu o meu problema. Agradeço muito


NGINX url rewrite to rest endpoints on a different port

Question: I want to do a url rewrite to redirect all request with /api to a different port.
I want to redirect all /api request to this http://localhost:8081/api
I tried to create a rewrite rule like this but it returns a 404:
location /api {
    rewrite           ^/api/(.*) /$1 break;
    proxy_pass        http://localhost:8081/api;
}

Edit: It tried to update using the suggestion from the comment using this curl
curl -i GET "http://localhost/api/healthcheck/check" -H "accept: */*"

With the following response:
curl: (6) Could not resolve host: GET
HTTP/1.1 502 Bad Gateway
Server: nginx/1.14.0 (Ubuntu)
Date: Mon, 10 Aug 2020 23:56:17 GMT
Content-Type: text/html
Content-Length: 182
Connection: keep-alive

Heres my whole comfig
server {
access_log /var/log/nginx/access_log.log;
error_log  /var/log/nginx/error_log.log;
listen        80;
server_name   ui.buildanalyzer.io;
location / {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection 'upgrade';
    proxy_set_header   Host $host;
    proxy_cache_bypass $http_upgrade;
}
  location /api {
       proxy_pass http://localhost:8081/api;
  }

}

Comment: Your code removes the `/api` from the original request, so a request to `http://example.com/api` is sent to `http://localhost:8081/`. If you need to keep the `/api` part, remove the `rewrite...break` statement.
Comment: its returning 404. unable to resolve GET when trying to do a curl request. port 80 is serving a vue application and the redirect should serve json
Comment: got an error method not allowed
Comment: Please add output of `nginx -T` in your question. Please also add exact commands and output of the commands what you are using to test.
Comment: Updated the question
Comment: You should remove the stray `GET` from the `curl` command. It does nothing here except throw an error, since there is no such host.
Comment: Im getting a bad getway
Answer: Finally make it work! Here is my configuration
location /api {
    proxy_pass http://localhost:5021;
    proxy_http_version 1.1;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    proxy_set_header   X-Forwarded-Proto $scheme;
}

I can call all GET endpoints but the problem is i cannot make all POST work. I also achieved to display the endpoint documentation using almost identical configuration.


Filter for all terms in a "dynamic vocabulary"

Question: I would like to add a filter in a view to search only nodes related to terms in a specific vocabulary. The problem is that the editors continuously add terms to the vocabulary and consequently I cannot select once and for ever which are the possible terms.
I would need a filter like this:
positive if the term searched, or its translation, is in the vocabulary "myVocabulary".
Answer: I believe contextual filters under the advanced options in your view is what you are looking for. You can add the term reference field there and then dynamically filter the view from the url with either the term name or term id or both depending on the options you select.
Comment: I have not the term, id or name, in the url.
I need that to make a search page with exposed filters.
Comment: If you expose the filter and not select any terms by default it will display them all.
Views Admin: http://cl.ly/image/1g0I1r0r0e0w
Output: http://cl.ly/image/1V3t1t3i1o2v


How does multicollinearity between some variables affect non-collinear ones?

Question: In a multiple regression model, i.e. $y \sim x_1 + x_2 + x_3$, where $x_1$ and $x_2$ are collinear (e.g. present high correlation around 0.8), it is well known that many problems arise regarding parameter estimation or hypothesis testing (on $x_1$ and $x_2$). But how does collinearity affect the third non-collinear variable, $x_3$?
Answer: (Assume a linear model, OLS.)
Multicollinearity has its bad effects through the variance inflation factor (VIF), which is calculated by using all but one of the regression features to predict the remaining regression feature. That regression has its $R^2$ calculated, and then $\frac{1}{1-R^2}$ is the VIF.
If that remaining variable is independent of the others, then that $R^2=0$, and the $VIF=1$. Thus, the multicollinearity does not cross-contaminate the standard error for the coefficient of that independent variable.


Experienced mathematicians simplifying messy algebra

Question: $$\frac{pa}{n}\left(p\frac{a-1}{N-1}+q\frac{b+1}{N+1}\right)+p\left(1-\frac{a}{N}\right)\left(\frac{pa}{N-1}+\frac{qb}{N+1}\right)+\frac{qb}{N}\left(p\frac{a+1}{N+1}+q\frac{b-1}{N-1}\right)+q\left(1-\frac{b}{N}\right)\left(\frac{pa}{N+1}+\frac{qb}{N-1}\right)=\frac{(p+q)(pa+qb)}{N}$$
The ways people with different experience in math simplify algebra ranges massively. It is something assumed trivial, so any techniques or tricks in doing so are only found by finding them yourself. Any googling will land you at an elementary school homepage.
As a first year, my attempt at the above simplification was to set denominators equal, which made for two pages of tedious workings. I would be very interested in hearing how people with more experience in math than myself would approach this simplification, or other daunting simplifications in general.
To prevent this question being too broad, I also asked my professor what he would do, he suggested that I "factorise groups of terms which had obvious common factors". The meaning of these words independently is obvious, but could somebody explain the better approach he is alluding to, as I can only see approaches equivalent to matching denominators?
Comment: Use a tool like Macsyma, Maple, etc?
Comment: copper.hat said it, but has to be repeated: use software. I wouldn't trust myself that much to do it by hand.
Comment: "Simplifying" is largely preference and as you put it, tediousness... unless you have an idea of how it should look. If you know the answer ahead of time, it is easier.
Comment: @copper.hat How do these compare to WA? Mathematica and WA did not take too kindly to the large number of variables/large expression in general. Are the ones mentioned more tuned for this task?
Comment: @Jensen: Sorry, I don't really have a useful comparative experience, but I don't think the above should be a challenge?
Answer: I'm not sure there's all that many tricks.  What I would do, however, is simply get rid of the denominators by multiplying the whole shebang by $N(N- 1)(N + 1)$.
Answer: Looking for patterns, and careful use of variable substitutions, can help.
For instance, the LHS has the obvious common denominator $N(N-1)(N+1)$.  We can then let $x = N-1$ and $y = N+1$.  Also, note that $a$ and $b$ never appear alone, but always multiplied by $p$ and $q$, respectively.  This suggests letting $c = pa$ and $d = qb$.  We then obtain as the LHS numerator
$$c((c-p)y + (d+q)x) + (Np-c)(cy+dx) + d((c+p)x + (d-q)y) + (Nq-d)(cx + dy).$$  Multiplying everything out results in cancellations:
$$(\color{red}{c^2 y} - cpy + \color{blue}{cdx} + cqx) + (Ncpy + Ndpx - \color{red}{c^2 y} - \color{blue}{cdx}) + (\color{blue}{cdx} + dpx + \color{green}{d^2 y} - dqy) + (Ncqx + Ndqy - \color{blue}{cdx} - \color{green}{d^2 y}). $$  Then factoring the remaining terms yields
$$\begin{align}
(N-1)cpy &+ (N+1)dpx + (N-1)dqy + (N+1)cqx  \\
&= cpxy + dpxy + dqxy + cqxy \\
&= xy(c+d)(p+q) \\
&= (N-1)(N+1)(pa + qb)(p + q)
\end{align}$$
and the result follows.

I think a common theme when dealing with reasonably symmetric expressions like these is to take sub-expressions that occur more than once, assign a variable to these, and break the simplification task into smaller parts.  Of course, when the expression is not symmetric, or doesn't have "nice" features, it becomes much more tedious to simplify, and there is no real trick to it other than to go through it mechanically.  But if you're taking pages of work to simplify this one, I would say that you're not doing it efficiently.
Answer: $$\frac{pa}{N}\left(p\frac{a-1}{N-1}+q\frac{b+1}{N+1}\right)+p\left(1-\frac{a}{N}\right)\left(\frac{pa}{N-1}+\frac{qb}{N+1}\right)+\frac{qb}{N}\left(p\frac{a+1}{N+1}+q\frac{b-1}{N-1}\right)+q\left(1-\frac{b}{N}\right)\left(\frac{pa}{N+1}+\frac{qb}{N-1}\right)= \\
\frac{pa}{N}\left(\frac{pa}{N-1} -\frac{p}{N-1}+\frac{qb}{N+1} + \frac{q}{N+1}\right)+\left(p-\frac{pa}{N}\right)\left(\frac{pa}{N-1}+\frac{qb}{N+1}\right)+\frac{qb}{N}\left(\frac{pa}{N+1}+\frac{p}{N+1}+\frac{qb}{N-1} - \frac{q}{N-1}\right)+\left(q-\frac{qb}{N}\right)\left(\frac{pa}{N+1}+\frac{qb}{N-1}\right)$$
So what I did so far: I just broke the terms with $a+1,a-1,b+1,b-1$ in two parts,one with the letter and one with the $1$. Note that this way i can simplify the minus terms in the second and fourth parentheses with those in the first and third respectively. Which gives:
$$   \frac{pa}{N}\left(-\frac{p}{N-1}+ \frac{q}{N+1}\right)+p\left(\frac{pa}{N-1}+\frac{qb}{N+1}\right)+\frac{qb}{N}\left(+\frac{p}{N+1}- \frac{q}{N-1}\right)+q\left(\frac{pa}{N+1}+\frac{qb}{N-1}\right)$$
Now, I would like to have $\frac{1}{N}$ outside so:
$$   \frac{1}{N}\left[pa\left(-\frac{p}{N-1}+ \frac{q}{N+1}\right)+pN\left(\frac{pa}{N-1}+\frac{qb}{N+1}\right)+qb\left(+\frac{p}{N+1}- \frac{q}{N-1}\right)+qN\left(\frac{pa}{N+1}+\frac{qb}{N-1}\right)\right]$$
Now if you observe carefully you may see that the $N-1,N+1$ will go away but to make it more clear:
$$ \frac{1}{N}\left[pa\left(-\frac{p}{N-1}\right)+ pa\left(\frac{q}{N+1}\right)+pN\left(\frac{pa}{N-1}\right) +pN\left(\frac{qb}{N+1}\right)+qb\left(+\frac{p}{N+1}\right)- qb\left(\frac{q}{N-1}\right)+qN\left(\frac{pa}{N+1}\right)+qN\left(\frac{qb}{N-1}\right)\right]$$
Now pair the first term with the third and we get $p^2a$, the second with the seventh and we get $qpa$, the fourth with the fifth and we get $qpb$ and
the sixth with the eighth and we get $q^2b$. Putting it all together:
$$\frac{1}{N}(p^2a + qpa + qpb + q^2b) = \\
 \frac{1}{N}[pa(p + q) + qb(p + q)] = \\
\frac{(pa+qb)(p + q)}{N}$$


Clear all sort fields VBA

Question: I am trying to sort data through excel VBA but it is already sorted by a different header.  How would I clear all the sort fields before I set the new one? I have tried Sort.SortFields.Clear but it hasn't worked. Any help would be greatly appreciated. Here's the code I'm using:
 Sheet9.Activate

Columns("J:J").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(1, "J").Value = "InternalID"
Set rng2 = FindHeader("CLIENT NAME", Sheet9.Name)

Count = 1

Sheet9.Cells.Select

With Sheet9.Sort
        .SortFields.Clear
        .SortFields.Add Key:=rng2, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

Comment: Are you sure they aren't cleared? They aren't a filter so the values won't go back to their old position, but the sort fields will be clear.
Comment: Maybe you are using a filter too? In that case you might want to use .ShowAllData in such way: Sheet9.ShowAllData.
Comment: Ok. It is clearing them. But it gives me a sort reference not valid error when I try to apply it. I have updated the question with all the code I am using.
Comment: You're missing a `.SetRange` call.
Comment: maybe the [MSDN Documentation](https://learn.microsoft.com/en-us/office/vba/api/excel.sortfields.add) can help?
Answer: ActiveSheet.Range("Your_Range_Value").AutoFilter Field:=1

I did this for every column that has a sort field and it clears them out. Where Field:=X is the column number in your range that you want to clear.
This is what I have in my Workbook. Sheet1 is code name of sheet, and rng is string representing the range value ("B4:G1500")
' Clear all filters
Sheet1.Range(rng).AutoFilter Field:=1
Sheet1.Range(rng).AutoFilter Field:=2
Sheet1.Range(rng).AutoFilter Field:=3
Sheet1.Range(rng).AutoFilter Field:=4
Sheet1.Range(rng).AutoFilter Field:=5
Sheet1.Range(rng).AutoFilter Field:=6

Clear all sort fields VBA


Which of these sports requires a definite winner and loser?

Question: From what I can see, the following sports require that there has to be a winner/loser (draws aren't possible due to some continuation rule that leads to a winning result):

Basketball
Baseball
American Football
Tennis
Cricket
Darts

Can some who's more familiar with any of these sports confirm or correct this impression?
Comment: American football has ties even though you don't see them often. Also just because there is an overtime or multiple games doesn't mean their can't be ties or draws.
Comment: @JoeW Thanks - of all of my list, American Football I was the most doubtful of. When I say 'best of 3' I'm thinking of the likes of tennis whereby it's the first to a certain number of sets which would be played out one a particular night and is considered on stage (like a semi-final of a competition) as opposed to something like a series in in the NBA finals where each would be considered a game in their own right (if that makes sense?) On any given night you were to go to a basketball game for example, there will always be a winner/loser - right?
Comment: There is no difference between a best of 3 in table tennis and basketball. In both cases if the current game won't end because of the score it does not matter how many more games there are in the series.
Comment: I would also point out that the reason you don't see ties in baseball and basketball is that for some reason the American sports fan hates ties.
Comment: @JoeW I get that, but that would mean that each individual game has to have a winner/loser outcome - to put it another way, in a 5-game series that goes down to the last game it'll be because they're both won 2 games each rather then 1 game each and 2 drawn games (or 4 drawn games)
Comment: Well to be fair in most sports where you are talking about a multi game series it is normally during a tournament which generally throws ties out and play until there is a winner
Comment: @JoeW Ok, in the example of basketball, has there ever been a drawn game? is it even possible?
Comment: I've taken out the second half of this question asking for a list of more sports, as I feel the list is just too big: off the top of my head, I can already think of volleyball, table tennis, handball, squash, badminton, ... Answering about the six sports listed in the question seems on-topic though.
Comment: Of course there has been. What you are forgetting is that there are many different rule sets for basketball depending on the competitive level and league.
Comment: Folks: please answer in answers, not in comments. If you have an answer, even a partial one, it's better as an answer rather than in an already overcrowded comment thread.
Answer: Barring force majeure (police emergencies, building unsafe, etc) of your list:

Basketball: always has a result. As many overtime periods as necessary are played, at least under NBA and FIBA rules.
Baseball: just about always has a result. As many extra innings as necessary are played - the only exception in MLB is if weather interrupts a game at the end of the season with no playoff implications in which case they may never finish the game.
American football: NFL regular season matches have only one 15 minute sort-of sudden death overtime period. NFL playoff matches continue indefinitely.
Tennis: always has a result, via a tie-breaker in most tournaments, but three of the four Grand Slams play "2 games clear" in the final set; in the most extreme case, 138 games were played in the final set.
Cricket: Limited overs can result in a tie (or a no result if an insufficient number of overs are bowled); the tie is sometimes broken via a "super over", but not in all cases. Timed matches can result in either a draw or a tie.
Darts - I think always has a result, but I'm not that au fait with the various competitions.
Comment: WBSC rules allow for a tie when the game is called by the umpire and it is a regulation game (rule 7.01.a). A tied game remains a draw under these circumstances, unless a result is otherwise required for competition purposes.
Comment: MLB Baseball also allows ties for All-Star games, admittedly a special circumstance though.


Domain name resolution not working over VPN to Windows 2003 domain, VPN is on a different subnet

Question: I am able to browse shares and, sometimes, connect my outlook to the exchange server when connected over VPN to my office's LAN. However I am aware my VPN address is in a completely different subnet to that the server is on. (my server is something like 192.168.0.1 whereas my VPN is 5.*)
The problem is exchange and accessing shares can be slow typically at first and exchange often drops out - I think because more needs to be configured on the Windows server 2003 box for domain lookups?
EDIT: I see someone tried to close this question?! Let me rephrase:
How should one configure the DNS lookupzones to allow quick resolution of my local domain from a different subnet?
Answer: A VPN connection is probably going through a WAN with higher latencies and lower throughput, so a performance hit is expected when browsing shares.
It does not matter (much) if your VPN client gets an address from a different subnet when connecting. If you are able to browse shares and connect to Exchange, you probably have set up DNS correctly, but you could double-check by trying to resolve some domain-internal DNS RRs at your VPN client as described in the documentation:
<code>nslookup
[...]
> set q=srv
> _ldap._tcp.dc._msdcs.your-ad-domain.local
</code>
If it resolves to your domain controller(s), everything is fine. If not, it obviously belongs changed. How to set up a DNS server for a VPN client depends on your VPN implementation. If you could add the details to your question, someone is likely to give you some advice.
If you are using Windows RAS (e.g. PPTP VPNs terminated at your Windows Server), you would need to add the DNS server information for your AD as the first entry in the RRAS DNS Service search order configuration. The resolution of short names will not work with this configuration, though - it does not support the assignment of domain search lists, so you will have to use FQDNs for name resolution.
Comment: Thanks, the nslookup does not succeed! (I knew something was wrong).. It seemed to just query my Internet DNS.. My VPN connection has a gateway of 18.104.22.168 and does not have any DNS...
Comment: This is likely to be your main problem then. I've posted some additional information on this topic to my answer article - feel free to provide further configuration information.
Answer: I had to manually enter a DNS on the VPN connection then move the VPN connection priority to the top so it was queried before my other connected interfaces:

NOTE: For Hamachi follow this too: http://logmeinwiki.com/wiki/Hamachi:Microsoft_Exchange_Server_connection


Efficient method to find a unique value within a worksheet - preferably not VLOOKUP

Question: I have a sheet of 13000 rows of data, 10 columns wide. I need to find a unique value within column 2 and report on corresponding values from the row with the unique value.
I've tried VLOOKUP but since the data has gaps or data in some cells can be either numeric or text this method seems complex. I've tried a more basic find e.g Worksheets("IMPORT").Columns(2).Find("17013").Row but this seemed slow therefore I've used:
Set foundCell = Sheets("IMPORT").Range("A1").CurrentRegion.Find(What:="17013", LookIn:=xlValues, LookAt:=xlWhole)
Found_row = foundCell.Row

MsgBox Found_row

This seems a bit quicker. In this case I'm looking for 17013, and once I've found the row I can report on other data in the row to a userform. I find that after about 60 enquiries Excel seems to shut down so I was wondering is there is a more efficient method to search for a unique value?
Comment: I'm curious what did you mean by "unique" value ? From your code, it seems you want to find a certain value (the value is unique or not, only the user know). In the first code, you want to find a value within column 2.... in the second code, you want to find a value anywehre within A1.currentregion. Or did you mean (for example) in the rows of column 2, you have data something like this : `1,2,3,1,1,4,4,3,5,6,6,7,7` ---> from those data, you want a macro to give you a result : 2 and 5 because the other data are not unique but duplicate. Please CMIIW.
Comment: The unique value is from a series of bar codes from a list of 13000 products. No two bar codes are the same hence each search is for a unique number that resides in Column 2. The code is part of a stock management project, scan the bar code and present the user with associated stock info. The code as presented is part of a series of user forms.
Answer: Find in Column
Sub Test()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Sheets("IMPORT")
    Dim rg As Range: Set rg = ws.Range("A1").CurrentRegion
    Dim crg As Range: Set crg = rg.Columns(2)

    Dim rIndex: rIndex = Application.Match("17013", crg, 0)

    Dim fCell As Range

    If IsNumeric(rIndex) Then
        Set fCell = crg.Cells(rIndex)
        MsgBox "Found in cell " & fCell & ".", vbInformation
    Else
        MsgBox "Not found.", vbExclamation
    End If

End Sub

Answer: If you need to get the row number of the single and unique value inside a range use:
Public Function GET_ROW(ByVal searchRng As Range) As Long
'searchRng must be a single column range and must contain a SINGLE unique value
GET_ROW = Evaluate("=SUMPRODUCT(--(COUNTIF(" & searchRng.Address & "," & searchRng.Address & ")=1)*ROW(" & searchRng.Address & "))")
End Function

This UDF will work only if there's a single unique value in the range. If you got more than 1 it won't work as expected.
If you already know what the unique value is and you just need the row number use:
Public Function MATCH_ROW(ByVal searchRng As Range, ByVal searchValue As Long) As Long
'searchrng must be a single column range

With Application.WorksheetFunction
    MATCH_ROW = .Match(searchValue, searchRng.EntireColumn, 0)
End With
End Function

Notice in both cases searchRng is a single column range and searchValue is numeric. If you are searching for strings, change this part.


Microeconomics (quasi-linear utility function)

Question: Suppose that Sally's preferences over baskets containing food (good x), and clothing (good y), are described by the utility function
$U(x,y)=\sqrt{x}+y$.
Sally's corresponding marginal utilities are,
$U^\prime_x=\frac{1}{2\sqrt{x}}$   and    $U^\prime_y=1$.
Use Px to represent the price of food, Py to represent the price of clothing, and I to represent Sally's income.

Question 1: Find Sally's food demand function, and Sally's clothing demand function.
    For the purposes of this question you should assume that I/Py greater than or equal  Py/4Px.

Clothing demand function : y= I/py - Py/4Px
Food demand function : x = P^2y/4P^2x
After deriving demand function for both Clothing and Food, the following  question confused me.

Question 3: Now assume that I/Py less than Py/4Px. Find Sally's food demand function, and
  Sally's clothing demand function.

How do i get about doing this following question and getting the NEW Demand function for Food and Clothing?
I do know it might  possible be a corner solution.. But how do i explain it in terms of the function as i am not given the price of food and price of clothing in numerical form?
Answer: This problem is a case of optimisation under inequality constraints, where the requirement $x,y \ge 0$ is not stated explicitly. Here is an answer in the language used for your question.
The demand functions are $x^*(p_x,p_y;I) = \dfrac{I}{p_x}$ and $y^*(p_x,p_y;I) = 0$.
Here is a proof. By the rule of weighted marginal utilities, at the margin it is better to purchase $x$ than $y$ whenever
$$\frac{U^\prime_x}{p_x} \ge \frac{U^\prime_y}{p_y}$$
Substituting for $U^\prime_x$ and $U^\prime_y$ yields
$$\frac{1}{2 \sqrt{x^*}}\frac{1}{p_x} \ge \frac{1}{p_y}$$
Replacing $x^* = I/p_x$, we get
$$\frac{1}{2 \sqrt{Ip_x}} \ge \frac{1}{p_y}$$
Rearranging, this is precisely the condition $4IP_x \le p_y^2$. When this latter holds, it is always better to purchase $x$ rather than $y$.
Comment: Thanks for the above explanation. I do understand what you meant. But for Question 3, it ask to find Sally's Food Demand Function and Sally's clothing demand function if we assume that now is I/Py < Py/4Px

Wouldn't good y(Clothing) be Zero? How do i show it in a demand function of good y(Clothing)


Custom tabs design with Swipeable Views

Question: I've followed a tutorial on how to create tabs that you can swipe between using fragments, but now as I'm done with the tutorial I need to implement a custom design on the tabs. Can I do that because that is not explained in the tutorial.
*This is the tutorial I followed
Answer: Create custom tab's layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tabsLayout" android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dip" android:gravity="center" android:orientation="vertical">

    <TextView android:id="@+id/tabsText" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="Title"
        android:textSize="15dip" />
</LinearLayout>

Customize the look and feel of the view
tabs_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tabsLayout" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@drawable/tab_bg_selector"
    android:padding="10dip" android:gravity="center" android:orientation="vertical">

    <TextView android:id="@+id/tabsText" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="Title"
        android:textSize="15dip" android:textColor="@drawable/tab_text_selector" />
</LinearLayout>

similarly set text and background selector.use it as your new layout
you can reference this for more details.
Answer: create xml(tab1) in drawble folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/videos_gray"
  android:state_selected="true" />

<item android:drawable="@drawable/videos_white" />

and use that in java file
// Create an actionbar
ActionBar actionBar = getActionBar();

// Hide Actionbar Icon
actionBar.setDisplayShowHomeEnabled(false);

// Hide Actionbar Title
actionBar.setDisplayShowTitleEnabled(false);

// Create Actionbar Tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

// Create first Tab
tab = actionBar.newTab().setTabListener(new FragmentTab1());
// Create your own custom icon
tab.setIcon(R.drawable.tab1);
actionBar.addTab(tab);

// Create Second Tab
tab = actionBar.newTab().setTabListener(new FragmentTab2());
// Set Tab Title
tab.setText("Tab2");
actionBar.addTab(tab);

// Create Third Tab
tab = actionBar.newTab().setTabListener(new FragmentTab3());
// Set Tab Title
tab.setText("Tab3");
actionBar.addTab(tab);

Custom tabs design with Swipeable Views


Typing array item in TS

Question: Do I need to define array items type in loop functions (map/filter/find/...)?
For example, I have an array:
const arr: { lastName: string, age: number }[]

Pushing 2 items:
arr.push({firstName: 'Messi', age: 35})
arr.push({firstName: 'Ronaldo', age: 37})

Now, I want to iterate over this array using map:
const result = arr.map(player => "My last name is: " player.lastName)

Do I need to define player's type even though the array is defined?
For example:
const result = arr.map(player: { lastName: string, age: number } => "My last name is: " player.lastName)

Comment: No that is not needed. Typescript (and your IDE) is able to infer the type from the `arr` type when mapping over it.
Answer: No. Typescript can infer type of player. You can read this official doc: https://www.typescriptlang.org/docs/handbook/type-inference.html

Typing array item in TS


drupal_view or views_embed_view doesn't show translated content

Question: I have a block view on a multi-language website. Rendering Language is set to Content language selected for page and the translated content is displayed correctly in the admin page.
I embed this view like {{ drupal_view('ipa_projects_map') }} inside twig but at that page the content in original language is displayed, ignoring the content language selected for page setting.
Any ideas why?
PS: drupal_view is provided by "Twig Tweak" module and utilizes views_embed_view
Comment: `twig tweak` seems to support translatable content as per this issue https://www.drupal.org/node/2833546 ... Can you tell us how you setup `admin/config/regional/language/detection` ?
Comment: Language is detected by url, `/en` for english and `/tr` for turkish.
Answer: I found the problem. The view is configured to be a "block" and the "rendering language" setting belongs to the "block" definition I guess. So I added the block id and now it renders in the correct language:
{{ drupal_view('ipa_projects_map', 'block_1') }}


How to get button itself in action closure with SwiftUI?

Question: Is possible to get button itself in action closure with SwiftUI ?
struct ContentView: View {
    var body: some View {
        Button("test") {
            // change the color of button when user is tapping on it
        }
    }
}

Answer: If you want to access the properties of your button you can create a custom ButtonStyle.
Use its configuration to set the desired behaviour.
struct CustomButtonStyle: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .frame(minWidth: 0, maxWidth: .infinity)
            .padding()
            .foregroundColor(.white)
            .background(LinearGradient(gradient: Gradient(colors: [.red, .orange]), startPoint: .leading, endPoint: .trailing))
            .cornerRadius(40)
            .scaleEffect(configuration.isPressed ? 0.9 : 1)
    }
}

The above example was taken from here: SwiftUI Tip: ButtonStyle and Animated Buttons
In your case you can adapt it to set a custom background:
.background(configuration.isPressed ? Color.red : Color.blue)

Answer: Here's how:
struct ContentView: View {
    @State var color = Color.red
    var body: some View {
        Button("test") {
            self.color = Color.green
        }.background(color)
    }
}

Answer: Ya... I just figure out by myself too
struct ContentView: View {
    @State var buttonColor: Color = Color.clear
    var body: some View {
        Button(action: {
            self.buttonColor = Color(red: Double.random(in: 0...1),
                                     green: Double.random(in: 0...1),
                                     blue: Double.random(in: 0...1))
        }, label: {
            Text("Button").background(buttonColor)
        })
    }
}


How call a block named Poll Recent from template?

Question: I need to call the block Poll-recent from template.  I have tried this code and not work for me.  I am working in Drupal 7.
<?php
$block = module_invoke('block', 'block_view','poll-recent');
print $block['content']; ?>

or
<?php
$block = module_invoke('poll', 'block_view','recent');
print $block['content']; ?>

What is my error?
Thanks for your help.
Answer: In D7, you will need:
$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);

In the case of recent poll:
<?php
  $block = module_invoke('poll', 'block_view', 'recent');
  print render($block['content']);
?>

Curiously, although defined in poll_block_info the delta is actually ignored in poll_block_view, perhaps as the poll module only provides a single block.
Answer: @cabita: Try adding in a fourth argument 'block_delta' and using the render function to print the output, as suggested in this detailed post on Drupal.org
Hope this helps :-)
Comment: I tried with $block = module_invoke('poll', 'block', 'view', 'recent'); and nothing.
Answer: Hope this work;
$block = module_invoke('poll', 'block_view','recent');
print render($block);


Class field theory for function fields and a curious statement

Question: Let $X_0$ be a smooth curve over a finite field $\mathbb{F}_q$, and let $X$ be the base-change to the algebraic closure. I read that, according to class field theory in function fields,
"the image of $\pi_1(X, a)$ in the abelianized locally compact Weil group of $X_0$ is canonically isomorphic to the divisor class group $Pic^0$ of divisors of degree zero, which are rational over $\mathbb{F}_q$"
(Source: Kiehl and Weissauer's book on the Weil conjectures. Deligne makes this assertion in Weil II.)
What is the justification for this? I thought "class field theory for function fields" would give an isomorphism of the abelianized absolute Galois group of the function field of $X_0$ and the group of idele classes of $X_0$. It's not obvious to me how this relates to the statement claimed.
Answer: There is a standard exact sequence $1 \to \pi_1(X,a) \to \pi_1(X_0,a) \to
Gal(\overline{\mathbb{F}}_q/\mathbb{F}_q) \to 1,$  given by covariant functoriality of $\pi_1$.
How can one think about $\pi_1(X_0,a)$?  Well, it is a quotient of the absolute Galois group of the function field $K(X_0)$ of $X_0$, and can be thought of as the
Galois group of the maximal Galois extension of $K(X_0)$ which is everywhere
unramified.  Thus $\pi_1(X_0,a)^{ab}$ is the Galois group of the maximal abelian extension of $K(X_0)$ which is everywhere unramified.
Class field theory gives a description of this everywhere unramified abelian extension in terms of class groups/ideles.  When you sort it out in this context, you will find that $\pi_1(X_0,a)^{ab}$ gets identified with the profinite completion of the $\mathbb{F}_q$-rational points of $Pic(X_0)$.    Concretely,
$Pic^0(X_0)(\mathbb F_q)$ is finite, and the degree map induces an exact sequence
$$0 \to Pic^0(X_0)(\mathbb F_q) \to Pic(X_0)(\mathbb F_q) \to \mathbb Z \to 0.$$
Taking profinite completions just replaces $\mathbb Z$ by $\hat{\mathbb Z}$.
Now going back to the exact sequence at the beginning of the answer, since
$Gal(\overline{\mathbb{F}}_q/\mathbb{F}_q)$ is abelian, there is an induced
sequence
$$\pi_1(X,a) \to \pi_1(X_0,a)^{ab} \to Gal(\overline{\mathbb{F}}_q/\mathbb{F}_q)
\to 1.$$
Since $Gal(\overline{\mathbb{F}}_q/\mathbb{F}_q)$ is a copy of $\hat{\mathbb{Z}}$, generated by $Frob_q$, we may rewrite this as
$$\pi_1(X,a) \to \pi_1(X_0,a)^{ab} \to \hat{\mathbb Z} \to 0.$$
Now one checks that under the identification of $\pi_1(X_0,a)^{ab}$
and the profinite completion of $Pic(X_0)(\mathbb F_q)$, the map to
$\hat{\mathbb Z}$ of this last exact sequence is the same as the degree map.
Comparing exact sequences, we see that the image of $\pi_1(X,a)$ in
$\pi_1(X_0,a)^{ab}$ is equal to $Pic^0(X_0)(\mathbb{F}_q)$, which is what
is being asserted.
[Note: The reason that Weil groups are invoked are that, in this context,
passing from Galois groups to Weil groups simply replaces $\hat{\mathbb Z}$
by $\mathbb Z$.  So $\pi_1(X_0,a)^{ab}$ is a Galois group, while
$Pic(X_0)(\mathbb{F}_q)$ is the corresponding Weil group.  The latter has
a surjection to $\mathbb Z$, while the former has a surjection to
$\hat{\mathbb Z}$.  If you compute the quotient of the idele class group pertaining to the maximal abelian everywhere unramified extension, you will
naturally get $Pic(X_0)(\mathbb F_q)$, i.e. the Weil group.  In the function
field case the Artin reciprocity map from quotients of the idele class group
to abelian Galois groups is injective, with image being the Weil group.
By constrast, in the number field case the reciprocity map is surjective,
but has a kernel, coming from the contribution at the archimedean primes.
A careful discussion of Weil groups, including the distinction between
the number field and function field cases, can be found in Tate's Numer
theoretic background article in the Corvalis proceedings.]
Answer: In brief, a (local or global) Weil group intends to accommodate abelian extensions of all extensions of a (global or local) field, not "only" the abelian extensions of a fixed base. Thus, smashing it down to make an assertion about extensions of a given (global or local) field requires the intervention of suitable abelianization.
Talking about $Pic^0$ is just the algebraic geometry way of talking about a class group, with some rationality questions intervening. The $\pi_1(X,a)$ is the geometric 'absolute Galois group', so includes some things that wouldn't be rational over the fixed base.
In short, as in the question, indeed, the classfield theory over a fixed (e.g., global) base can be formulated in terms of the idele class group of that base. The fancier assertion involving Weil group and $\pi_1$ and such is saying the same thing, but is obliged to mash things down, to drop/forget some things to make the same assertion.
The fact that Weil groups (or, Weil-Deligne, etc.) exist and behave reasonably is a fairly subtle fact about the simultaneous classfield theory of all extensions of a given base, and has content. However, that content adds little to the assertions about extensions of a fixed base.
"Class formations" and such axiomatize the cohomological formulation of classfield theory (wherein the reciprocity laws are cup products...), and give us "Weil groups", eventually.


Can't connect to EC2 instance in VPC (Amazon AWS)

Question: I've taken the following steps:

Created a VPC (with a single public subnet)
Added an EC2 instance to the VPC
Allocated an elastic IP
Associated the elastic IP with the instance
Created a security group and assigned it to the instance
Modified the security rules to allow inbound ICMP echo and TCP on port 22

I've done all this and I still can't ping or ssh into the instance.  If I follow the same steps minus the VPC bits I am able to set this up without issue.  What step am I missing?
Comment: Did you assign a gateway and a route to the VPC subnet?
Comment: yes, you need to assign an "internet gateway" to the public routing table.
Comment: Excellent, thanks man.  If you put it in the form of an answer I'll accept it.  In your answer, could you also specify what exactly to put into the routes table?  I put in 0.0.0.0/0 and the target as the internet gateway, but that doesn't sound like the right thing to do.
Comment: If I go to Internet Gateways, there is a gateway assigned to the VPC.  How do I check if a route has been assigned?
Comment: Is route a route table?
Comment: That's exactly the thing you need to do. Amazon tried to simplify the config recently with some sane(?) defaults, but it is very easy to mess it up. I've had similar issues with VPC and public networks before.
Comment: When you create a public subnet and launch an instance in that public subnet, the public subnet needs to have a route table which will route the traffic to the internet gateway back and forth. Did you also add the ACL? if you did then make sure it is attached to your VPC and you have allowed all the connections which you need to ssh into your linux EC2. I am very new to AWS but according to my knowledge on it this should help you a bit, if I am wrong please correct me.
Answer: To communicate outside of the VPC, each non-default subnet needs a routing table and an internet gateway associated to it (the default subnets get an external gateway and a routing table by default).
Depending on the way you have created public subnet in the VPC, you might need to explicitly add them additionally. Your VPC setup sounds like it matches Scenario 1 - a private cloud (VPC) with a single public subnet, and an Internet gateway to enable communication over the Internet from the AWS VPC documentation.
You will need to add an internet gateway to your VPC and inside the Public subnet's routing table assign 0.0.0.0/0 (default route) to go to the assigned internet gateway. There is a nice illustration of the exact network topology inside the documentation.
Also, for more information, you can check the VPC Internet Gateway AWS documentation. Unfortunately it's a little messy and a non-obvious gotcha.
For more details about connection issues, see also: Troubleshooting Connecting to Your Instance.
Comment: VPC management > Route Table > [Routes] > Add , 0.0.0.0/0, dropdown to pick your internet gateway
Comment: In addition to assigning the default route for the internet gateway I also had to associate the subnet with the routing table. But once I had done these two things I was up and running. Thanks.
Comment: I will throw this out there for the internet to learn from my mistake. If your route to the Internet Gateway has destination 0.0.0.0/32 then it will not work. The route needs to be changed to 0.0.0.0/0 as specified in Zorlem's answer.
Answer: Not sure if this is exactly this case but I just created a VPC with Public and Private Subnets and noticed that there is a default security group that has the source address as the same security group name. Effective it has no access. Had to change this source to Anywhere and it started working.
Comment: Hello,
I'm testing that Scenario 2 too. Public and private instance in public and private subnet. The point is i don't understand how the private instance could be able to access Internet and update software.
Comment: Thanks, this was my problem, I was assuming, that means all instances inside VPC had access
Answer: I've noticed that (I think) you need to be careful about which availability zone your instance is created in.  The SubNet, Network Interface and Instance need to be in the same availability zone otherwise there is no way to connect to a public IP for that instance.
I may be wrong - but I don't think so, this has cost me 12 hours of work to figure out.
Hope this helps someone else.
Comment: That's correct. Scenario 1, as mentioned in the answer, is where you create a `/16` VPC and then create a `/24` in each AZ you want to work in
Answer: You should allocate an ENI and assign the Elastic IP to this ENI. Also, you should assign this ENI to your VPC.
The route table must be correct too, to correctly forward the outside packets to your VPC.
Comment: I believe that adding an ENI is needed when you want additional network interfaces on your instances, by default they come with one NIC.
Answer: Since SSH is statefull protocol, you need to make sure that you have the following OUTBOUND rule in your network ACL:
Rule #  Type            Protocol        Port Range      Destination     Allow / Deny
100     Custom TCP Rule TCP (6)         49152-65535     0.0.0.0/0       ALLOW


Jquery Waypoints : Multiple functions not working

Question: I can only say that I testing waypoints and that as soon as I add a second function the first wont work anymore. Why is that?
<code>$(document).ready(function() {
$(".black").waypoint(function(){
    TweenMax.to(this, 2, {right:"0", ease:Power2.easeInOut})
},{offset:'50%'});

$(".white").waypoint(function(){
    TweenMax.to(this, 2, {left:"0", ease:Power2.easeInOut})
},{offset:'50%'});

});
</code>
Comment: Which version of jQuery Waypoints are you using?
Answer: Try the following. I would be curious if the log will show its called more than once but the TweenMax is not able to execute multiple times.
<code>$(document).ready(function() {
$(".black").waypoint(function(direction){
    console.log('BLACK');
    TweenMax.to(this, 2, {right:"0", ease:Power2.easeInOut})
},{offset:'50%'});

$(".white").waypoint(function(direction){
    console.log('WHITE');
    TweenMax.to(this, 2, {left:"0", ease:Power2.easeInOut})
},{offset:'50%'});

});
</code>


How to add ARRAYFORMULA to header cell in column above data cells?

Question: I am displaying formula ouput data in column J. The input for the calculation is data referenced in other columns. The working formula is as follows:
=ARRAYFORMULA(if(regexmatch(B2:B,"call"),100*(G2:G*D2:D),"")

Here is a screenshot of my columns:

The problem is I am running a script after the data is loaded that deletes rows with 0 in column J. Because the formula is in J2 the delete script deletes the 2nd row and then the formula along with it, so the cells in column J end up all being blank.
I think I need to add the formula to J1 -- the cell with "Calls" -- so that the formula isn't deleted with the row, but I can't figure out how to do this. How do I add the formula to J1 so that the formula ignores cell J1 and only executes on the cells below? Or where else do I put the formula so it is not deleted?
Comment: Rather than `ARRAYFORMULA()` use `BYROW()` or `MAP()`.
Answer: Use VSTACK() function.
=VSTACK("Calls",ARRAYFORMULA(if(regexmatch(B2:B,"call"),100*(G2:G*D2:D),""))

Put above formula to J1 cell.
Comment: Interesting. I've never heard of VSTACK before. Thanks for sharing.
Answer: Here's how I do it...
={"Calls";ARRAYFORMULA(if(regexmatch(B2:B,"call"),100*(G2:G*D2:D),"")}


Non-existence of moment generating function

Question: If moment generating function $E[e^{tX}]$ exists only for $t=0$, does it imply that every moment of $X$ does not exist(is not finite)?
Comment: 1. So how does the question arise? Is it work for some subject other than homework?  2. It's unclear why you keep referring to the Cauchy; to answer a question "does having attribute A imply B" you don't examine some examples of B and see if they have attribute A. You need to know there are no examples of *not*-B which have attribute A. The Cauchy is logically useless for answering the question you asked, it's an example for which the proposition is true, which doesn't help you figure out whether all cases are true; for that you need to show there are no counterexamples. But there are!
Comment: This is why my answer discusses the $t$ and the lognormal. Either is sufficient, since they're counterexamples to the proposition. If you want to prove no moments exist for the Cauchy, try it for the first moment (which is easy).  That implies all the others.
Comment: Is this work for some subject?  homework, for example? If not, how do you come to face such a question?
Comment: This is homework and if this would be true then I could prove that no moments of Cauchy distribution exist because its mgf doesn't exist.
Answer: No.
Consider a distribution whose first $k$ moments are finite (perhaps a $t_{k+1}$-distribution) but whose higher order moments aren't. Does its MGF exist in a neighborhood of 0? (See if you can show it)
Indeed, even if every moment exists, it can be that the MGF doesn't exist in a neighborhood of 0. The lognormal is a commonly given example.
Comment: @kjetil Wow, I could have sworn I saw a $(-\epsilon,\epsilon)$ in the question before I answered. Turns out it was another question I was looking at on the same day.
Comment: Well, but the OP said "exists only for $t=0$", not an open interval about zero. Are there counterexamples also for that case? There cannot be, because mgf *always* exist for $t=0$ (and is equal to 1 there). Not very useful, yes.
Answer: Again, let us use the lognormal as example. Let $X, Y$ be two iid lognormal variables. Let $D = X - Y$. Then all moments of $D$ exists (they can be calculated from the lognormal moments), but the mgf of $D$ only exists for $t=0$.
Some details here:  Difference of two i.i.d. lognormal random variables


HP ProLiant - Does ILO 2 Advanced offer additional SNMP or IPMI features?

Question: We've got ML350 G5 servers with iLO 2 standard license.
Does upgrading to higher iLO license will unlock new SNMP or IPMI data registers?
If it will, which ones?
Comment: This question appears to be off-topic because it is licensing-related, and would therefore be much better directed to HP.
Comment: possible duplicate of [Can you help me with my software licensing issue?](http://serverfault.com/questions/215405/can-you-help-me-with-my-software-licensing-issue)
Comment: I think you need to be running iLO2 firmware rev 2.0 or later for IPMI support. You can get 30 day trials of the iLO advance licence pack to try out. I've never worked with an iLO without the advance pack, so can't say if that's what has given us SNMP support or not.
Comment: @MadHatter
HP asks for a valid contract to answer those kind of questions.
It's why I'm asking here, hopping someone has experienced it before.
Answer:
Does upgrading to higher iLO license will unlock new SNMP or IPMI data registers ?

No.
ILO2 Advanced gives you additional remote media and console functionality. It also provides power measurement/management and directory support.
What are you trying to achieve via the ILO2 and SNMP?
For that era server (2006-2009), I would not bother with investing any additional money into the hardware.


creating map with dash getting syntax errors

Question: I am new to Dash and python, i am simply practicing an example which contains map graph, while executing the program i am getting syntax errors. can any one help me on this? ref: https://codepen.io/Dorkaitz/pen/QmooBK
the below one is my code :
<code>import plotly.plotly as py
import plotly.figure_factory as ff
import pandas as pd

Plotly.d3.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv',

 function(err, rows){
      function unpack(rows, key) {
          return rows.map(function(row) { return row[key]; });
      }

var scl = [[0,'rgb(5, 10, 172)'],[0.35,'rgb(40, 60, 190)'],[0.5,'rgb(70, 100, 245)'], [0.6,'rgb(90, 120, 245)'],[0.7,'rgb(106, 137, 247)'],[1,'rgb(220, 220, 220)']];

var data = [{
    type:'scattergeo',
    locationmode: 'USA-states',
    lon: unpack(rows, 'long'),
    lat: unpack(rows, 'lat'),
    hoverinfor:  unpack(rows, 'airport'),
    text:  unpack(rows, 'airport'),
    mode: 'markers',
    marker: {
      size: 8,
      opacity: 0.8,
      reversescale: true,
      autocolorscale: false,
      symbol: 'round',
      line: {
        width: 1,
        color: 'rgb(102,102,102)'
      },
      colorscale: scl,
      cmin: 0,
      color: unpack(rows, 'cnt'),
    }
}];

var layout = {
      colorbar: false,
      autoscale: 1,
      showgrid: 1,
      margin: {t: 0, l: 0, r: 0, b: 0},
      geo: {
        autoscale: 1,
        scope: "world",
        projection: {
          type: 'mercator',
        },
        lonaxis: { range: [-169, 191] },
        lataxis: { range: [-3, 90] },
        showframe: false,
        showlegend: false,
        showland: true,
        showocean: true,
        showscale: true,
        landcolor: 'rgb(62,71,80)',
        oceancolor: 'rgb(33,43,54)',
        subunitcolor: 'rgb(217,217,217)',
        countrycolor: 'rgb(217,217,217)',
        countrywidth: 0.5,
        subunitwidth: 0.5,
        fixedrange: true,
        scrollzoom: false
      }
    };

Plotly.plot(myDiv, data, layout, {scrollZoom: false});

  var geo = Plotly.plot;
  console.log(geo);

});
</code>
Answer: This code isnt python, var? ";"? not properly intended. Clearly you need more work before asking at SO


How should I analyze data with repeated measures variables and integer between-subject factors?

Question: I ran a study, where a single variable was measured repeatedly for each participant, under different conditions. Analyzing this data with SPSS has been rather straightforward, by using the General Linear Model -> Repeated Measures ANOVA, and specifying each measure in the within-subject factors.
My problem arises when I try to include some post-experiment data I collected, like a test that all participants completed after the experiment, with integral scores ranging from 0-24. I want to include this to see how these scores relate to the within-subjects measures, and adding this data as a between-subject factor makes sense, but due to the nature of the test score variable I have up to 25 categories that make the data impossible to work with.
It seems like this should be a common issue, and my Googling has helped me a bit, but most of the examples I have seen use categorical variables like gender for the between-subject factors. What do I do if the between-subject factor isn't categorical?
I will be very grateful for any insight, comments and tips you have. Thanks!
Comment: I'm thinking that your concern is that the scores are ordinal data instead of interval, is that right?
Comment: @gung I will admit that I sometimes have trouble discerning between ordinal, interval and discrete data. In this case the scores are integers ranging from 0 to 24, and represent the number of problems the participant answered correctly. For reference, the test is the MRT-A mental rotations test, described here: [link](http://wexler.free.fr/library/files/peters%20(1995)%20a%20redrawn%20vandenberg%20and%20kuse%20mental%20rotations%20test.%20different%20versions%20and%20factors%20that%20affect%20performance.pdf).
Answer: You could treat the test score as an interval between subjects predictor in a full model of that and the within effects.  You really should be doing multi-level modelling at this point and I'd strongly encourage you look at some tutorials on that for SPSS.
There is an alternative, that is not as good but might be simpler to understand.  Let's say your primary question is whether the repeated measures effect is dependent on (interacts with) a linear effect of the test score.  Calculate the repeated measures effect score for each participant and then perform a regression on the resulting effect scores.  In general, once you have each subject with a single score you're interested in then you could analyze the continuous test score predictor how you'd handle any continuous variable.
Comment: Converting it to another scale doesn't make it continuous.  That's actually kind of an absurd idea.  Then you'd just have intervals in a different scale. You have a variable that you can treat continuously as long as you don't take fractional scores as meaningful in discussion.  In practice no variables are continuous since there is always some limit to the ability to measure.  This is a relatively course continuous variable is all.
Comment: The scores might be converted when they're response variables because they're known not to be distributed normally and the arcsine fixes that.  But there's not requirement for normality as a predictor variable.
Comment: thanks for your comments. I felt that simply changing the scale was weird, but wasn't sure enough. The fact that I've seen some papers do it didn't help. I'm reading up on multi-level modelling right now.
Comment: Thank you for a helpful response.

As for using a continuous factor, I have seen some papers where the authors convert the integer scores in this test (MRT-A, referenced in a comment on the original post) to percentages (or an arcsine in one case) to make it continuous. But is that really enough?

I will also look into multi-level modelling, and thanks for bringing that up.
Answer: I would agree with John.  Another simpler approach might be to say four or five categories such as very poor [0,x1]  poor[x1,x2] average [x2,x3] good [x3,x4] and excellent [x4,24].  Known the test you should be able to pick reasonable break points.  I raise this idea because it just seems to me that the difference between a score 24 and 25 say probably does add much useful information regarding the relationships you are trying to look at,
Comment: I think that the argument at the end of your answer is problematic. You're not just throwing out small differences with broad categorizations of the test, you're potentially throwing out the pattern of the relationship between the test and the effect score (or whatever the questioner uses). There could be a curvilinear pattern that is quite dependent upon all those individual points to reveal adequately. I only used linear as an example. There are so many good options for dealing with non-linear these days that breaking it into categories is never a good idea.
Comment: Thanks. That thought did cross my mind, and I'm glad to see it wasn't too crazy. I'll have to comb the literature though, since I haven't seen any such categorization in any papers that use this particular test (MRT-A, referenced in a comment on the original post) yet.
Answer: To use MRT-A as a continuous variable, you should add it to the model as a covariate. Then from the button Model in SPSS, choose under specify model Custom, drag the within- and between-subjects to the corresponding Model.


Prove that the relation on $X$ given by $x\sim y$ if $f(x)=f(y)$ is an equivalence relation

Question: Let $f:X\to Y$ be a function between two sets. Prove that the relation on $X$ given by $x\sim y$ if $f(x)=f(y)$ is an equivalence relation.
I know that it should have $3$ cases, reflexive (for all $x$ in $X$, $f(x)=f(y)$), symmetric and transitive.
Comment: So, which of these three propertie(s) is (are) causing you trouble? (For the record, note that *every* equivalence relation can be represented as in your post.)
Comment: You are correct. A relation $\sim$ on a set $X$ is an equivalence relation if and only if it satisfies all three properties you mention, iff for all $x, y, z$ in $X$, the relation is reflexive, symmetric, and transitive. So you proceed in your proof to show that $\sim$, in fact, satisfies each of the properties. Once you've done that, you are done.
Comment: Note how this follows from the fact that equality is an equivalence relation. Note also that every equivalence relation relation arises in this way.
Comment: @did I was just unsure how to set this up, I get the concept but somehow i always have a trouble understanding what the question really wants me to do
Comment: Causing trouble, not the trouble. What I mean is that if you write down correctly the definition of, say, reflexivity and if you ask yourself whether the relation you defined in your post is reflexive or not, you should come pretty quickly to the conclusion that it is. If you did that, this should be mentioned in your post. If you did not, I wonder why.
Comment: @did since they want us to prove this as it is equivalence relation, then it has to be true, doesn't it?
Comment: ?? Is this truism related to my previous comment? (You still did not mention whether you had written down the definition of reflexivity and checked that this relation satisfies it, or not.)
Comment: @did I know the definition of equivalence relation, but I always have trouble figuring out what the question wants me to do. Like why is there x ~ y and f(x)=f(y), so i am unsure why there is x ~ y ... etc
Comment: Your trouble may be, either that you do not understand the definition of an equivalence relation, or that you do not understand the definition of the relation in your post. It is difficult to determine as long as you do not write down, yourself, fully, the definition of an equivalence relation (as suggested two comments ago). At present my feeling is that the answers to your question (while both being competently written, and one being accepted) might miss the point--because you did not say what the point is.
Answer: Reflexivity: Not much to do for this one.
Suppose $f(x) = a,$ then since $f(x) = f(x)$ for all $x \in X$, we have $$f(x) = f(x) \iff a \sim a.$$
Symmetric: Not much to do for this one either.
Suppose $f(x) = f(y)$ and let $f(x) = a$ and $f(y) = b$. Then $$f(x) = f(y) \iff f(y) = f(x).$$ Hence, $$a \sim b \iff b \sim a.$$
Transitive: This is still pretty straightforward, but a bit more involved.
Suppose $f(x) = f(y)$ and $f(y) = f(z)$, and let $a = f(x)$, $b = f(y)$, and $c = f(z)$.
Then $$f(x) = f(y) \implies a = b,$$ and $$f(y) = f(z) \implies b = c.$$
Therefore, $$f(x) = f(y) \textrm{ and } f(y) = f(z) \implies f(x) = f(z) \implies a = c.$$
Hence,
$$ a  \sim b \textrm{ and } b  \sim c \iff a  \sim c$$
Comment: Perhaps it is "trivial" to you, and/or "easy", but the OP wouldn't have asked the question if it were trivial to him/her. Please consider rephrasing your answer.
Comment: I added a bit more explanation and removed fighting words like "trivial" and "easy".
Comment: btw, Charles, to get the $\sim$ character, just use `\sim`. Your answer/formatting is fine...just a tip.
Comment: @CharlesBoyd one quick question where is x~y actually used? do you have to write it or not?
Comment: @amWhy Well, this is difficult to know until the OP decides to answer my comment.
Comment: @did I wasn't trying to start a debate. I just tend to give the benefit of the doubt, in terms of taking questions as *real* questions.
Comment: @CharlesBoyd thanks a lot, that helps me a lot
Comment: I claim that $f(x) \sim f(y) = a \sim b \iff x \sim y$. That is, you have the equivalence relation $a \sim b$ partitioning the image $f(X)$ into equivalence classes and hence the same equivalence relation partitoning the pre-image $X$ into equivalence classes. In other words, $f$ takes equivalence classes on $X$ to equivalence classes on $f(X)$.
Answer: Charles's answer is fine, but to say things a tiny bit differently.
Reflexive: You want to prove that $x\sim x$ for all $x\in X$. This is equivalent to proving that $f(x) = f(x)$ for all $x$ in $X$. But this is obviously true. So the relation is reflexive.
Symmetric: You want to prove that if $x\sim y$, then $y \sim x$. So assume that $x\sim y$. That means that $f(x) = f(y)$. But this is the same as saying that $f(y) = f(x)$ (since equality is symmetric). So we have $y\sim x$. So you have symmetric.
Transitive: You want to prove that if $x\sim y$ and $y\sim z$ then $x\sim z$. So assume the first two. Then you have $f(x) = f(y)$ and $f(y) = f(z)$. But this means that $f(x) = f(y) = f(z)$, or $f(x) = f(z)$. Hence by definition you have $x\sim z$. And you have transitivity.
In all you have proved that the relation is an equivalence relation.


Guitars playing in harmony

Question: I wonder if guitars playing in harmony is as simple as this:
Let's say you want to play a solo part in Am with the minor scale.
If you would play the 3 notes on each of the 3 highest strings (G, B and e):
e|-------------5-7-8|
B|-------5-6-8------|
G|-4-5-7------------|

That would be: B C D E F G A B C
Now, let's say I want to play a 5th above that in harmony, would that mean that every note is just 5 notes above in the scale being used, so being: F G A B C D E F G.
Resulting in such tab:
e|-------------------12-13-15|
B|----------12-13-15---------|
G|-10-12-14------------------|

Or could I just take the same patern as the original and move it up a few frets?
Additionally, I have a Digitech Whammy 5. If I choose to have a 4th above and enable the pedal, would that mean that it plays this solo part perfectly a 4th above, or does the pedal do something else?
Answer: It's nearly as simple as that. Nearly. But - harmony such as you illustrate here is made up from the notes of the scale, yes - but, everything does not move exactly parallel as I think you say. Let's take a 1-3-5, say in Cmaj. C-E (1-3) is a major third, which is 4 frets, and the 3-5 is a minor third, which is 3 frets. So the spacing is 4 frets then 3 frets. Move up to the second note of D. The chord made from this is usually Dmin. in key C. This is D-F-A, which has a different spacing from the C maj. chord. It's 3 frets, then 4 frets - the opposite way from the C maj.You'll notice that the 1st and 5th notes are spaced the same, at 7 frets, so they can go parallel.Until the last but one chord, where there's only 6 frets between the top and bottom note of the triad.Having said that, this chord is the least used in pop music - the m7b5.
This is why, if you just programmed a harmony unit to, say, thirds, it would be out of tune on half of them.It needs to be told which key you're playing in.Then it will compensate automatically.The clever ones that you plug your guitar into analyse the current chord, and sort out for you. For instance, in C, occasionally you'll use Dmaj. instead of Dm. On the earlier machines, they would still play an F, rather than the much needed F#.
Comment: If I understand what you're saying, I don't think it would work very well. To sound acceptable in harmony, thirds (both maj. and min.) will sound good.4ths and 5ths often have a 'hard' sound to them on their own. 6ths sound good - they're upside down thirds, so why wouldn't they - but 2nds and 7ths are close and can sound like "has someone missed the right note by a couple of frets?". The bottom line,as ever, is 'If it sounds good it probably is!'  Play it and listen.
Comment: Thanks for the answer! One addition small question:
If I were to create a solo in the key of Am that goes (randomized) C A B G G F A D. In theory to be in harmonic, I could just play any other solo over that with notes from the Am scale like for example (randomized) A F G D C C B A. Obviously, that wouldn't be a 5th above the whole time but kind of all mixed up together, but still in harmony?

Guitars playing in harmony


Drush - /usr/bin/drush: line 129: /usr/bin/php: Success

Question: When I run any drush command I am getting this line:
<code>/usr/bin/drush: line 129: /usr/bin/php: Success
</code>
For example:
<code>[root@061889 ~]# drush
/usr/bin/drush: line 129: /usr/bin/php: Success
[root@061889 ~]# drush cron
/usr/bin/drush: line 129: /usr/bin/php: Success
[root@061889 ~]# drush help
/usr/bin/drush: line 129: /usr/bin/php: Success
</code>
I've tried rebooting my VPS but am still getting the same issue. This has been discovered while trying to get past a "Attempting to re-run cron while it is already running" error, in case that has any relevance. But, you've guessed it...
<code>[root@061889 ~]# drush vdel cron_semaphore
/usr/bin/drush: line 129: /usr/bin/php: Success
</code>
Any ideas?
Comment: try running $ which drush, and hit the whole location -   something changed in your PHP?
Comment: Thanks for your help. `$ which drush` gives `/usr/bin/drush`. Tried running drush from /usr/bin but getting the same message. Nothing's changed in php. Dunno what you mean by 'hit the whole location', sorry (is this a linux command line term?! Comfortable in command line on Windows, new to Linux command line)
Answer: just run

$ /usr/bin/drush

if it runs it means that your symlink to the drush command is wrong
Comment: Hi, excuse the late reply and thanks for your help... Running `/usr/bin/drush` gives exactly the same message as in my question


How do I replace part of a webform component label with a variable token?

Question: I have webform component labels like this:
Did [your pet] have any illnesses?
and I want to replace [your pet] with a variable token?
Do I need to write a custom module or can I do this by editing one of the theme .tpl files?
Tried this code as suggested:
<code><?php

/*
 * Implementation of hook_form_alter()
 */

drupal_set_message(t('Outwith the hook'), 'warning'); // display outwith the hook

function wit_bootstrap_form_alter(&$form, &$form_state, $form_id) {

drupal_set_message(t('Inside the hook'), 'warning'); // display within the hook

 // target my form / my field
  if ($form_id == "webform_client_form_1") {
    // target my form / my field

    if ($form['neutered']['#title']) {
        $title = $form['neutered']['#title'];
        $token_val = 'freelo';//get_tokenised_value(); // Which ever way you handle that...
        $title = str_replace('[your pet]', $token_val, $title);
        $form['neutered']['#title'] = $title;
    }
  }
}
</code>
Answer: hook_form_alter() should allow you to so.
Within your theme you should be able to do something like :
<code>/*
 * Implementation of hook_form_alter()
 */
function my_theme_form_alter(&$form, &$form_state, $form_id){
  // target my form / my field
  if ($form_id == "my_form") {
    if ( $form['my_field']['#title'] ) {
      $title =  $form['my_field']['#title'];
      $token_val = get_tokenised_value(); // Which ever way you handle that...
      $title = str_replace('[your pet]', $token_val, $title);
      $form['my_field']['#title'] = $title;
    }
  }
}
</code>
Also check the forms api reference to see what things you can set / alter on forms.
Comment: Thanks for your help with this. We have done as you suggest but to no avail. Here is what we have, the form component is still unaltered. We can display a warning message outwith the hook but not within. Any help/advice you can offer would be very much appreciated:
Comment: Will send you the code, can't get it to format. new to this
Comment: Sure. Edit your question to add the code you've tried.
Comment: Ok, I've added a copy of our code, based on you r suggestions, to or original question


Find and add multiple objects scores to be closest to a given value with JavaScript

Question: I have an array of objects as:
[
  {
    score: 1,
  },
  {
    score: 2,
  },
  {
    score: 4,
  },
]

And I have a given value, a number.
e.g.: value is 6
My goal is to take objects so their score (added themself) to be closest to the value (here: 6)
My first step is to check if an object score is equal to the value.
If it's not the case, I have no idea how I can achieve this.
With the array above, for 6 I would need to pick the second and the third because it's the only combination where the added scores is equal to 6 (4 + 2)
But, imagine the third object's score is 3, I would need to pick the 3 objects to obtain 6.
Sometimes I cannot get the value so I just need to be the closest one.
I don't want You to create an algorithm but I need to know what path I should follow to achieve this efficiently because I have absolutely no idea how to achieve this.
Comment: Think of it as a binary problem. Each object is either in or out of the party. Besides that, you must at least be familiar with the concept of recursive programming. Are you?
Comment: do you have greater values or negative? do you only want to get the sum or the objects?
Comment: I know what is recursive function in JS, that's all.
Given value is > 0 and scores are >= 0.
Comment: Use recursion.

Basically start with a function call that checks the first score. If it's greater than or equal to the final score, then return that value. If it is less than the score, then call the function again, with the new score passed as an argument. If the next score plus the previous score is greater than or equal to the score, return the value. If not, keep going until the score is greater than or equal to the value.
Comment: Now, you also have to check what final score is closest, not necessarily which is greater (for example you could get 10 as the greater value, while the lesser value is 5, which is closer, so in that case, you would need to pick 5).
Comment: So to solve this you need to do the same thing, again, in reverse. Start with a function call (different function) to the first score value. If it is equal to or less than the final score value, return it. If it is greater than the final score, move on, and call the same function again, with the previous score as a parameter. If the new score plus the previous score just checked is less than or equal to the final value, then return it. If it is greater, then keep going until you have reached the end.
Comment: If you have reached the end and all of the values added are still greater, then just return the last value.

Now you have a total of 2 returned values, from these two different functions. Now you just have to compare the distance between each value to the final score, i.e., the absolute value. Say your score is 6, and one result is 8 and another is 4. So take a variable list distHigher and set it equal to 8 - 6, then make another variable, distLower, and set it equal to 6 - 4, then just determine which number is smaller, and that is your answer.
Answer: Use recursion.
Basically start with a function call that checks the first score. If it's greater than or equal to the final score, then return that value. If it is less than the score, then call the function again, with the new score passed as an argument. If the next score plus the previous score is greater than or equal to the score, return the value. If not, keep going until the score is greater than or equal to the value.
Now, you also have to check what final score is closest, not necessarily which is greater (for example you could get 10 as the greater value, while the lesser value is 5, which is closer, so in that case, you would need to pick 5).
So to solve this you need to do the same thing, again, in reverse. Start with a function call (different function) to the first score value. If it is equal to or less than the final score value, return it. If it is greater than the final score, move on, and call the same function again, with the previous score as a parameter. If the new score plus the previous score just checked is less than or equal to the final value, then return it. If it is greater, then keep going until you have reached the end. If you have reached the end and all of the values added are still greater, then just return the last value.
Now you have a total of 2 returned values, from these two different functions. Now you just have to compare the distance between each value to the final score, i.e., the absolute value. Say your score is 6, and one result is 8 and another is 4. So take a variable list distHigher and set it equal to 8 - 6, then make another variable, distLower, and set it equal to 6 - 4, then just determine which number is smaller, and that is your answer.


IPFW denies ssl connections

Question: I'm having an issues loading https websites (google, facebook, amazon) through my PHP scripts using functions like fsockopen, file_get_contents. Operation is being timed out. So I started looking through my system settings and noticed that when ipfw service is being stopped, it works like a charm.
So this is an issue definately related to my IPFW configuration. I have enabled logging and this pops out in the log file while trying to execute the PHP script:
ipfw: 1000 Deny ICMPv6:1.3 [2001:...:...:...::] [2001:...:2:...::] in via em0
ipfw: 1000 Deny ICMPv6:131.0 [...::...:...:...:...] [...::1:...:0] in via em0
ipfw: 1000 Deny ICMPv6:136.0 [2001:...:...:...:ff:ff:ff:ff] [...:...:2:...::] in via em0

Looks like an issue with the IPv6, though, I do allow all keep state-kind connections in my ipfw file.
Here is the configuration I'm currently using:
#!/usr/local/bin/bash

IPF="/sbin/ipfw -q add"

/sbin/ipfw -q -f flush

$IPF 10 allow all from any to any via lo0
$IPF 11 deny all from any to 127.0.0.0/8
$IPF 12 deny all from 127.0.0.0/8 to any
$IPF 13 deny tcp from any to any frag

$IPF 250 check-state
$IPF 260 allow tcp from any to any established
$IPF 270 allow all from any to any out keep-state
$IPF 280 allow icmp from any to any

$IPF 290 allow log tcp from 127.0.0.1/32 to 127.0.0.1/32 3306 in

$IPF 350 allow udp from any to any 53 in
$IPF 351 allow tcp from any to any 53 out
$IPF 352 allow tcp from any to any 80 in
$IPF 353 allow tcp from any to any 80 out
$IPF 361 allow tcp from any to any 443 in
$IPF 362 allow tcp from any to any 443 out
$IPF 363 allow tcp from any to any 22 in
$IPF 364 allow tcp from any to any 22 out

$IPF 1000 deny log all from any to any

Also: I started having this problem after upgrading to FreeBSD 10.3 (9.2 earlier).
What is the problem?
Answer: I do not use IPv6, but I notice from /etc/rc.firewall and /etc/protocols that ICMP has a different symbolic name for IPv6 which is ipv6-icmp. If you need to pass IPv6 ICMP packets, you may want to add a new rule:
allow ipv6-icmp ...

I do not understand your existing rules, and you may have separated in and out rules for diagnostics purposes, but:
allow tcp from any to any xxx in
allow tcp from any to any xxx out

Is similar (if not equivalent) to:
allow tcp from any to any xxx

Also, all of your out rules are pre-empted by rule 270 anyway.
If your server needs to use name service, you are missing a rule to allow responses from the remote DNS server over UDP:
allow udp from any 53 to any

Comment: `icmp6` works as well. Also thanks for catching the 270 rule.

IPFW denies ssl connections


apache virtualhost with condition

Question: I have added an Apache proxy for node application, below is my conf
<VirtualHost *:80>
    ServerName main.open.co
    DocumentRoot /var/www/vhosts/maint-test
    Options -Indexes
    ErrorDocument 404 /test.html
    ProxyRequests on
    ProxyPass /test.html !
    ProxyPass / http://localhost:4130/
    ProxyPassReverse / http://localhost:4130/
</VirtualHost>

The above configuration works fine but I want to add a condition that if test.html is present in DocumentRoot then it should show test.html, else it should use ProxyPass.
Can anyone please help me on this ?
Comment: Your configuration seems correct `ProxyPass /test.html !` should not proxy /test.html, what happend when you try yourserver/test.html ? What is wrote in access or error logs. I think you are trying to redirect localhost:4130 404 errors to /test.html, but you are doing it in Apache instead of your localhost:4130 application. You application on port 4130 should trigger /test.html to works as you want (even if /test.html doesn't exist on localhost:4130
Answer: You can use Rewrite Rules with Proxy support instead. I have tested this & it works.
 <VirtualHost *:80>
    ServerName main.open.co
    DocumentRoot /var/www/vhosts/maint-test
    Options -Indexes
    ErrorDocument 404 /test.html
       RewriteEngine On
       RewriteCond %{REQUEST_URI} !test.html
       RewriteRule ^/(.*)$ http://localhost:4130/$1 [P,L]

       RewriteCond %{REQUEST_URI} test.html
       RewriteCond /var/www/vhosts/maint-test%{REQUEST_FILENAME} !-f
       RewriteRule ^/test.html$ http://localhost:4130/test.html [P,L]
</VirtualHost>

apache virtualhost with condition