In R Limma's `normalizeMedianValues` function, why is its operations preceded with a log transformation followed by an exponential transformation?

Question: In the function normalizeMedianValues in the package limma, column counts are normalised such that their column medians are equal to the average of the column medians.
What I'd like to understand is why the medians are first log transformed, followed by the subtraction of the mean medians, then reversed with an exp() function. What is the mathematical or statistical reasoning behind this? What happens if you don't do the log or exp transformation? Here is the code:
normalizeMedianValues <- function(x)
#   Normalize columns of a matrix to have the same median value
#   Gordon Smyth
#   24 Jan 2011.  Last modified 24 Jan 2011.
{
    narrays <- NCOL(x)
    if(narrays==1) return(x)
    cmed <- log(apply(x, 2, median, na.rm=TRUE))
    cmed <- exp(cmed - mean(cmed))
    t(t(x)/cmed)
}

M <- cbind(Array1=rnorm(10, mean = 100),Array2=2*rnorm(10, mean = 100))

normalizeMedianValues(M)

Answer: In your example, the normalised values are about the same size as the original values. That's the point of subtracting the log mean.  If you instead used
normalizeMedianValues1<- function(x) {
    narrays <- NCOL(x)
    if(narrays==1) return(x)
    cmed <- apply(x, 2, median, na.rm=TRUE)
    t(t(x)/cmed)
}

the normalised values would all be around 1.
Another way to write the code, which might be clearer, is
    cmed <- apply(x, 2, median, na.rm=TRUE)
    scale<-exp(mean(log(cmed)))
    t(t(x)/cmed)*scale

We divide each column by its median, making them all have a median of 1, then multiply by the geometric mean of the medians, so the normalised columns all have a median that's equal to scale, a value in the middle of the data range in some sense.
Comment: Great answer, your alternative way of writing the code really helped me understand the problem (and develop a better way of writing a function that works in long-format data).

My initial question was really focused on the rationale for `exp(mean(log(cmed)))`, but I now know its the geometric mean (which I've heard of but never really used). I'm guessing its used here over arithmetic mean purely because it is better suited to skewed values?


Drag and Drop code snippet for flash Canvas

Question: I'm working on a code snippet in Flash Canvas HTML5 to allow an icon to be dragged and dropped over a target, then on release the playhead jumps to a frame number.
Here is what I have so far:
this.Brush.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag_5);

function fl_ClickToDrag_5(event:MouseEvent):void
{
     this.Brush.startDrag();
}

stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_5);

function fl_ReleaseToDrop_5(event:MouseEvent):void
{
      this.Brush.stopDrag();
}

Any help would be great, thanks
Comment: What is the question?
Answer: I have found this http://www.adobe.com/inspire/2014/03/flash-pro-jigsaw.html resource to be invaluable with building a drag and drop activity in the new flash canvas environment.
To make your icon jump to a different frame I would add a gotoAndStop(/*FrameNumber*/) inside the on press up function of the tutorial (line 29 or 30 I believe).
Answer: this.slider.addEventListener("mousedown", mouseDownFun.bind(this));

function mouseDownFun()

{

    console.log("mouseUpFun");
    this.slider.addEventListener("pressmove", mouseMoveFun.bind(this));
    this.slider.addEventListener("pressup", mouseUpFun.bind(this));
}

function mouseMoveFun()

{

    this.slider.x = stage.mouseX - 42;
}

function mouseUpFun()

{

    console.log("mouseUpFun");
    this.slider.removeEventListener("pressmove", mouseMoveFun.bind(this));
    this.slider.removeEventListener("pressup", mouseUpFun.bind(this));
}


Ordered sampling of uniform variables

Question: I need to sample starting positions in a DNA sequence of given length L.
These starting positions represent starting points of functional domains in DNA sequences. They have a length of d. The starting positions should be distributed uniformly and must have a minimal distance of d between them (functional domains should not overlap). Positions higher then L-d+1 are not possible because functional domains should be complete.
The approach of sampling iterativly a starting position i and procecede with sampling in uniformly in the interval [i+d, L-d+1] does not produce a uniform distribution.
Do you know of any solution to this?
Comment: Depending on the relative sizes of L, d and the number of samples you need, this may work: sample starting positions uniformly without the distance requirement, and reject if the distance requirement is not met.  Typically you're not going to have many functional domain starting points in a sequence, so you should not get too many rejections.
Comment: Surely this is correct but I was wondering for a more elegant solution.
Comment: Elegance is in the eye of the beholder. But: I didn't post it as a solution :-)
Comment: Actually, come to think of it: what do you mean by uniform distribution in this case? If e.g. L is 4 and d is 2 while n is also 2, the only solution is to take positions 1 and 3. In what way can this ever be 'distributed uniformly'?
Comment: Surely this would be uniform distributed. Every solution (there is only one) has the same probability (1).
Comment: This question is crossposted on math.SE. Please see the FAQ and meta about crossposts.
Answer: In java'ish pseudo-code:
<code>curpos=-d+1
for(i=1; i<=n; i++)
{
    maxendrange=L-(n-i+1)*d // make sure there's room for all the remaining domains
    minstartrange=curpos+d //skip the previous domain
    newpos=sampleuniform(minstartrange, maxendrange)
    //store result somewhere
}
</code>
I haven't proved it or anything, but I'm quite sure this should give equal probability to all possible solutions.
Edit: Within the loop, you would have to weight based on how many ways you can position  $n-i$ domains (with the distance restriction) in a sequence of length $L-(curpos+2d)$. It's going to require a lot of calculations that are bound to be more 'expensive' than simply sampling without the distance requirement and rejecting based on it.
As such I return to my original idea (as mentioned in my comment): it will probably be the most effective solution...
Comment: Against your intuition. This is clearly not uniform distributed. :D
Comment: The more I investigate in this problem. The more I think you are right. I have a mathematical approximation. A benchmark will decide which way is the best.

Ordered sampling of uniform variables


Save information to the second page and so on

Question: I have this code in my php email body.

Register

In the link of the code above, when it is clicked it will direct the user to the get-referal.php.
Here is the code in the get-refereal.php:
    <?php

        $referal_name=$_GET[member_name];
        $referal_email=$_GET[member_email];

    ?>

    <?php echo $referal_name ?>
    <?php echo $referal_email ?>

    Home
    Galery

In the get-referal.php I am able to get the referal_name and the referal_email
But what I want know is when the user click Home.php or Galery.php, I am still able to get the referal_name and the referal_emailwithout have to set the link to

'php?member_name='.$member_name.'&member_email='.$member_email.'

[UPDATE]
What I want now is how to hide the member_name and member_email in the url link so that the user can't change it?
Comment: Now you can use `$_SESSION` variable to hide member data.
Comment: Use sessions. Look it up in the manual.
Answer: I would save the values in session variables.
At the start of each page where you need the session to persist put:
<?php session_start(); ?>

Then in the page where you grab the GET data, store it in a session var:
$_SESSION['member_name'] = $_GET['member_name'];
$_SESSION['member_email'] = $_GET['member_email'];

You will,then be able to retrieve from the SESSION super global on any page with a valid session running.
I would be very careful in how you use the data from the $_GET global as it's very easily tampered with.
Comment: How to make it safe from _easily tempered with_?
Comment: dont use a $_GET global as its easy for someone to substitute the data in it. Or if you have to, pass it through a sanitisation function.  If you like my posted answer, please accept it.
Answer: Try this :

<a href="http://indd.jncy.com/get-referal.php?member_name=<?PHP echo $member_name; ?>&member_email=<?PHP echo $member_email;?>">Register

User <?PHP ?> for use php variables.
[UPDATE]
Store $member_name and $member_email to Session.
First start session then use it.
<?PHP
session_start();

$_SESSION['referal_name']=$member_name;
$_SESSION['referal_email']=$member_email;
?>

Register

Now write following code in get-referal.php
<?PHP
session_start();

$referal_name=$_SESSION['referal_name'];
$referal_email=$_SESSION['referal_email'];

?>

<?php echo $referal_name; ?>
<?php echo $referal_email; ?>

Home
Galery

Comment: I have also a session for login user. The session for login user is different from the session for referral user. However, when I click the link directly for the referral user, it reads the session for the login user instead for the referral.
Answer: start session at each page
<?php
        // Start the session
        session_start();
 ?>

At page get-refereal.php
$_SESSION['referal_name']=$referal_name;
$_SESSION['referal_email']=$referal_email;

At pagehome.php and galery.php  you can get it by
$val1=$_SESSION['referal_name']; and $val2=$_SESSION['referal_email'];

echo $val1;
echo $val2;


dataframe mean calculation -> values that differ >20% from the median should be excluded from the mean-computation

Question: I want to calculate the row-wise mean of columns y_2010, y_2011, y_2012, y_2013, y_2014 of the dataframe (energy use data per year), however:

values that differ more then 20% from the median (of the five values), should be excluded from the mean computation.
if less then two values in each row remain (after the condition above), the mean is set to NaN  as one value is not enough to have a reliable mean -> so the mean can only be calculated for rows that contain two or more values after the '20% difference condition' above. (see ID(36): one value remains after the first condition, but that's not enough for a reliable mean so it's set to NaN)

Calculation of the mean of 5 columns is easy, but I'm stuck at defining the conditions 'if median*0.8 <= one of the values in the data row <= median*1,2 then mean == mean of values within the boundary and 2 or more values are present.
So I'm trying to calculate the mean only for the data rows with no 'outliers'.
Initial df:
ID  y_2010   y_2011   y_2012  y_2013  y_2014
23   22631  21954.0  22314.0   22032   21843
43   27456  29654.0  28159.0   28654    2000
36   61200      NaN      NaN   31895    1600
87   87621  86542.0  87542.0   88456   86961
90   58951  57486.0   2000.0       0       0
98   24587  25478.0      NaN   24896   25461

Desired df:
   ID  y_2010   y_2011   y_2012  y_2013  y_2014      mean
0  23   22631  21954.0  22314.0   22032   21843   22154.8
1  43   27456  29654.0  28159.0   28654    2000  28480.75
2  36   61200      NaN      NaN   31895    1600       NaN
3  87   87621  86542.0  87542.0   88456   86961   87424.4
4  90   58951  57486.0   2000.0       0       0       NaN
5  98   24587  25478.0      NaN   24896   25461   25105.5

Tried code so far (I'm stuck at getting the conditions right and apply them to the dataframe):
import pandas as pd
import numpy as np

df = pd.DataFrame({"ID": [23,43,36,87,90,98],
               "y_2010": [22631,27456,61200,87621,58951,24587],
               "y_2011": [21954,29654,np.nan,86542,57486,25478],
               "y_2012": [22314,28159,np.nan,87542,2000,np.nan],
               "y_2013": [22032,28654,31895,88456,0,24896,],
               "y_2014": [21843,2000,1600,86961,0,25461]})
print(df)

a = df.loc[:, ['y_2010','y_2011','y_2012','y_2013', 'y_2014']]

# calculate median
median = a.median(1)
print(median)

# where condition is violated
mask = a.lt(median*.8, axis=0) | a.gt(median*1.2, axis=0)

Comment: the mean for the row with ID 90 should also be set to NaN right?
Comment: Sure, you're completely right! I'm sorry ;) I must have overlooked the zeros at first.
Answer: I think your mask is right, then from there you can try this:
col_mean = a[~mask].mean(axis=1)
nan_mask = ~(mask.sum(axis=1) >= 2)

a["mean"] = col_mean.where(nan_mask, other=np.NaN)
print(a)

Output:
   y_2010   y_2011  y_2012  y_2013  y_2014  mean
0   22631   21954.0 22314.0 22032   21843   22154.80
1   27456   29654.0 28159.0 28654   2000    28480.75
2   61200   NaN     NaN     31895   1600    NaN
3   87621   86542.0 87542.0 88456   86961   87424.40
4   58951   57486.0 2000.0  0       0       NaN
5   24587   25478.0 NaN     24896   25461   25105.50

Comment: exactly! I wasn't familiar with the '~' operator, but it's quite neat this way.


Calling Patch.exe from Powershell with p0 argument

Question: I'm currently trying to patch some files via PowerShell using Patch.exe
I am able to call the exe using the '&' command, but it doesn't seem to be reading my p0 input. I'm not an expert on PowerShell and any help would be appreciated!
here is what I am calling in PS:
$output = & "$scriptPath\patch.exe" -p0 -i $scriptPath\diff.txt

My error reads:
can't find file to patch at input line 5
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:

Which I can emulate by leaving out the p0 parameter on my patch file from commandline.
Here are some alternatives I've already tried:
#$output = & "$scriptPath\patch.exe" -p0 -i "$scriptPath\diff.txt"

#CMD /c "$scriptPath\patchFile.bat" (where patchFile.bat has %~dp0patch.exe -p0 < %~dp0diff.txt, seems like powershell reads < as 0<, so there is an error there I think)

#GET-CONTENT $scriptPath\diff.txt | &"$scriptPath\patch.exe" "-p0"

#GET-CONTENT $scriptPath\diff.txt | CMD /c "$scriptPath\patch.exe -p0"

Thanks!
Answer: Try:
$output = & "$scriptPath\patch.exe" -p0 -i "$scriptPath\diff.txt"

Comment: That path looks like a relative path.  If patch.exe happens to be relying on the process's current working directory, you may need to set that manually e.g. `[Environment]::CurrentDirectory = $pwd`
Comment: Ah in that case, it was just the PowerShell file system provider's current directory which is different from the process's current directory.  The reason for this is you can have multiple runspaces in a process, each CD'd into a different location therefore the notion of a single current directory does not apply very well to a process running the PowerShell engine.
Comment: @RichardLee Which Patch.exe is this? Does the fact that it indicates it is at input line 5 mean that it is reading your diff.txt file?  If so, how is the filename specified at line 5 in that file?
Comment: I got the patch.exe from gnuwin -- its a windows version of the linux patch command. Yes, I think it is reading my diff.txt correctly. Line 5 just indicates where the diff changes were '@@ -23,7 +23,7 @@' -- however in some other errors it points to the line where it indicates which file to change like "--- CacheLib/config.xml (revision XXXXX)"
Comment: Although the powershell script was starting in the same location as my patch.exe (which was in cachetools), something was misaligned.. I think you are correct, I actually got it working a few minutes ago using Push-Location $scriptPath / Pop-Location!
Answer: Patch.exe started in the wrong context and I solved this by using Push-Location / Pop-Location
Here is what my code looks like now
Push-Location $scriptPath
$output = & "$scriptPath\patch.exe" -p0 -i "$scriptPath\diff.txt"
Pop-Location

Keith also mentioned in one of his comments that you can use:
[Environment]::CurrentDirectory = $pwd

I have not tested this, but I assume it does the same thing (Keith is a powershell MVP, I am just a student).


How to dissmiss keyboard in MFMailComposeViewController?

Question: I am using MFMailComposeViewController to compose email for my iPhone app. How could I dismiss keyboard after entering 'toRecipients'?
Answer: Try this.
<code>UIWindow* keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView* firstResponder = [keyWindow performSelector:@selector(firstResponder)];
[firstResponder resignFirstResponder];
</code>
But Also Remember.
Important: The mail composition interface itself is not customizable and must not be modified by your application. Apple might reject your app for it. Documentation
Comment: Possible Duplicate ***Question & Answer*** http://stackoverflow.com/q/4872565/1059705


Contexto da propriedade this no TypeScript + Node

Question: Tenho uma classe XPTO com os métodos abaixo, no método de login eu tento chamar o método de tratamento da resposta, contudo, o this está undefined no contexto da função, pelo que pude entender eu teria que usar a função .bind(), mas como eu faria isso se minha função de tratamento de resposta recebe parâmetros?
Naturalmente, eu poderia fazer tudo em uma função só (eu testei e funcionou), mas ai a função ficaria muito grande, já li esta pergunta, mas não ficou claro.
Código das duas funções:
import AutenticacaoDAO from '../daos/autenticacao.dao'
import MailController from './email.controller'
import jwt from 'jsonwebtoken'
import TokenSecret from '../config/token-secret'
import crypto from 'crypto'
import { Request, Response } from 'express'
import { Usuario } from '../models/usuario.model';

class AutenticacaoController {
    constructor() {

    }

    public async login(req: Request, res: Response) {
        let usuario;
        try {
            usuario = await AutenticacaoDAO.login(req.body)
            this.tratarResposta(crypto.createHash("md5").update(req.body.senha).digest("hex"), usuario, res)  //this está undefined
        } catch (error) {
            res.json(error)
        }
    }

    private tratarResposta(senhaEnviada: any, usuario: any, res: Response){ //função que eu quero chamar
        if (usuario && usuario.length > 0 && senhaEnviada === usuario[0].usuario.senha && !usuario[0].usuario.bloqueado) {
            res.json({
                usuario: usuario,
                token: jwt.sign({ usuario: usuario[0] }, TokenSecret, { expiresIn: '7d' })
            })
        } else if (usuario && usuario.length > 0 && senhaEnviada !== usuario[0].usuario.senha) {
            res.status(403).json({
                mensagem: `Não foi possível efetuar o login, sua senha está incorreta.`, erro: res.statusCode
            })
        }
        else if (usuario && usuario.length > 0 && usuario[0].usuario.bloqueado) {
            res.status(403).json({
                mensagem: `Não foi possível efetuar o login, seu usuário encontra-se bloqueado. Converse com seu gestor.`, erro: res.statusCode
            })
        }
        else {
            res.status(404).json({
                mensagem: `Não foi possível efetuar o login: Usuario não encontrado.`, erro: res.statusCode
            })
        }
    }

}

export default new AutenticacaoController()

Comment: Esses métodos fazem parte de uma classe?
Comment: Sim, vou colocar a classe toda, acho que fica melhor.
Comment: @luizfelipe, coloquei a classe toda.
Answer: Quando você vai executar o login em outro lugar, o this.tratarResposta será referenciado para aquele outro lugar, e não para essa classe. Estranho não? Mas JS é assim. haha
Pra isso, dentro do construtor, coloque: this.login = this.login.bind(this)
Isso vai fazer o this.tratarResposta referenciar ao this.tratarResposta de AutenticacaoController, e não da classe que ele estará chamando. Sempre que der undefined, é preciso fazer um bind, e o melhor lugar para isso é no constructor.
Não cheguei a fazer testes de código, mas acredito que seja isso. Caso não funcionar, crie um código online (no codepen ou outro lugar) simulando exatamente como você está fazendo ai.


É possível criar um campo data que seja Cross-Browser?

Question: Alguém sabe como fazer com que o <input type="date"> funcione em todos os navegadores?
No Google Chrome funciona normalmente, consigo passar o parâmetro no formulário, recebo na variável e jogo no insert, o problema é que no Internet Explorer ele não captura essa data. Existe algum código que faça esse método valer em todos os navegadores?
Comment: Vc está usando `` ?
Comment: sim estou!!!!!!
Answer: Não são todos os browser que suportam <input type="date" />.
Veja aqui a lista de compatibilidade de browsers para a tag <input type="date">


Modelling of Artificial Neural Networks for Deep Learning

Question: A few questions arose, which are related to ANN modelling.
First of all, is it possible to determine the number of hidden layers at the beginning and the ANN itself changes this number on its own to optimize the results?
Second, in a supervised training phase, an expert delivers input-result-pairs to the ANN. Will the expert usually take a look at the weights the system proposed or is it hidden / not interesting for the expert?
Third, in an unsupervised training phase, only input elements are delivered to the system. How does the system optimize the weights or it's structure if there is no result for a comparison?
Thanks in advance for some clarification and hints.
Comment: This might be useful: https://stats.stackexchange.com/questions/21717/how-to-train-and-validate-a-neural-network-model-in-r
Answer:
is it possible to determine the number of hidden layers

Unfortunately not. You can think of these as the parameters of the models and you have to specify or learn them.
Determining the number of layers and nodes per layer is a hard problem (as well as finding the weights). What you typically do is trying and out then checking the results. There are some more clever ways like e.g. genetic algorithms.

self adjusting

This can be done but not in an obvious way. If you set the Network to be very large and introduce regularization by decaying the weights or penalizing high weights the Network will reduce some of the weights to zeros. This is effectively having fewer weights. As for changing the number of layers i simply don't know. This changes the whole dynamic of the net and i don't think it's possible. At least easily.

Will the expert usually take a look at the weights

You can do that. I makes sense for the first layer, i.e. the ones that are connected directly to the input. If the input has a semantic meaning, like e.g. "female" you can interpret the weight assigned to it. In convolutional neural nets this is also quite popular. The weights can there be visualizes as images, like done here http://cs231n.github.io/assets/cnnvis/filt1.jpeg

unsupervised training

If you don't have any targets you can e.g. perform a clustering. This seeks to find a pattern in the data and match the data to so called prototypes. These prototypes represent a class of data. You can look into "Self Organizing Maps".
Comment: Thanks for your reply. My first question was, if the neural network itself can adjust its structure?


What is hook_field_default_fields()?

Question: I'm looking through a Drupal 7 module code in an attempt to understand what it does. It implements hook_field_default_fields(), but I can't find any documentation on this.
What does this hook do?
I did find that the Field Types API seems to expose similar hooks such as hook_field_extra_fields(), but they aren't exactly the same.
Answer: It's a hook used from the Features module. Truly, the feature.api.php file, which should contain a description of all the hooks used by a module, contains a description for hook_field_default_fields_alter().

Deprecated as of 7.x-2.0.
Alter the default fields right before they are cached into the database.
@param array[] &$fields
By reference. The fields that have been declared by another feature.
@deprecated

Usually an alter hook is paired with a "normal" hook, but that is not always the case.
If you see that the hook is always invoked with drupal_alter('field_default_fields', /* the other arguments */), the module uses only the alter hook. Checking if the module itself implements hook_field_default_fields() or hook_field_default_fields_alter() would also help to understand which hook is used from the module. Unfortunately, in this case, the module doesn't implement neither one or the other hook. This is easily explained from the fact the hook has been deprecated. (A module should be the first one not to implement its own deprecated hooks.)

What is hook_field_default_fields()?


Is it OK to use a 409 HTTP code in the case when the record with specified property that should be unique already exists?

Question: I have a table that contains two unique columns. Is it OK to return 409 for PUT requests that trying to create a record with a duplicate column value?
Comment: HTTP codes are not about your internal states, only about the resources - how does the request looks like? Apart from that nobody can force you not to return a 409 in that case, there's no REST police walking around and inspecting your API.
Comment: `PUT: { "Token":"unique token", "Name": "unique name"... }`
Of course, there is no REST police. I asked about the common practice.
Answer:
Is it OK to use a 409 HTTP code in the case when the record with specified property that should be unique already exists?

Sure.
It may help to consider that status codes are meta data; they are information provided to inform general purpose components coarse grained understanding of the nature of the HTTP response, rather than being information for the API consumer.
If you like, consider the common case on the web: we send a 404 response so that the browser (and any general purposes caches along the way) will understand that the body of the response is a representation of a description of a client error, so that they can manipulate their local caches correctly.
But the human being gets an HTML representation of a fail whale.
Given that the primary audience of the status code is machine, rather than man, you can get a sense of the appropriateness of a status code by looking into what the consequences of the different codes would be.
And the truth is, for many of the codes... 400 vs 403 vs 409 vs whatever...  there just isn't a lot that the machines can do that is different from one code to the next.  In a lot of cases, about the best you could hope for is to highlight the part of the http request (method-token, URI, HTTP-version, body, authorization...) that is the source of the problem.
409 is a fine choice for your case - in particular, it calls attention to the body of the request, informs that there is some incompatibility between the semantics of the current request and the current state of the resource, and indicates that the client may be able to resolve the conflict and resubmit the request.
But if you were to choose "403" instead, the negative consequences would be really small.  From the outside, in practice, is just doesn't matter very much.


Javascript - Why below function definition errors out?

Question: var a = [3,5,2,6,8];
var i = 0;
function x(a[i]) { //This line errors out, why?

}

Please explain why above line errors out? and I am trying to print array elements in reverse order using recursion. If you can write the code also, would be fantastic!
Comment: The argument declaration, `a[i]`, is invalid syntax. Just `a` will do.
Answer: you pass value to function definition. you have to give it when you call function, not when defining
function. you can pass a value when you call a function.
var a = [3,5,2,6,8];
var i = 0;
function x(t) {

}
x(a[i]);

Answer: You are defining a function with an argument incorrectly. You give a name to your function arguments, just like any other variable:
function x(array) {
  //Do something with your array
}

And then you call the function:
var a = [1,2,3,4,5];
x(a);

Answer: Using recursion:
var a = [3,5,2,6,8];
function x(p, len) {
   if(len >= 0){
     alert(p[len-1]);
     x(p, len-1);
   }
}
// and call
x(a, 5);

DEMO
Comment: No reverse functions to be used...logic only invited!
Comment: @sahilsharma added recursion to answer ;)
Answer: As you can read on other answers, you are sort of mixing function declaration and function evaluation (call).
This declares the function x that accepts an a parameter:
function x(a) {

}

And this calls a function x with argument a:
var a = [3,5,2,6,8];
x(a);

or directly:
x([3,5,2,6,8]);

Regarding to the recursive function to reverse an array, this could be an option:
var a = [3,5,2,6,8];
function x(a) {
    if (a.length === 0) {
        return [];
    }
    return a.slice(-1).concat(x(a.slice(0, -1)));
}


Qual é a sintaxe correta para usar orientação a objetos em C# usando o .NET Core?

Question: Tenho que me familiarizar com implementação do código orientação a objeto no desenvolvimento C#. No entanto, os materiais que estou aprendendo supõem que eu tenho ambiente Windows e Visual Studio instalado (exemplo). Quando pesquiso material a respeito acabo me deparando com tutoriais de orientação a objeto que pouco tem haver com meu problema específico (que é fazer isso usando .NET Core).
Então imagino que deva ter alguma importação (no C# usam a expressão using + a importação), qualquer coisa que permita que eu apenas me ambiente a usar OOP.
Estou tentando implementar com o seguinte código:
using System;

namespace hwapp
{
    class Program
    {
        static void Main(string[] args)
        {
           objeto c = new Program();
    c.numero = 12;
    c.titular = "João";
    c.saldo = 102;

    Console.WriteLine("Número: "+c.numero+"\n");
    Console.WriteLine("Titular da conta: "+c.titular+"\n");
    Console.WriteLine("Salto: "+c.saldo+"\n");
        }
    }
}

Ao dar o comando dotnet run, retorna a seguinte mensagem

Program.cs(9,12): error CS0246: The type or namespace name 'objeto' could not be found (are you missing a using directive or an assembly reference?) [/home/upgrade/dotnet/hwapp/hwapp.csproj]

The build failed. Please fix the build errors and run again.

Leituras recomendadas:
O que posso fazer no .NET Framework e no .NET Core não? E vice-versa
https://docs.microsoft.com/pt-br/dotnet/articles/core/
Answer: Qualquer material que ensine uma linguagem em cima de um IDE não é um bom material pra se aprender linguagem. Inclusive não gosto do material que está usando, mas é só minha opinião.
O C# é a mesma linguagem não importa em qual runtime ou sistema operacional que está rodando. Então se aprender a linguagem com um bom material pode usar esse conhecimento de forma idêntica em todo lugar. O .NET Core é só uma base escrita de forma diferente para usar a mesma coisa. Claro que as bibliotecas não básicas podem ter algumas diferenças para atender o objetivo dele que é diferente do .NET Framework (que morreu). E não dá para fazer algo universal como algumas pessoas acreditavam ou acreditam até hoje que dá.
Orientação a objeto é só uma organização de código. Ou você sabe OOP ou não sabe, isto independe de linguagem. E devo dizer que poucas pessoas sabem realmente o que é e como fazer OO corretamente, a maioria só acha que sabe, vide  efeito Dunning-Kugger. Orientação a objeto é só um paradigma secundário.
O código apresentado não tem nada nem perto do OOP. Na verdade tem um erro de digitação, o tipo deveria ser object e não objeto. De qualquer forma aquilo não deveria ser do tipo object. Este código é absolutamente procedural e sem sentido. porque acessa membros que não existem no tipo object.
Recomendo escolher um material que ensine em passos, que só entre em orientação a objeto quando dominar o básico. Veja c#.
Isto provavelmente causará mais confusão do que ajudar, mas algo que seria na linha do que está desejando:
using static System.Console;

public class Program {
    public static void Main(string[] args) {
        var conta = new Conta(1, "Joao", 100M);
        WriteLine(conta.Sacar(103.45M) ? $"Saque realizado, saldo restante {conta.Saldo}" : "Não foi possível sacar");
        conta.Depositar(50.0M);
        conta.Titular = "Joao da Silva";
        WriteLine(conta.Sacar(103.45M) ? $"Saque realizado, saldo restante {conta.Saldo}" : "Não foi possível sacar");
        WriteLine($"Número: {conta.Numero}");
        WriteLine($"Titular da conta: {conta.Titular}");
        WriteLine($"Saldo: {conta.Saldo}");
    }
}

public class Conta {
    public int Numero { get; set; }
    public string Titular { get; set; }
    public decimal Saldo { get; set; }
    public Conta(int numero, string titular, decimal saldo) {
        Numero = numero;
        Titular = titular;
        Saldo = saldo;
    }
    public void Depositar(decimal valor) => Saldo += valor;

    public bool Sacar(decimal valor) {
        if (Saldo - valor >= 0) {
            Saldo -= valor;
            return true;
        }
        return false;
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Obviamente que isto é uma enorme simplificação. Uma classe real teria muito mais complexa. Isto é orientado a objeto? Em parte. Há encapsulamento, e só. OOP é muito mais complexo que isso, mas de forma simplificada, partindo de que não precisa de outras complexidades pode ser considerado OO.
Então o erro aí é exclusivamente de digitação e uso indevido de campos, nada tem a ver com estar no Linux, ser .NET Core, ou estar usando OOP. Existe um problema do código ser muito ruim, principalmente se está querendo fazer OOP.
Sobre o using precisa saber para que ele serve. Não faz o menor sentido importar nomes de algo que faz parte da linguagem e não da biblioteca.
Importante notar que a resposta do AP mantém as mesmas premissas erradas da pergunta e incorpora mais algumas. É normal quando a pessoa desconhece os fatos, mas fica o alerta para quem está aprendendo.

Um exemplo de código mais razoavelmente orientado a objeto em PHP que acho que já conhece.
Significado da terminologia: "Orientado a objeto"
O que é "Orientado a objeto" e quais outros métodos?
O que é paradigma?
Programação Funcional e Programação Orientada a Objetos. O que são e quais suas principais diferenças?
Também seria bom saber sobre tipagem estática e dinâmica e estilo de tipagem.
Comment: O primeiro comentário não faz sentido, não tem relevância para o problema. A resposta lá resolve o problema, mas desensina. Siga aquilo e fará errado pra sempre.
Comment: "Orientação a objeto é só uma organização de código" +1. E se pudesse daria outro pela menção a D/K.
Comment: O ponto é quero praticar os exercícios. Quero ver rodando.
E simplesmente não consigo fazer isso no .NET CORE .
E ainda tem o problema de nem tudo usado no .NET framework ser usado no .NET CORE.
Comment: Quando você voltar, eu gostaria que complementasse com a resposta do stackoverflow em inglês:
http://stackoverflow.com/questions/43965452/how-to-program-in-oop-by-c-sharp-in-net-core/43965612#43965612

Também preciso almoçar :)
Comment: Verdade! Mas por sorte eu descobri duas coisas erradas em matéria tanto de C# quanto de OOP, que fiz com aquela implementação. Depois do almoço eu vou descrever isso, e isso talvez ajude aqueles que estiverem aprendendo e passando pelo mesmo problema.
Comment: Acabei de ver o final da edição do seu post. Quando eu voltar mostro porque tem mais do que erro de digitação.
Comment: É, tem o uso de variáveis locais como se fossem campos, que eu falo no começo.
Comment: Tem mais que isso. Em breve eu posto!
Comment: @OnoSendai que acabou se mostrando a coisa mais importante de toda resposta :D
Answer: O problema foi solucionado com as questões abaixo.
Erros envolvendo C#

Então imagino que deva ter alguma importação (no C# usam a expressão
  "using" + a importaçao), qualquer coisa que permita que eu apenas me
  ambiente a usar OOP.

A resposta é não! Não é necessário o uso de nenhuma importação/biblioteca/framework adicional para testar recursos do paradigma orientado a objetos. O C# nativamente trabalha orientado a objetos, e o insucesso do teste realizado tem haver com a falta de conhecimento do AP em relação a implementação do C# com esse paradigma, e uso de material didático inchado (que limita a certo ambiente de desenvolvimento). Os erros serão comentados a seguir.
static void Main(string[] args)
        {
           objeto c = new Program();
    c.numero = 12;
    c.titular = "João";
    c.saldo = 102;

Na terceira linha, o código está seguindo o exemplo do material didático.
Conta c = new Conta();

Só que mesmo no material didático, a classe Conta já tinha tido declarada os tipo de seus atributos.
class Conta
{
    int numero;
    string titular;
    double saldo;
}

O erro principal foi não declarar os tipos dos atributos no código de exemplo. Esse defeito foi corrigido pelo StackOverFlow em inglês.
using System;

namespace hwapp {
    class Program {
        // Aqui embaixo está a correção dos atributos
        int numero;
        string titular;
        int saldo;

        static void Main(string[] args) {
            var conta = new Program(); // linha corrigida
            conta.numero = 12;
            conta.titular = "João";
            conta.saldo = 102;

            Console.WriteLine("Número: "+conta.numero.ToString()+"\n");
            Console.WriteLine("Titular da conta: "+conta.titular+"\n");
            Console.WriteLine("Saldo: "+conta.saldo.ToString()+"\n");
        }
    }
}

Erros de conceituação do paradigma orientado a objetos
Sobre essa linha..
objeto c = new Program();

Mesmo se "objeto" fosse o objeto de fato, ele não foi "setado", então não existe. A explicação porque o material didático fez isso já foi dita acima. Vale citar que o AP não tinha intenção de usar a sintaxe "object", que eu não sabia que existia em C#. Outro problema é o título original da pergunta:

Como programar orientação a objetos em C# usando o .NET CORE?

Embora ainda seja programação a pergunta, ela pode induzir o usuário do SOPT a dissertar sobre paradigma de Orientação a Objetos (o conceito), e não o problema da implementação (o código). Por exemplo, pode ser levantada questões se, um código que não use algum dos pilares do paradigma OOP (abstração, encapsulamento, herança e polimorfismo) é de fato OOP. Um defensor purista do paradigma pode alegar que deva existir uso completo dos pilares. Seu opositor vai alegar que excesso de herança causa acoplamento. No final nenhum dos dois abordará a implementação em C# (que sempre tem diferenças entre uma linguagem e outra). Por este motivo, após a edição deste post, o título da pergunta e partes do conteúdo será alterado. Ainda sobre um terceiro erro do AP envolvendo OOP, é supor que deva haver um adicional de qualquer forma. Esse erro também foi citado nos erros envolvendo C#. Se tal ferramenta alega que nativamente dá suporte a OOP, pelo menos qualquer adicional não deveria ser instalado/importado/etc. Talvez essa "bizarrice" exista em alguma ferramenta mas é passível de críticas. Abaixo código da classe funcionando sem importação.
namespace hwapp {
    class Program {
        // Aqui embaixo está a correção dos atributos
        int numero;
        string titular;
        int saldo;

        static void Main(string[] args) {
            var conta = new Program(); // linha corrigida
            conta.numero = 12;
            conta.titular = "João";
            conta.saldo = 102;

        }
    }
}

O máximo que acontece é um Warning de dados não sendo utilizados
Program.cs(6,13): warning CS0414: The field 'Program.numero' is assigned but its value is never used [/home/upgrade/dotnet/hwapp/hwapp.csproj]
Program.cs(8,13): warning CS0414: The field 'Program.saldo' is assigned but its value is never used [/home/upgrade/dotnet/hwapp/hwapp.csproj]
Program.cs(7,16): warning CS0414: The field 'Program.titular' is assigned but its value is never used [/home/upgrade/dotnet/hwapp/hwapp.csproj]

Sobre um quarto erro envolvendo esse tópico, está no conceito de CamelCase. Isso não necessariamente é um erro de OOP, mas de boas práticas. Mas que induziu um erro de OOP ao não notar a sintaxe da classe Conta.
O problema foi solucionado buscando informações destes conceitos.
Resposta do StackOverFlow em inglês:
https://stackoverflow.com/questions/43965452/how-to-program-in-oop-by-c-sharp-in-net-core
Orientação a objetos
https://msdn.microsoft.com/pt-br/library/cc580626.aspx?f=255&MSPPError=-2147217396
Sobre CamelCase
https://pt.wikipedia.org/wiki/CamelCase
Comment: Não porque aqui não é um fórum. Se você deseja aprender tudo errado é problema seu, a chance de aprender certo foi dada. Pra falar a verdade eu nem achava que essa pergunta era boa, tive o maior esforço para responder o mais completo possível. E acho que já demostrei que sei o que estou falando, ainda mais em uma questão tão básica quanto isto, e o que eu ganho é um negativo. Maravilha.
Comment: Praticamente nada disso faz sentido, e tem vários erros, induzindo quem não sabe a achar que tudo aí é verdade, o que é bem pouco. Portanto se os problemas desta resposta não forem resolvidos, serei obrigado negativar para evitar que as pessoas se enganem.
Comment: Você pode usar a sessão de respostas ou de comentários para apontar estes erros, e eventualmente eles serem corrigidos (se eles existirem).
No entanto, foram estas questões que solucionaram meu problema, em parte no StackOverflow em inglês, em parte refletindo sobre as questões do C# e usando a documentação oficial. Tanto que consigo continuar os exercícios do material citado sem problemas.
Não posso comentar com você sobre orientação a objeto, porque é um assunto extenso, e foge do escopo do site. Já o problema do código foi resolvido.
Comment: Aqui não é fórum mais também não é bola de cristal. Quando algum membro qualquer citar os erros, eu naturalmente os corrigirei. Não tenho problemas com isso. O negativo (que foi meu) tem mais relação com o problema proposto, do que com a coerência do conteúdo. Não voto em um post porque acho ele bom. Voto se ele estiver correto em relação ao problema. É um critério diferente que uso, diferente de muitos membros, e isso não é um problema para mim. Você domina bem o assunto, e isso é louvável. Mas infelizmente não tem relação prática com o problema citado.
Comment: Leia minha resposta, está tudo lá o que está errado. Não corrigir é um direito seu. Justamente por não ser bola de cristal, só você poderia responder do jeito que você queria. Eu respondi o que é útil para todos. Minha resposta resolve 100% dos problemas relatados na pergunta, não resolve o que não está na pergunta.
Comment: Eu vou deixar em aberto. Porque sua postagem não ajudou muito a resolver meu problema (que já foi solucionado, com outras informações).
Aqueles que passarem pelo mesmo problema decidirão. Pelo menos a sua edição da pergunta ficou boa. A postagem ficou menos prolixa.


A geometry problem seeking for proof

Question: Circle $\odot O_1$ is tangent with circle $\odot O_2$ at $P$. Two tangent lines $AE$ and $AF$ of circle $\odot O_2$ meets circle $O_1$ at $B$, $G$ and $C$, $H$, respectively. $D$ is the in-center of $\triangle ABC$. $DP$ meets $BC$ at $I$, $EI$ meets $AO_2$ at $J$.
Here is a figure:

Prove:

$E$, $B$, $D$, $P$ are concyclic
$CJ\perp AO_2$
Comment: It's intended that no further reference beyond their definition is made to $G$ and $H$, right?
Comment: Yes, $G$ and $H$ are of no use in the problem statement. I don't know if it will be important to the proof or not, because I don't know the answer although I spend some days on it.
Answer: This is a solution for part 1. I haven't thought about part 2 yet.
The following text may not be very rigorous. To be more specific, the solution may rely on the picture a bit. For example, it may implicitly use the fact that points $P$, $E$ and $F$ all lie on the same side of line $BC$, simply because it looks that way on the picture. I'm afraid that if I make the solution any more rigorous, it will become absolutely incomprehensible.
Step 1. Build $P'$ and several other new points.
We will forget about point $P$ and the bigger circle $\odot O_1$ for a while, and focus on the triangle $\triangle ABC$ and the smaller circle $\odot O_2$. Consider the circumcircle of $\triangle EBD$. It intersects $\odot O_2$ at point $E$. There must be a second point where these two circles intersect. Let us denote that point by $P'$.
Clearly, $E,\,B,\,D,\,P'$ are concyclic. Our plan is simple: to prove that $P=P'$. To do this, we'll construct several more lines and points. Let us denote by $Q$ the second point where line $P'D$ intersects $\odot O_2$. Let $B'$ and $C'$ be the points of intersection of $O_2$ with $P'B$ and $P'C$ respectively. You can see all these on the figure:

Step 2. Explore the properties of the newly constructed objects.
The objective of this step is to prove that $BC||B'C'$. We will do this by some simple angle chasing.
First of all, since $EBDP'$ is an inscribed quadrilateral,
$$
\angle EP'Q=\angle ABD = 1/2 \angle ABC.
$$
It is quite easy to see that
$$
\angle EP'F = 90^{\circ} - 1/2 \angle BAC = 1/2(\angle ABC + \angle ACB).
$$
From this we have
$$
\angle FP'D = 1/2 \angle ACB = \angle ACD,
$$
so $FCDP'$ is also an inscribed quadrilateral.
So, we have two inscribed quadrilaterals $EBDP'$ and $FCDP'$. From the first one we know that $\angle BED = \angle BP'D$ and from the second that $\angle CFD = \angle CP'D$. It is obvious that $\angle BED = \angle CFD$ (because $\triangle AED = \triangle AFD$), therefore $\angle BP'D = \angle CP'D$. To put it in different letters, $\angle B'P'Q = \angle C'P'Q$. This in turn means that $\angle B'O_2Q = \angle C'O_2Q$, which means that $B'C' \perp O_2Q$. Now to prove that $B'C'||BC$, it only remains to prove that $O_2Q \perp BC$.
But this is easy. We already know that $\angle EP'Q = 1/2 \angle ABC$. Also, $\angle EP'Q = 1/2 \angle EO_2Q$. So $\angle EO_2Q = \angle ABC$. Since $O_2E \perp BA$, it means that $O_2Q \perp BC$, qed.
Step 3. Prove that $P=P'$.
Alright, we now know that $BC||B'C'$. From here it will be quite easy to prove that $P=P'$.
Since $BC||B'C'$, there exists a homothety $f$ with center $P'$ that sends line $B'C'$ to line $BC$. Clearly, $f(B')=B$ and $f(C')=C$. Let us denote $\odot O'_1 = f(\odot O_2)$. Since $\odot O'_1$ is the image of $\odot O_2$ under a homothety with center $P'$, circles $\odot O'_1$ and $\odot O_2$ are tangent at $P'$. Also, since $B'$ and $C'$ lie on $\odot O_2$, $B$ and $C$ lie on $\odot O'_1$.
Let us revise what we have established. We have two circles $\odot O_1$ and $\odot O'_1$. Both of them contain points $B$ and $C$ and both of them are tangent to $\odot O_2$ at points $P$ and $P'$ respectively. But from this it is already clear that $\odot O_1$ and $\odot O'_1$ are the same, and so are points $P$ and $P'$. Done!

A geometry problem seeking for proof


how to Get the Listview on select item in the spinner

Question: Actually i am developing an application which will implement all CURD operation.
My application consist of spinner,Listview,textbox.
Now what i want is, for updating operation , i need to get the values from the listview by selecting.
I don't know how to display the selected values(from Listview) in the Spinner.
Here is my spinner coding
sppriority = (Spinner) findViewById(R.id.sp_priority);
public void addNewTask(View view) {
HashMap<String, String> queryValues = new HashMap<String, String>();
queryValues.put("priority", sppriority.getSelectedItem().toString());

sppriority.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
Task = adapter.getItemAtPosition(position).toString();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
});

and this is Listview on click code:
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

lvpriority = (TextView) view.findViewById(R.id.lvpriority);
String vallvpriority = lvpriority.getText().toString();

Intent objIndent5 = new Intent(getApplicationContext(),addinbox.class);
objIndent5.putExtra("lvpriority", vallvpriority);
}

This is how i used which is not working:
 **if(animalList.size()!=0) {

    sppriority.setText(animalList.get("priority"));
    }**

        public void editTask(View view) {
        HashMap<String, String> queryValues = new HashMap<String, String>();
        queryValues.put("priority", sppriority.getSelectedItem().toString());
        controller.updateTask(queryValues);
        }

Please Help me to get the selected item of listview to spinner.
Thanks in advance.
Answer: Here is an outline of a simple way:
1) Have a HashSet which is member of your activity, let us call it selectSet.
   //Initialize like this
   HashSet<String>selectSet=new HashSet<String>();

2) onItemClick of ListView, add item to selectSet.
     public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
        lvpriority = (TextView) view.findViewById(R.id.lvpriority);
        String vallvpriority = lvpriority.getText().toString();
        selectSet.add(vallvpriority);
     }

3) Create ArrayAdapter<String> spinnerAdapter=new ArrayAdapter<String>(context, resource);
4) Iterate through the HashSet and add items to the spinnerAdapter
     for(String priority: selectSet){
        spinnerAdapter.add(priority);
     }
5) Set the spinnerAdapter to your spinner:
     spppriority.setAdapter(spinnerAdapter);

Comment: Hi thanks for your quick replay...I have tried as you suggest but i didn't get the selected value into the spinner
Comment: @Appdev Try checking selectSet.size() and spppriority.getAdapter().getCount(), see whether they are populated properly. Are you getting any error?
Comment: @ Kartik_Koro..If you don't mind can you please guide me to where to use the code which you suggested.Because i used at  item click listener but throws error at add by red underline ("The method add(String) is undefined for the type String
")
Comment: @Appdev just write it after you set adapter to the spinner, but you should not be getting the error of "undefined for type String", since `spppriority.getAdapter()` will return an `Object` of type `SpinnerAdapter` and `selectSet` is a `HashSet`. Are you sure you initialized the HashSet properly? I added edit with initialization of HashSet.
Comment: @ Kartik_Koro ..Once again thanks for showing interest to help me.If you Don't mind is it possible for you to provide any Examples.Sorry to trouble you.i'm very new to android so only


Which orthogonal rotation matrices for diagonalisation

Question: We consider 2D orthogonal rotation matrices $R$. We consider a real matrix
$$A = \begin{pmatrix} a & b\\ b & c \end{pmatrix}.$$
I write that $B = RAR^T$ for some diagonal matrix $B$.
I would like to know for which values of $\theta$ (angle of rotation of $R$) that this is possible. To determine all the possible values of $\theta$ I tried expanding out the equation $B = RAR^T$ and equating, but it was incredibly difficult to infer what the possible values of $\theta$ would be. What is a better way to approach this question?
Comment: Have you computed the eigenvectors of $A$? Notice that $R^T B = A R^T$.
Comment: Yeah but they didn't give me much useful information - they were just large algebraic expressions @Joe
Comment: @Featherball Likewise, any expression for $\theta$ in terms of $a,b,$ and $c$ will also be a "large algebraic expression". If that's an issue, then maybe you're asking the wrong question.
Comment: @BenGrossmann For this part of the question, they don't permit us to use the fact that the diagonal entries of B are the eigenvalues of A, and that the columns of R form the eigenvectors
Comment: What do you mean "don't permit us to use the fact..."? There is no theorem you need to use to derive that fact. That fact comes straight from the equation $B=RAR^T$.  If the problem explicitly states not to use eigenvalues or eigenvectors to solve the problem, then you should have mentioned that in your post, let alone avoid the "eigenvalues-eigenvectors" tag.
Answer: The $2D$ rotation matrix $R$ is given by
$R = \begin{bmatrix} \cos \theta && - \sin \theta \\ \sin \theta && \cos \theta \end{bmatrix} $
Diagonalizing a symmetric matrix $A$ means find a matrix of eigenvectors $R$ such that
$A R = R B $
It is known that for any symmetric matrix, the eigenvectors are orthogonal to each other, so by choosing them to be of unit length, matrix $R$ will be an orthgonal matrix, in which case $R^{-1} = R^T $, hence
$ B = R^{-1} A R = R^T A R $
Now explicitly compute $R^T A R $
$R^T A R = \begin{bmatrix} \cos \theta  && \sin \theta  \\ -\sin \theta && \cos \theta \end{bmatrix} \begin{bmatrix} a && b \\ b && c \end{bmatrix} \begin{bmatrix} \cos \theta  && - \sin \theta \\ \sin \theta  && \cos \theta  \end{bmatrix} $
Multiplying the two right most matrices,
$R^T A R = \begin{bmatrix} \cos \theta && \sin \theta  \\ -\sin \theta && \cos \theta \end{bmatrix} \begin{bmatrix} a \cos \theta + b \sin \theta && -a \sin \theta + b \cos \theta \\ b \cos \theta + c \sin \theta && -b \sin \theta + c \cos \theta \end{bmatrix}  $
Which multiplies to
$R^T A R = \begin{bmatrix} a \cos^2 \theta + c \sin^2 \theta + 2 b \sin \theta \cos \theta &&  b (\cos^2 \theta - \sin^2 \theta) + (c - a) \sin \theta \cos \theta \\ b (\cos^2 \theta - \sin^2 \theta) + (c - a) \sin \theta \cos \theta && a \sin^2 \theta + c \cos^2 \theta - 2 b \sin \theta \cos \theta \end{bmatrix} $
Now we want the off-diagonal entries to be $0$, hence,
$ b (\cos^2 \theta - \sin^2 \theta) + (c - a) \sin \theta \cos \theta = 0 $
But $\cos^2 \theta - \sin^2 \theta = \cos(2 \theta) $ and $ \sin \theta \cos \theta = \frac{1}{2} \sin(2 \theta) $
Therefore, the equation becomes
$ b \cos(2 \theta) + \dfrac{1}{2} (c - a) \sin(2 \theta)  = 0 $
From which,
$ \tan(2 \theta) = \dfrac{ 2b }{ a - c} $
i.e.
$ \theta = \dfrac{1}{2} \tan^{-1} \left( \dfrac{2b}{a - c} \right) $


Specify all the singularities of $g(z)$

Question: I am working on some past exam questions, and I just had a question about an intuitive way to know where the singularities of a complex function are.
For example for the function $$g(z)=\frac{1}{z^3+1}$$
The singularities are at: $z=-1$ and $z= \frac{1 \pm i\sqrt{3}}{2} = e^{\pm \frac{i\pi}{3}}$
The root at $-1$ is obvious, but the second and the third roots at $e^{\pm \frac{i\pi}{3}}$ do not come naturally to me. How can you tell by looking at the function, what these singularities would be?
Many thanks!
Comment: The zeros of $z^3+1$, that is, the cube roots of $-1$. With a little experience, one knows them asleep.
Answer: The singularities in this case occur where $z^3=-1$. The solutions will form an equilateral triangle in the complex plane. It's easy to observe the $-1$ vertex of this equilateral triangle, which leads you quickly to the other two vertices $\omega_6$ and $\omega_6^5$ where $\omega_6$ indicates the $6$-th primitive root of unity, (so $\omega_6=e^{2\pi i/6}$).
Answer: For $z_1=-1$, we have
$$(-1)^3+1=0$$
For $z_{2,3}=e^{\pm \frac{i\pi}{3}}$, we have
$$\left( e^{\pm \frac{i\pi}{3}}\right)^3+1=\left( e^{\pm (i\pi)}\right)+1=(-1)+1=0$$

Specify all the singularities of $g(z)$


Can I set the GOPATH using the go command line tool?

Question: I would like to set GOPATH using the go tool upon compilation, just like adding an include path in C/++. I want the gopath to be used only within a certain project. Can this be done without setting an environment variable?
Comment: On unix, prefix the `go` command with setting the env var, e.g. `GOPATH=XXX go build .`
Comment: @icza thats a solution, but I would like to refrain from using environment variables in general. Plus, I'm on windows :)
Comment: You can use `go env -w GOPATH="..."`. That is not a system environment variable, but that is a global setting.
Comment: `go env` has `-w` flag and `-u` flag. `-w` sets a Go environment variable and `-u` unsets it. However, there does not seem to be a way to combine it into a single command while building, so you'll need to manually set it up, run the build, then unset it.
Comment: Why do you want to set the GOPATH at all (and even per projekt)?
Comment: And as @TehSphinX noted, this may cause problem if there somehow other build process is caught between the set and unset, as it is global setting.
Comment: @TehSphinX so if I do it your way, the environment variable will 'go out of scope' after the command ends?
Comment: @TehSphinX because I like it when all of my dependencies are in the same location, in my repository.
Comment: No, it is a global setting that stays until set otherwise.
Comment: @TehSphinX is there a way to make it a 'local' environment var?
Comment: @Serket: Have you looked into working with Go modules? That is the correct way and there is no need to manipulate the GOPATH at all.
Comment: @TehSphinX No I haven't. Could you explain or provide some resources for reference?
Answer: Instead of trying to have a GOPATH per project to separate dependencies, work with Go modules.
A short intro on Go modules: https://ncona.com/2020/10/introduction-to-golang-modules/
Indepth, official intro: https://blog.golang.org/using-go-modules

My intro:
In your repository call go init yourModuleName to start working with go modules.
Once initialized, to me the most important command is go mod tidy. You call that and it cleans up your go.mod/go.sum files, removing what is not needed and adding what is needed.
To add a new dependency call go get dependencyname from within your project folder to add it to your go.mod file and be able to use it in your code.
To update a dependency, just call go get dependencyname again and it will update the version to the latest available in go.mod file.


Adaptação de Código VBA para buscar fotos de uma pasta

Question: Boa tarde.
Tenho uma macro, o qual busca numa planilha o nome da foto (ex: IMG0102.JPG), busca numa pasta predefinida a foto relacionada e a insere na célula que está o nome da foto.
Contudo, necessito atualizar essa planilha todos os dias com novas fotos, no entanto toda vez que executo a macro ele duplica todas as fotos que eu já havia inserido. Portanto, necessitaria que esse macro pulasse cada célula com foto (para não duplicar as que já tem) e seguisse somente para as células sem fotos
Segue exemplo da planilha:

Segue a macro que procura a célula com o nome da foto e procura na pasta:
    Sub InserirFotos()
imgpasta = "xxxxxxxxx\" ' caminho da pasta das fotos

For i = 2 To 1000 'Numero das Linhas ' inicio e fim para inserir fotos
For j = 28 To 35 'Numero das Colunas ' inicio e fim das colunas de onde estao os nomes das fotos

        imgleft = ActiveSheet.Cells(i, j).Left
        imgtop = ActiveSheet.Cells(i, j).Top
        imgwidth = ActiveSheet.Cells(i, j).Width
        imgheight = ActiveSheet.Cells(i, j).Height
        imagem = Trim(ActiveSheet.Cells(i, j).Value)

    If imagem <> "" Then
    If Dir(imgpasta + imagem) <> "" Then
        ActiveSheet.Shapes.AddPicture imgpasta + imagem, True, True, imgleft, imgtop, imgwidth, imgheight
    End If
    End If

Next j
Next i

    ActiveSheet.Shapes.SelectAll
    Selection.Placement = xlMoveAndSize

End Sub

Comment: Veja [esta resposta](https://pt.stackoverflow.com/a/290851/75104)
Comment: Meu caro, estou meio corrido aqui e não olhei o código, mas, conforme você disse que esta funcionando, seria mais fácil você criar uma nova coluna tipo Estatus, e ao gravar a imagem esta coluna recebe um valor entre 0 e 1. Onde 0 não tem foto e 1 tem foto. Quando for analisar o código para gravar a fotos verifica o estatus primeiro para depois inserir a foto. Tente aí, caso não consigo, vou dar uma olhada no código.
Comment: Bom dia Kevin Valente, Criei o código pra você, espero que de certo. Obs.: Tentei colocar o código aqui, mas, tive alguns problemas com o código, prefere então inserir o link para download. CRIANDO E ATUALIZANDO LISTA DE IMAGENS DA PASTA DO WINDOWS. LINK PARA DOWNLOAD DO ARQUIVO: https://drive.google.com/open?id=1poR5-FSLko3-AcHKrHxQKAG9u9BYg5Bm [![inserir a descrição da imagem aqui](https://i.stack.imgur.com/8YEqc.jpg)](https://i.stack.imgur.com/8YEqc.jpg)
Comment: Você deve sempre colocar o código diretamente na sua resposta, porque se esse link se quebrar, no futuro, sua resposta não terá mais utilidade.
Comment: Tentei colocar, mas, a própria página da Stackoverflow confundo o que é código com comentários, mistura linhas de códigos e retira linhas de código passando a ser uma escrita na página. Por isso postei o link. Mas, se conseguir resolver este problema ou me mostrar como resolver posto o código aqui.
Comment: Depois de inserir o código no seu texto você pode selecionar todas as linhas de código e clicar no botão `{ }` (Amostra de código), ou você pode também acrescentar manualmente 4 espaços no início de cada linha de código, assim o editor já saberá que aquele trecho é de código, e fará a formatação adequada. Ou então, se não conseguir, posta de forma errada mesmo, que depois alguém edita a sua mensagem para arrumar a formatação.
Comment: Favor ler [como editar código](https://pt.stackoverflow.com/editing-help) e editar a sua resposta
Answer: Todos os seus arquivos estão passando por aqui:
If imagem <> "" Then
    If Dir(imgpasta + imagem) <> "" Then
        ActiveSheet.Shapes.AddPicture imgpasta + imagem, True, True, imgleft, imgtop, imgwidth, imgheight
    End If
End If

Sugestão rápida:
If imagem <> "" Then

        If Len(Dir(imgpasta + imagem, vbDirectory) & "") = 0 Then

            ActiveSheet.Shapes.AddPicture imgpasta + imagem, True, True, imgleft, imgtop, imgwidth, imgheight

        End If

    End If

Comment: Boa tarde, amigo. Substitui pela sua sugestão, no entanto não puxa as fotos da pasta. Sabe o que pode ser?
Comment: Só para entender, é uma lista que diz quais imagens tem na pasta?
Comment: O macro insere as imagens conforme nomeação das células dentro da matriz selecionada.
Answer: Criei o código pra você, espero que dê certo.
CRIANDO E ATUALIZANDO LISTA DE IMAGENS DA PASTA DO WINDOWS.
LINK PARA DOWNLOAD DO ARQUIVO COMPLETO: https://drive.google.com/open?id=1poR5-FSLko3-AcHKrHxQKAG9u9BYg5Bm

'--- INSERINDO E ALTERANDO FOTOS
'--- by firstname.lastname@example.com
'--- versão 1.0  }

Option Explicit
Public Cod         As String
Public UCell       As Range
Public Nome1       As String
Public Nome2       As String
Public strFolder   As String
Public strFileName As String
Public objPic      As Picture
Public rngCell     As Range
Public CPasta      As String

Sub InserirImagens()

    Set UCell = Range("E1048576").End(xlUp)

    [E2].Select
    Nome1 = ActiveCell.Value

    CPasta = [A2].Value 'Caminho das fotos
    strFolder = CPasta '"C:\Users\Jean Braga\Desktop\EXCEL IMAGENS\" 'altere o caminho para onde estão as imagens

    If Right(strFolder, 1) <> "\" Then
        strFolder = strFolder & "\"
    End If

    strFileName = Dir(strFolder & "*.jpg", vbNormal) 'arquivos jpg

    If Nome1 = "" Then
        PrimeiraFoto

    Else

    Do While Len(strFileName) > 0
        Selection.Offset(1, 0).Select
        strFileName = Dir
        Nome1 = ActiveCell.Value
        If Nome1 = "" Then
            Nome2 = strFileName
            strFileName = ActiveCell.Value
        End If

    Loop

    Selection.Offset(-1, -1).Select
    Cod = ActiveCell.Value
    Selection.Offset(1, 0).Select
    ActiveCell.Value = Cod + 1
    Selection.Offset(0, 1).Select
    ActiveCell.Value = Nome2
    Selection.Offset(0, 1).Select

    strFileName = Nome2

    If strFileName = "" Then
        MsgBox "FOTOS ATUALIZADAS"
        Selection.Offset(0, -2).Select
        ActiveCell.Value = ""
        Exit Sub

    End If

    Set objPic = ActiveSheet.Pictures.Insert(strFolder & strFileName)
    With objPic
        .ShapeRange.Top = ActiveCell.Top
        .ShapeRange.Left = ActiveCell.Left
        .ShapeRange.Height = 12.5
        .ShapeRange.Width = 23

    End With

    strFileName = Dir

    Do While Len(strFileName) > 0
        [D2].Select
        Set UCell = Range("D1048576").End(xlUp)
        UCell.Select
        Cod = ActiveCell.Value
        Selection.Offset(1, 0).Select
        ActiveCell.Value = Cod + 1
        Selection.Offset(0, 1).Select
        ActiveCell.Value = strFileName
        Selection.Offset(0, 1).Select

        Set objPic = ActiveSheet.Pictures.Insert(strFolder & strFileName)
        With objPic
            .ShapeRange.Top = ActiveCell.Top
            .ShapeRange.Left = ActiveCell.Left
            .ShapeRange.Height = 12.5
            .ShapeRange.Width = 23

        End With

        strFileName = Dir
    Loop

    End If

End Sub

Function PrimeiraFoto()

    ActiveCell.Value = strFileName
    Selection.Offset(0, -1).Select
    ActiveCell.Value = "1"
    Selection.Offset(0, 2).Select

    If strFileName = "" Then
        MsgBox "FOTOS ATUALIZADAS"
        Selection.Offset(0, -2).Select
        ActiveCell.Value = ""
        'Exit Sub

    End If

    Set objPic = ActiveSheet.Pictures.Insert(strFolder & strFileName)
    With objPic
        .ShapeRange.Top = ActiveCell.Top
        .ShapeRange.Left = ActiveCell.Left
        .ShapeRange.Height = 12.5
        .ShapeRange.Width = 23

    End With

    strFileName = Dir

    Do While Len(strFileName) > 0
        [D2].Select
        Set UCell = Range("D1048576").End(xlUp)
        UCell.Select
        Cod = ActiveCell.Value
        Selection.Offset(1, 0).Select
        ActiveCell.Value = Cod + 1
        Selection.Offset(0, 1).Select
        ActiveCell.Value = strFileName
        Selection.Offset(0, 1).Select

        Set objPic = ActiveSheet.Pictures.Insert(strFolder & strFileName)
        With objPic
            .ShapeRange.Top = ActiveCell.Top
            .ShapeRange.Left = ActiveCell.Left
            .ShapeRange.Height = 12.5
            .ShapeRange.Width = 23

        End With

        strFileName = Dir

    Loop
End Function


overriding a function within the jquery validation plugin

Question: I am using the jquery form validation plugin to validate a long form. If a user submits the form with multiple fields that fail to validate, the cursor returns to the last field that did not pass. Instead, I want the cursor to be returned to the first field in the form that failed validation. Rather than modifying the plugin, I would like to override focusInvalid, which is nested inside "prototype: {...}":
focusInvalid: function() {
    if( this.settings.focusInvalid ) {
        try {
            $(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible").focus();
        } catch(e) {
            // ignore IE throwing errors when focusing hidden elements
        }
    }
},

I've tried adding my own version of focusInvalid within the following, but I haven't been able to get that to work:
$("form#user-register").validate({. . .});

Any pointers?
Answer: You can disable the selection of the first invalid input with the focusInvalid option. You can then use the invalidHandler option to set a custom function that selects the first element in your form. The invalidHandler option is the function that the plugin calls when an invalid form is submitted.
Example below:
$("form#user-register").validate({
     invalidHandler: function(form, validator){
         $(validator.invalidElements()[0]).focus();
     },
     focusInvalid:false
});

Comment: Thanks, I didn't know about invalidHandler. The code above is close to what I need; however, I'd like the user to be returned to the first *invalid* field.

I thought it would be something along the lines of:

    invalidHandler: function(){
      $(this.errorList[0].element).filter(":visible").focus();
    },
    focusInvalid: false

. . . but I haven't been able to get that to work. Any further points?

Thanks!
Comment: Updated. You were on the right track with what you were doing. You can still filter use the `:visible` filter if you want but it would only be needed if you are validating hidden inputs.


Prove $\Bbb Z/n\Bbb Z$ is not a domain

Question: If $n>1$ is not a prime number,
$\mathbb Z/n \mathbb Z$ is commutative ring,
where $n>1$ is a fixed natural number,
then $\mathbb Z/n\mathbb Z$ is not an integral domain.
natural number is either a prime number or a product of two numbers...
integral domain is  $ac=ab$, then $b=c$ ($a$ is not $0$) its mean, zero divisor does not work in The law concellation.
If $\mathbb Z/n\mathbb Z$ has zero divisor, then this proof will be easy.
But how to prove $\mathbb Z/n\mathbb Z$ has zero divisor?
Comment: If $n$ is not prime there are $n_1$ and $n_2$ such that neither one is equal to $1$ and $n_1n_2=n$.
Comment: (For the record, this is not linear algebra)
Answer: If a number $n$ is the product of two numbers $a$ and $b$ where both are not equal to 1, which is possible since $n$ is not prime, then the residue classes of $a$ and $b$ are both nonzero but their product is zero mod $n$.

Prove $\Bbb Z/n\Bbb Z$ is not a domain


Commutators polynoms Algebra

Question: Define the commutator $[a, b] := ab − ba$.
I have to show:
if $[a, b]=0$ follows $[f(a),g( b)]=0$ where $f,g$ are polynomials in the ring $K[X]$.
my idea:
$f(a)=a_1+a_2+\cdots+a_n$,
$g(b)=b_1+b_2+\cdots+b_n$,
then $[f(a),g(b)]=a_ib_i-b_ia_i=0$.
Answer: You don't know what $f$ and $g$ are, and you can't just pick one that you want. It suffices though to show that for all $i,j\geq 0$ we have $[a^i,b^j] = 0$ because the bracket is linear. We have that
$$ab-ba = 0$$
so
$$ab = ba$$
Hence, by induction you can show that
$$a^ib = ba^i$$
since
$$a^ib = a^{i-1}ba$$
and hence by a second induction we get
$$a^ib^j = b^ja^i$$
hence
$$[a^i,b^j] = 0$$

Commutators polynoms Algebra


Is there a way to make a if(null) do something

Question: I have a hashmap of States and capitals
Currently a user inputs the state and it will give them the corresponding capital
and then they will type done when they want to kick out of the program
Is there a way to make an if statement that would take the null that the hashmap would send if there was no said state in it?
Like if I ask for Canada it will return null because there is no state named Canada.
Is there a way to use the null it sends back in a for loop so I can do something like
if(null)
{
   say that that isn't a capital
}
else
{
   say the capital of what was inserted
}

Comment: Do you mean like `if (capital == null) {` - or did I misunderstand?
Comment: yes, Hovercraft got it, thanks for the help guys
Answer: yes, simply do what you are asking:
String capital = stateMap.get(testValue);
if (capital == null) {
   // error message
   System.err.printf("%s is not a valid state, please try again%n", testValue);
} else {
   // output a valid result
   System.out.printf("The capital of %s is %s%n", testValue, capital);
}


Scheme : How to quote result of function call?

Question: Is it possible to quote result of function call?
For example
(quoteresult (+ 1 1)) => '2
Comment: Althought it is a very basic question, it is very hard to google any learning materials for scheme.
Comment: [Structure and Interpretation of Computer Programs](https://mitpress.mit.edu/sicp/), [How to Design Programs](http://www.htdp.org).
Answer: At first blush, your question doesn't really make any sense. "Quoting" is a thing that can be performed on datums in a piece of source code. "Quoting" a runtime value is at best a no-op and at worst nonsensical.
The example in your question illustrates why it doesn't make any sense. Your so-called quoteresult form would evaluate (+ 1 1) to produce '2, but '2 evaluates to 2, the same thing (+ 1 1) evaluates to. How would the result of quoteresult ever be different from ordinary evaluation?
If, however, you want to actually produce a quote expression to be handed off to some use of dynamic evaluation (with the usual disclaimer that that is probably a bad idea), then you need only generate a list of two elements: the symbol quote and your function's result. If that's the case, you can implement quoteresult quite simply:
(define (quoteresult x)
  (list 'quote x))

This is, however, of limited usefulness for most programs.
For more information on what quoting is and how it works, see What is the difference between quote and list?.
Comment: I  need to quote the result because I am building a a quoted representation of scheme program based on input. I will eval it once it is built. Before that happens, I have to quote every list inside to make sure the eval function doesn't try to apply the list head on its tail.
Comment: @FordO. So you are saying you want the result to be the *list* `(quote 2)`? That is, the result of evaluating the expression `(list 'quote 2)`?
Comment: @FordO. Why do you evaluate the forms in the first place? If you nkow what to do `quoteresult` on I guess you could just skip evaluating them in the first place?


Find $f(x)$ such that $f(\frac{3}{x})+f(\frac{x}{2})=\frac{9}{x^2}+\frac{x^2}{4}-2$

Question: How to find $f(x)$ from below relation ?
$$f\left(\frac{3}{x}\right)+f\left(\frac{x}{2}\right)=\frac{9}{x^2}+\frac{x^2}{4}-2$$ I have two question about this .I find $f(x)=x^2-1$  that work fine ,but
$\\(1)$ how can be sure that there is no other solutions ?
$\\(2)$ How can find $f(x)$ in general ?
Comment: You have to specify the domain. Otherwise there is a problem when $x=0.$
Comment: @JohnWatson: Also $g\left(\sqrt{\dfrac32}x \right)=h(x)$ gives us a more symmetric version of this equation $$h\left(x\right)+h\left(\dfrac 1x\right)=0.$$
Comment: An explicit example of another solution is $f(x) = (3/2) x^{-2} - 1$.
Comment: Perhaps it would be easier if you put $g(x) =f(x)-x^2+1$. Then your equation became: $$ g\Big({3\over x}\Big) +g\Big({x\over 2}\Big) =0$$
Answer: If $f$ is analytic, we can expand it in a Laurant Series:
$$f(x)=\sum_{n=-\infty}^\infty a_nx^n.$$
Then $f(3/x)+f(x/2)=\sum_{n=-\infty}^\infty 3^na_nx^{-n}+2^{-n}a_nx^n.$
Your functional equation implies that for $n\notin (-2,2,0)$:
$$3^{-n}a_{-n}+2^{-n}a_n=0,$$
You can also work out the coefficients $a_0,a_{\pm 2}$:
$2a_0=-2 \Rightarrow a_0=-1$
$$3^{-2}a_{-2}+2^{-2}a_2=1/4$$
$$3^{2}a_{2}+2^{2}a_{-2}=9,$$
which are the same equation, so $a_2=1-4a_{-2}/9$. So even without the rest of the $a_i$, you can still form an infinite family of solutions:
$$f(x)=\frac{c}{x^2}+(1-4c/9)x^2-1.$$


How to allow users to post content and easily overrule its default access settings?

Question: On our website, we have a content type ("news"), which includes both public and private items. Normally, posts will be viewable by authenticated users only. However, I want to allow people to post content that is viewed publicly. The way I would prefer to do this is with a simple checkbox during node creation, which allows the node to be public, and viewable for anonymous users.
So far, I've tried the Content Access module, but the interface it provides is too complicated; I only need a checkmark for "allow anonymous to view".
Answer: You can get this to work using a combination of the Rules module and the Content Access module, whereas the Rules module will automatically (behind the scenes) trigger the logic that's needed. The logic itself is entirely hidden for the user (author) and is equivalent to using the interface that you consider too complicated.
Here are some more details to get it to work:

Start from a rule that is similar to the example I included in my answer to "How to specify a Rules condition related to select list values?".
This sample rule uses a field named field_optionlist, with 3 possible values A,B,C. In your case you could use any other fieldname (to fit your naming conventions). And your field only needs 2 values, say Y (= yes, instead of A) and N (= no, instead of B). Some more tips to get you going:

Make sure to define this field (for your content type news) BEFORE importing the rule sample in item '1.' above (if not the import of the rule will fail).
If you use another machine name for that field, also edit the field name in the sample rule before importing it.
Adapt the Rules condition related to "value = C" to "value = Y" (to fit your case), and the message included in the Rules Action.

QA-test the intermediate result after completing step '2.': you should have a Drupal message show up when a news node is created with field value = Y (and not when it is not Y).
Use the integration of the Content Access module with the Rules module to create a Rules Action that updates the access of the node, similar to the Rules Action I included in my sample rule included in my answer to the question "How to revoke edit access to the node's author after publishing a node?". The actual settings to use for the content access module should match with the settings you seemed to already have tried (but which you consider as too complicated to have the node editor set them).

Refinement: if you really want a "checkmark" (instead of such yes/no selection field explained above), create a boolean field and rework the rule detailed above to use that field instead.
Bonus: if you ever need similar logic for another content type, just define the SAME field (with same machine name). After doing so, you should not have to change anything to the Rule as defined above. That's because of the "entity has field" condition ...
Comment: That sounds perfect! I'm going to work on this soon, will accept the answer as soon as it seems to work. One more question, as I'm not entirely sure how Rules works (though I assume this works): When the content is created in any other way than by a User (in this case, by a migration), will the rule still trigger?
Comment: As a side comment: While I've used Drupal sites with the content access interface before, and haven't had much issues with it then, for this website a large number of people will be able to make posts, without much regularity. Thus, I prefer not to get regular questions about which checks out of the 40 or so they had to check or uncheck.
Comment: Since the sample rule is using the Rules event "node_insert", it better also gets triggered as part of a migration. If not, then either it's a rules bug, or something wrong in your migration procedure. Which module are you using for such migration? something like migrate_d2d, or feeds? Anyway, let me know after you got it to work, ok?
Comment: Just `migrate`, with a custom migrate which extends that module with migrate hooks. I'll see if it works after I update the migration to include news items, but so far, creating and updating public and private items works perfectly. Thanks!


Difference between modes a, a+, w, w+, and r+ in built-in open function?

Question: In the python built-in open function, what is the exact difference between the modes w, a, w+, a+, and r+?
In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean.
Comment: The link you provided exactly defines the values.  What part about the link you provided could you not see or understand?  Could you clarify your question to explain what you didn't understand about the link?
Comment: is there no simple and single doc that explains what the + sign means?
Answer: The opening modes are exactly the same as those for the C standard library function fopen().
The BSD fopen manpage defines them as follows:
 The argument mode points to a string beginning with one of the following
 sequences (Additional characters may follow these sequences.):

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate file to zero length or create text file for writing.
         The stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.

Comment: NOTE:Python v3 adds a number of additional modes.  [link to docs](http://docs.python.org/3.3/library/functions.html#open)
Comment: Noted that `w` and `w+` both can do `The file is created if it does not exist`
Comment: am I right to say that the `+` doesn't do something consistent independent if it is `a`,`w` or `r`? Or am I failing to see the pattern? What is the pattern?
Comment: On Windows, `b` appended to the mode opens the file in binary mode, so there are also modes like `rb`, `wb`, and `r+b`. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written.
Comment: I believe you mean the fopen call in the C standard library (which is not a system call)
Comment: @CharlieParker: I believe the pattern is "also do the other thing". So, `r+` doesn't just open the file for reading but also for *writing* and `w+`, in turn, doesn't just open it for writing but also for *reading*. Similarly for `a+`.
Comment: @johnstamos > Why does w+ exist?. Because you might want to do a read with the same file pointer before closing it.
Comment: Why are the default Python docs so crappy? https://docs.python.org/2/library/functions.html#open
Is there a nice clean set of docs for the built-in functions like the BSD manpage you linked to?
Comment: Indeed there are significant differences between the two. Ex: 'a+' in sys call positions the stream at beginning of file, in std lib it positions at end. Fixing link...
Comment: @drAlberT then of course this first comment in the docs saying it trucates to zero is redundant and thus prone to confusing the reader. It leads to the very natural question as to why the "to zero" was clarified in one and not the other...regardless, thanks for the comment.
Comment: `a` does not create a file if it doesn't exit. `a+` surely does.
Comment: Why does w+ exist? I'm finding that the file is being truncated before I can read it. If I use "r" I can use readline() and get my first line. If I use "w+" readline() returns empty string.
Comment: @DirtyBit are you saying that the docs in the answer are wrong? They explicitly say `a` creates the file if it doesn't exist. `a+` seems to just add the ability to read as well as append, but it's not very clear.
Comment: These descriptions are somewhat incomplete in my opinion. e.g. `w+` says it truncates but then it doesn't clarify if what that means but in `w` it says it truncates to length zero. Am I suppose to assume the truncation is the same for both?
Answer: I noticed that every now and then I need to Google fopen all over again, just to build a mental image of what the primary differences between the modes are. So, I thought a diagram will be faster to read next time. Maybe someone else will find that helpful too.
Comment: For posterity: truncate means to overwrite from the beginning.
Comment: @CharlieParker That there are basically two file operations (read, write). Mode _r_ is primarily for reading, modes _w_, _a_ are primarily for writing. And **the plus sign enables the second operation** for a given mode (simply said).
Comment: @And I believe @Antti is referring to the property `Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar` which is somewhat stronger than just saying the *initial* position is the end.
Comment: The `a` description is **wrong**. The writes are always positioned at the end.
Comment: So the `+` basically means writing. That is weird that the `w` doesn't mean that but it means truncating...(after reading the next answer, it seems `w` writes over and `a` stands for appending. That makes more sense...)

Do you have any comments on file creation if it doesn't exist?
Comment: @MinhTran You are not overwriting existing contents, you are first throwing it away and then write as if there is nothing there. If the file contains the string `aaaaa` and I truncate and write `ttt` to the file, the result wouldn't be `tttaa`, but just `ttt`.
Comment: File creation happens for all methods _except_ `r` and `r+` (where you are assuming there IS a file to initially read...).
Comment: The plus does not mean "write". With "w" It means create or overwrite, where overwrite means make the file zero bytes to start with even if it had previously had more bytes of content.
Comment: for those who are wondering about the difference between `r+b` and `w+b`, from the version 3 [documentation](https://docs.python.org/3/library/functions.html#open):
`For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.`
Comment: `w+` doesn't allow reading the file before writing to it.
Answer: Same info, just in table form
                  | r   r+   w   w+   a   a+
------------------|--------------------------
read              | +   +        +        +
write             |     +    +   +    +   +
write after seek  |     +    +   +
create            |          +   +    +   +
truncate          |          +   +
position at start | +   +    +   +
position at end   |                   +   +

where meanings are:
(just to avoid any misinterpretation)

read - reading from file is allowed

write - writing to file is allowed

create - file is created if it does not exist yet

truncate - during opening of the file it is made empty (all content of the file is erased)

position at start - after file is opened, initial position is set to the start of the file

position at end - after file is opened, initial position is set to the end of the file

Note: a and a+ always append to the end of file - ignores any seek movements.
BTW. interesting behavior at least on my win7 / python2.7, for new file opened in a+ mode:
write('aa'); seek(0, 0); read(1); write('b') - second write is ignored
write('aa'); seek(0, 0); read(2); write('b') - second write raises IOError
Comment: Why is there no "Create file if it doesn't exist. If it does exist, position at start, enable read and write"? This is the most obvious use-case for me: I'm storing data in a file. If the file's not there, create it instead of erroring. If there's data in the file I want to read it all from the top, update some stuff then completely re-write the file from 0 for the NEXT TIME I load it. I use `open(file,'a'); close(); open(file,'r+')` to accomplish this.
Comment: @CharlieParker It means that all content of the file is erased (file is made empty)
Comment: What does "truncating" mean in this context?
Comment: What about updating the table, to include 'x' for Python 3?
Comment: @pinhead What you are describing is more appropriately handled by opening the file in read mode, loading the contents into memory, and closing it, then opening it afterwards in write mode to write out when you're done. I assume from the use case that you describe that you want the whole file in memory, and this way you don't corrupt the file in case your program terminates before it has time to save and exit.
Comment: You might want to add a note that with `a` and `a+` writes will *always* happen at the end of the file, irrespective of whether one manually moves the pointer using `seek()`.
Comment: @industryworker3595112 as @NikosAlexandris says, the table could include the `x` option introduced in Python 3.3+. I have a (rejected) edit which I hope suffices.
Comment: @pinhead the reason is this: why position at the start if you are writing and file already exists? Wouldn't that start overwriting contents? a+ will keep the file pointer at the end for this reason. I can think of one reason to open in read+write mode and create if not exists and also have random access for one reason and that is a fixed-size shared memory mapped file.
Comment: @balu thanks. I didn't know that. Thanks. After some testing - I'm stunned. Seems `a` modes do not play well with `seek` movements.
Comment: This is still accurate in Python 3.8.1. I expanded your table over at https://dev.to/codemouse92/dead-simple-python-working-with-files-lmg (and in my upcoming book); you're welcome to incorporate my changes in if you like.
Comment: I had the same question as @pinhead, and I don't think @krs013 answered it. You can use `a+` to *create* a file that might not exist and use `.seek(0)` to *read* (not write) from the beginning. That way you don't have to use `open(file,'a'); close(); open(file,'r+')`.
Answer: The options are the same as for the fopen function in the C standard library:
w truncates the file, overwriting whatever was already there
a appends to the file, adding onto whatever was already there
w+ opens for reading and writing, truncating the file but also allowing you to read back what's been written to the file
a+ opens for appending and reading, allowing you both to append to the file and also read its contents
Comment: What does "truncating" mean in this context? Does it mean to delete the old data if it had some? Or something else more specific?
Comment: @CharlieParker: Correct - it means that all data in the existing file will be dropped and we begin writing from the beginning of a now-empty file.
Answer:

r
r+
x
x+
w
w+
a
a+

readable
√
√

√

√

√

writeable

√
√
√
√
√
√
√

default position: start
√
√
√
√
√
√

default position: end

√
√

must exist
√
√

mustn't exist

√
√

truncate (clear file) on load

√
√

Always write to EOF

√
√

Mode

t (default)
b

str (io.TextIOBase)
√

bytes (io.BufferedIOBase)

√

If no mode is selected; text mode (t) is used. As such r is the same as rt.
Comment: What does "Always write to EOF" mean?
Comment: @qff EOF stands for End Of File. The "always" means even if you `seek(0)` (move the cursor to the start of the file) then when you `write("foo")` the file will write to the end of the file. Hence why it's called "append" mode. You always append to the end of the file.
Comment: @Vopel Yes, I have rejected your edit twice. The edit changed the Markdown with no appreciable benefit to the output, however you also mangled the second table tipping the edit closer to (unintentional) vandalism. "and then making a minor change was not cool" never happened. You should be able to see [the last edit is from May 6, 2023 by Good Pen](https://stackoverflow.com/posts/67558256/revisions). I see no reason to edit my answer, unless another mode for `open` is added.
Comment: @Vopel In my previous comment I mentioned two problems: 1. no appreciable benefit to the post, and 2. mangling the second table. Fixing the second issue still leaves the first issue. Your second and third edit don't have any appreciable benefit. If you can find something to improve the answer then feel free to edit, but trying to get the same changes to MD passed will just be met with me rejecting your edit.
Answer: I hit upon this trying to figure out why you would use mode 'w+' versus 'w'. In the end, I just did some testing. I don't see much purpose for mode 'w+', as in both cases, the file is truncated to begin with. However, with the 'w+', you could read after writing by seeking back. If you tried any reading with 'w', it would raise an IOError. Reading without using seek with mode 'w+' isn't going to yield anything, since the file pointer will be after where you have written.
Answer: I think this is important to consider for cross-platform execution, i.e. as a CYA. :)

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it'll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn't hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

This is directly quoted from Python Software Foundation 2.7.x.
Answer: I find it important to note that python 3 defines the opening modes differently to the answers here that were correct for Python 2.
The Python 3 opening modes are:
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
----
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (for backwards compatibility; should not be used in new code)

The modes r, w, x, a are combined with the mode modifiers b or t. + is optionally added, U should be avoided.
As I found out the hard way, it is a good idea to always specify t when opening a file in text mode since r is an alias for rt in the standard open() function but an alias for rb in the open() functions of all compression modules (when e.g. reading a *.bz2 file).
Thus the modes for opening a file should be:
rt / wt / xt / at for reading / writing / creating / appending to a file in text mode and
rb / wb / xb / ab for reading / writing / creating / appending to a file in binary mode.
Use + as before.
Answer: The particular doubt that many people get is 'What is the difference between r+ and w+ modes?
The r+ helps you read and write data onto an already existing file without truncating (Error if there is no such file).
The w+ mode on the other hand also allows reading and writing but it truncates the file (if no such file exists - a new file is created). If you are wondering how it is possible to read from a truncated file, the reading methods can be used to read the newly written file (or the empty file).
Cheers!


Which tables can i share in multilingual multi-site installation?

Question: I have a multi-site installation with different databases. I've shared i18n_; language; locale_ tables. On the main installation several languages work just fine.
But on the others sites which i am trying to use also with multilingual settings i can't get language switcher appear whatever i try. They don't want to use prefix between nodes. Translated nodes are connected but there's no way to switch between them.
Please could you give advice which tables am i able to use to have shared translations without problems?
Comment: Well the only thing i`ve managed to is completely delete all modules connected to multilingual site and reinstalled them. I`ve tried to share tables locale after that which caused problems. So as i see you can only import/export translations manually to each of the sites.
Answer: As i understood you almost cant use common tables on multi-site installation - i`ve been checking them one by one. First i configured all of sites - only the main site (from which tables were shared) could switch languages and translate nodes. On the others there were no switcher showing and translated nodes were not linking.
Maybe you can some, but still you got to have everything identical (starting from content types and endind with nodes)
Maybe i am wrong.


Google Chrome positioning issue

Question: I have a problem positioning some text in google chrome, I am trying to position
"Get Directions" and "Contact" side by side. This works fine in IE,Firefox and Opera but not Chrome. I know I should probably use floats but does anyone have any idea why isn't this working correctly?
(CSS)
    #main_container2{

    background-color: white;
    position:relative;
    left: 0%;
    top:0%;
    width:950px;
    height:985px;
    font-family:arial;
    font-size:36pt;

    }

(HTML)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href='green_machine.css'>
<title> test</title>

Get Directions

Contact

Answer: You use:
Get Directions

Contact

First element position: absolute and second element position: relative
Just set the both to absolute or relative
PS
I would have made it into a ul and li's
And either use float or display inline
Answer: First off, you don't need the left and top arguments on the main-container div, by default a positioned element is anchored top left.
To fix your problem though, you should try switching the second font tags position to absolute. Since the parent has a position (defined or not) the children's position will be within the parents container. Since you are trying to put them side by side, you should use position absolute on both elements.
Comment: Thanks ever so much. I need to go back and learn css positioning :(

Google Chrome positioning issue