Selenium WebDriver not finding the WebElements

Question: Below script i wrote navigates to the desired URL but, its not entering the values  for username and password. Xpath and css for both the fields are correct. Any idea whats going wrong here?
org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class websiteClass {

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://opensource.demo.orangehrmlive.com/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        driver.findElement(By.xpath(".//*[@id='txtUsername']")).sendKeys("Admin");
        driver.findElement(By.xpath(".//*[@id='txtPassword']")).sendKeys("admin");
        driver.findElement(By.xpath(".//*[@id='btnLogin']")).click();
    }

}

Answer: with version of geckodriver 0.18 driver.manage().window().maximize() throws exception (actually it's a geckodriver bug).
After removing two lines:
   driver.manage().window().maximize();
   driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

code works fine for me (program successfully login to website with geckodriver).
Also make sure that you set webdriver system property (before WebDriver driver = new FirefoxDriver();)
System.setProperty("webdriver.gecko.driver", PATH_TO_GECKO_DRIVER);

I also tried your code without any changes for ChromeDriver and it works fine.
If you still have issue, please post your geckodriver version and exception stack trace.
Comment: Thankyou Vasily. When i updated my geckodriver version from 0.11 to 0.18, code worked perfect.
Answer: it is working fine in the Firefox 43.0 and 2.51, I guess this is issue of Firefox browser. Either use gecko driver with selenium 3.3 jars or use Firefox 43.0 and 2.51 jars of selenium
use this for if you use chrome and update your chromedriver. For Firefox you need to change setproperty values only
System.setProperty("webdriver.chrome.driver", "E:\\software and tools\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
            driver.get("http://opensource.demo.orangehrmlive.com/");
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

            driver.findElement(By.xpath(".//*[@id='txtUsername']")).sendKeys("Admin");
            driver.findElement(By.xpath(".//*[@id='txtPassword']")).sendKeys("admin");
            driver.findElement(By.xpath(".//*[@id='btnLogin']")).click();

            driver.close();


How to check if valid excel file in python xlrd library

Question: Is there any way with xlrd library to check if the file you use is a valid excel file? I know there's other libraries to check headers of files and I could use file extension check. But for the sake of multiplatformness I wonder if there's any function I could use in the xlrd library itself that could just return something like false when trying to open the file and then notify the user.
I'm kind of new on Python so I tried getting something debugging the xlrd.open_workbook function with no success.
Answer: You can try to open workbook but in try/except block to catch XLRDError exception in case if file format not supported:
>>> from xlrd import open_workbook, XLRDError
>>> try:
...     book = open_workbook('test.txt')
... except XLRDError as e:
...     print e
...
Unsupported format, or corrupt file: Expected BOF record; found '--index-'

or use a simple function:
from xlrd import open_workbook, XLRDError

def test_book(filename):
    try:
        open_workbook(filename)
    except XLRDError:
        return False
    else:
        return True

Comment: I used the function, it works! thanks, I just would suggest you add xlrd. before open_workbook to your asnwer so other users will find this answer ready to go.


Beta vs beta-binomial why beta has higher AIC

Question: I am working with proportion data (very limited ~20 data points) for a response variable (RV), i.e. proportion of mature females out of total number of females sampled. The maturity is assessed by 6 distinct maturity stages.
I started out with a binomial distribution GLM (M3), which was overdispersed, I calculated the dispersion statistic to be ~115. Subsequently, I tried a beta distribution (M4), the model validation here suggested it was an okay fit (as okay as it can be with 20 dps).
However, upon reading this paper I realized that the beta distribution is not strictly a good fit for my RV, because the proportion is derived from discrete data, as opposed to continuous. The paper pointed me to the beta-binomial distribution (M5), which I had no issue running. After that, out of curiosity I ran AIC() on all three models to compare them. This was the result:
AIC(M3, M4, M5)
   df        AIC
M3  2 2335.20106
M4  3  -14.56873
M5  3  265.97071

My question is, why is the beta model (M4)seemingly performing so much better than the beta-binomial (M5) according to AIC? Is this due to overfitting? Or should I not have done the beta model in the first place because its wrong for my type of proportion data, and just ignore AIC?
Answer: If you are modeling the proportion directly (i.e. you are measuring $\frac{\text{count of mature females}}{\text{count of all females}})$ then the beta distribution will have a much better AIC than the other options.
The reason for this is that AIC is a penalized log likelihood, where the likelihood is the product of probabilities of the observations under the model. The key here is the the beta distribution is a probability density function for a proportion, whereas the binomial and beta-binomial are probability mass functions for a count out of some total count. The beta distribution gives probability densities for real numbers in the interval $[0, 1]$, whereas the binomial and beta-binomial give probabilities masses to positive integers in the set $\{0, 1, 2, ..., n_i\}$ (where $n_i$ is the total count for the $i$th observation).
Aside from the fact that probability masses and densities are on different scales (masses must be in $[0, 1]$, but densities can be in $[0, \infty)$), if you were to model the proportion directly the beta is the only one of the three choices that would be able to give valid likelihoods (a count can't be fractional). Thus the beta would naturally have a better AIC.
Despite this, if you have the actual count data and not just the proportion, you should use it. The probability parameter of a binomial distribution, and the shape parameters of a beta-binomial distribution can give you estimates for the proportions using the count data. You will likely get much better estimates using the count data, as you will not throw away information (e.g. the total count).
Comment: Thank you for the explanation!
Comment: Of course! Not a problem.


Normal subgroup of $GLn(\mathbb{C}$?

Question:
Is  the   subgroup of all complex  orthogonal matrix  are  normal subgroup of $GLn(\mathbb{C})$ ?

My attempt :  I know  that  in  real orthogonal matrix  its is false  take  $A=  \begin{bmatrix} 0 & 1\\-1 &0 \end{bmatrix}$ , $P=  \begin{bmatrix} 2 & 0\\0 &1 \end{bmatrix}$ that is $PAP^{-1} = B$ .Here $BB^T\neq  I$
Im confused in  complex  field
Any hints/solution
Comment: Your attempt makes no sense.  It is not clear what your example has to do with normal subgroups.
Comment: I can see that this is what you have done.  My question is what conjugating some orthogonal matrix has to do with normal subgroups of the set of orthogonal matrices (we can stick to real-orthogonal matrices for now).  It seems as though you do not understand the question being asked.
Comment: now that you've written your question clearly, your attempt makes sense.
Comment: oksss@Omnomnomnom  i just try to contradict the  statement in real orh=thogonal matrix
Comment: The statement is that every subgroup is normal.  What is the subgroup that you have defined, and how have you shown that it is not normal?
Comment: actually i  try to conjugating  some orthogonal matrix @Omnomnomnom here $A \in O(2)$
Answer: No. For instance, $GL_n(\mathbb R)$ is not a normal subgroup of $GL_n(\mathbb C)$. To see why when $n=2$, use the fact that, say,$$\begin{bmatrix}1+i&i\\i&1-i\end{bmatrix}.\begin{bmatrix}1&2\\2&3\end{bmatrix}.\begin{bmatrix}1+i&i\\i&1-i\end{bmatrix}^{-1}=\begin{bmatrix}3&2i\\-2i&1\end{bmatrix}.$$
Comment: The question seems to be about subgroups of the group of complex-orthogonal matrices
Comment: @Omnomnomnom Let us see what Jasmine has to say about this.
Comment: thanks u  @JoséCarlosSantos sir
Comment: i have  edited  my  question@Omnomnomnom
Comment: I am glad that the asker considers their question answered, but I don't see how this example answers the question; maybe I'm missing something.  What does $GL_n(\Bbb R)$ failing to be a normal subgroup of $GL_n(\Bbb C)$ have to do with the complex-orthogonal matrices failing to be a normal subgroup of $GL_n(\Bbb C)$?
Answer: Your answer for the real case works for the complex case as well.  You have an orthogonal matrix $A$ and a matrix $P \in \operatorname{GL}_n(\Bbb C)$ such that $A$ is complex-orthogonal (i.e. it satisfies $AA^T = I$), but $PAP^{-1}$ is not complex orthogonal.
Normal subgroups must be closed under conjugation, so the complex-orthogonal matrices do not form a normal subgroup.

Normal subgroup of $GLn(\mathbb{C}$?


Cucumber does not read data from scenario outline

Question: I have following scenario outline
<code> Background:
   Given customer is in hot or not page

 Scenario Outline: Hot article
  And customer enters <name>
  And submits
  And customer clicks thumbs up
  Then ensure the TBD

 Examples:
  | name |
  |  Elliot |
  |  Florian |
</code>
and following step implementation -
<code>@And("customer enters <name>")
public void customer_enters_name(String name) throws Throwable {
    // Express the Regexp above with the code you wish you had
    Thread.sleep(10000);
}
</code>
But when I execute test then I get following error -
You can implement missing steps with the snippets below:
<code>@Given("^customer enters Elliot$")
public void customer_enters_Elliot() throws Throwable {
  // Express the Regexp above with the code you wish you had
  throw new PendingException();
}

@Given("^customer enters Florian$")
 public void customer_enters_Florian() throws Throwable {
  // Express the Regexp above with the code you wish you had
  throw new PendingException();
}
</code>
Did I implement test steps wrong?
Comment: Try "" (in quotes) instead of
Comment: this works, could you mark your comment as an answer and I would accept it :)
Answer: Instead of
<code> Scenario Outline: ...
  And customer enters <name>
  ...
</code>
Do this (Note the double quotes)
<code> Scenario Outline: ...
  And customer enters "<name>"
  ...
</code>
Answer: Just to add, The same error arise when in the runner class ,we put the wrong package of the step class
<code>@CucumberOptions(glue = {"com.wrongpackage.step"})
public class TestRunner{

}
</code>
Step class should be present and the package should be correct.


modify date token in View to extract only year?

Question: We have a content type using a date field, in which the date is entered in the format mm/yyyy. An example entry might be 04/2016. In one particular View, we want to use only the Year value. It appears the token for this field is
[field_delivery_date-value]

In the Rewrite area for this View field, is there an operation that can be performed on the token in order to extract and display only the year value? Or would this need to be done in another way, not using tokens and the rewrite option?
Answer: Steps to get the just the year for Delivery Date field

Navigate to /admin/config/regional/date-time/formats page.
Click on Add Format button (/admin/config/regional/date-time/formats/add)
In the Format string text field add Y and save it.
Now add a date type by navigating to /admin/config/regional/date-time page.
Add a new date type and use the the format that we have added in the previous steps.
In the view select the type you want the date to be rendered.

So instead of Rewriting the output, you would directly get the year.
Hope that this will help you.
Comment: Thanks, this is helpful up to a point because I wasn't aware of that option to create a new format. However it doesn't provide the full path to what is needed, and I realize it's probably because the original date entry field is just a text field, not a date picker, in which the user is prompted to enter a date like 04/2016 for April 2016. It looks like that can't be re-rendered with a different date format. Maybe better to replace the original date entry method with a date picker, then this option you suggest would become available?
Comment: yepp that is recommended if you will be entering the date in it. It would be better if you make that field as a Date field instead of using the text field for  entering date.

Upvote this answer if you are satisfied with the Answer so that someone else can use this solution in case if they come across this problem.
Answer: In your view, click on your date field.
Note: In your Content Type your field needs to be a date field, text field won't work!
For formatter, select Custom.
For Date/Time Format, put Y

Note: In Drupal 8 there seems to be a bug, you will have to do this twice, as when you save the 1st time it does not change. In
  Drupal 7 it should work on the 1st try.


Having problems printing åäö (├Ñ ├à | ├ñ ├ä | ├ ├û)

Question: I can't print the swedish letters åäö.
#include <stdio.h>
#include <stdlib.h>

int main(void){
   printf("å Å | ä Ä | ö Ö");

   return 0;
}

The output I get is:

├Ñ ├à | ├ñ ├ä | ├ ├û

I don't understand what is wrong. I've searched google and stackoverflow, but nothing to be found. Maybe there is something wrong with UTF-8?
Other information that might be usefull:
I'm using Windows 10 and atom.
SOLUTION
Go to:
System language settings -> Administrative language settings -> Change system
 locale...
Now check the following box:
[Beta: Use Unicode UTF-8 for worldwide language support]
This fixed my problem and I am now able to use UTF-8 characters.
Comment: There is nothing wrong with utf-8, there is only something wrong with Windows. As far as I know, the windows terminal does not support utf-8. At least it didn't the last time I used it. I have heard some rumors that Microsoft was going to add support, but I don't think it has happened yet. If you are going to write terminal applications I only see four courses of actions: 1. wait for utf-8 support. 2. Wrangle with different extended ascii codepages or utf-16 3. Stick to 7 bit us-ascii 4. get a real os.
Comment: https://stackoverflow.com/q/1421811/11683? https://stackoverflow.com/a/50658001/11683?
Comment: I am assuming you can't change encodings, Unicode might be a better choice.  Windows has always been a mess when it came to encodings, but from what I remember, it has full support for unicode
Comment: Changing the language settings to Beta/UTF8 will break old ANSI programs, if you have any of them on your system. You should just use `SetConsoleOutputCP(CP_UTF8)` as suggested in the answer below, or use UTF16 which is the recommended method.
Answer: The Windows command window (terminal, console, whatever you call it) does support UTF-8 since several years, at least with Windows 7 based on my experiences. You need to set the code page:
mode con cp select=65001

Additionally you can set the output code page programmatically:
SetConsoleOutputCP(CP_UTF8);

Comment: Thank you for the help. Your suggestion was great, it didn't work for me, though it did set me on the right path towards the correct solution.

My solution was to do the following:

   System language settings -> Administrative language settings -> Change system locale...

   Now check the following box:

      [Beta: Use Unicode UTF-8 for worldwide language support]

This fixed my problem and I am now able to use UTF-8 characters.
Comment: Would you mind to tell us, how did it not work for you? Did you set a font with a big "enough" character set, for example?
Comment: Also change to `printf(u8"å Å | ä Ä | ö Ö")` and make sure your *.c file is saved in Unicode format.

Having problems printing åäö (├Ñ ├à | ├ñ ├ä | ├Â ├û)


NodeJS Async series not working sequentially

Question: I have the below code,
    var async = require('async'); var rest = require('restler');

    async.series([
        function(callback){
           rest.get('https://api.twitter.com/1.1/statuses/mentions_timeline.json').on('complete', function(result) {
              if (result instanceof Error) {
                console.log('Error:', result);
                this.retry(5000); // try again after 5 sec
              } else {
                console.log(result);
              }         });
            callback(null, 'one');
        },
        function(callback){
            console.log('2nd function');
            callback(null, 'two');
        }
        ],

// optional callback
        function(err, results){
               // results is now equal to ['one', 'two']
               console.log(results);
        });

I am expecting output like this,
{ errors: [ { message: 'Bad Authentication data', code: 215 } ] }
2nd function
[ 'one', 'two' ]

But am getting the below output,
2nd function
[ 'one', 'two' ]
{ errors: [ { message: 'Bad Authentication data', code: 215 } ] }

Rest request output always coming at last.
What is the correct way of doing this?
Answer:     function(callback){
       rest.get('https://api.twitter.com/1.1/statuses/mentions_timeline.json').on('complete', function(result) {
          if (result instanceof Error) {
            console.log('Error:', result);
            this.retry(5000); // try again after 5 sec
          } else {
            console.log(result);
             callback(null, 'one');
          }
       });
    },

rest.get is an asynchronous function. By calling it, you fire it off and continue blindly. Move your callback into rest.get's callback function.
Comment: Excellent, I didn't think this way, is there way I can identify which are asynchronous calls and which are synchronous calls?
Comment: Generally, if the call requires a callback function, then it is asynchronous.
Comment: There are very few synchronous calls in node and they are usuaully xxxSync() method name.  The area where you use the sync methods is in the file system module.
Comment: Yeah, I think I should understand the concepts in a better way. Thanks for the information.


Ordenar as chaves de um objeto simulando ORDER BY NOME ASC

Question: Em mysql no comando SELECT * FROM minha-tabela ORDER BY nome ASC a lista será retornada com todos os resultados ordenados de forma crescente com base na coluna nome, eu gostaria de saber como posso fazer o mesmo com um objeto js;
Exemplo:
Object
   1: Object
      nome: "Batista"
   2: Object
      nome: "Thiago"
   3: Object
      nome: "Joana"
   4: Object
      nome: "Ana"

Qual seria a função para reordenar as chaves do meu objeto por ordem alfabética com base na coluna nome para que o mesmo ficasse dessa forma:
Object
   1: Object
      nome: "Ana"
   2: Object
      nome: "Batista"
   3: Object
      nome: "Joana"
   4: Object
      nome: "Thiago"

Answer: Pelo comando sort fazendo a comparação da seguinte forma:

var obj = [{nome: "Batista"}, {nome: "Thiago"},
           {nome: "Joana"},{nome: "Ana"}];

//console.log(obj); // antes

obj.sort(function(a, b){
    var aa = a.nome.toLowerCase();
    var bb = b.nome.toLowerCase();
    if(aa < bb) return -1;
    if(aa > bb) return 1;
    return 0;
});

console.log(obj); // depois

Se no caso em particular for um objeto com vários objetos dentro, exemplo:

{0: {name:'a'}, 1: {name:'c'}, 2: {name:'b'}}

tem a maneira de pegar esses valores e tranformar em array com Object.values e aplicar o mesmo procedimento com o método sort, afinal é um array:

var obj = {0: {name:'a'}, 1: {name:'c'}, 2: {name:'b'}};

var objAsc = Object.values(obj).sort((a,b) => {
 if (a.nameb.name) return 1;
 return 0;
});

console.log(objAsc);

Referencias:

JavaScript Array sort() Method
Using an alphabetical sort()
Comment: Isso funciona para Objects? Pois estou testando aqui e diz object.sort is not a function, ou eu tenho que converter meu object para array?
Comment: Tem como você mostrar @LeoLetto o seu código na integra? No meu exemplo é um `array` de **objetos**
Comment: Acho que ai está o problema, pois o meu não é um array de objetos, e sim um objeto com outros objetos dentro
Comment: @LeoLetto eu quero ver esse Objeto de Objeto tem como colocar, talvez é um ajuste trivial aonde a ordenação fica, por favor poste ele pra mim ver!
Comment: Esse é o meu Object real as chaves devem ser reordenadas conforme o titulo que está marcado na imagem: http://imgur.com/a/5gGPr
Comment: Convertendo o Object principal para um array e aplicando sua função funcionou perfeitamente.
Comment: Entendo que essa resposta cabe para o seu caso @LeoLetto. No caso, no final, só transformar o array em objeto. Porque a única solução para ordenar objetos é transformar as chaves em array e depois voltar ao original convertidos (para ordenar as chaves de um obj por exemplo).
Comment: @LeoLetto são varias chaves e dentro vários arrays de objetos, se precisa ordernar todos?
Comment: Sim, mas transformando o Object principal em um array e aplicando sua função funcionou bem : http://imgur.com/a/6Dn8n
Comment: Poxa @LeoLetto verdade agora funfo certinho.


Wimbledon Tennis Championship 2004, women's single, semi-final (Sharapova vs. Davenport): July 1st or June 30th?

Question: I find multiple sources having both dates for this match: either 2004-06-30, or 2004-07-01. Wikipedia is no help in multiple articles, as single matches aren't broken down to dates.
I fear that from USA's perspective it was June 30th, while on location (London) it was already July 1st. But since agencies and article writers are still not paying interest in stating timezones I'm lost on this. Inspecting pictures is no help either, as sometimes "date created" means "date modified" due to improper metadata usage.
Maybe the match was paused by raining and continued the other day, but I haven't read that anywhere.

Additionally I'd also like to know the on-location dates of Sharapova's other matches during Wimbledon 2004, but that's more a bonus.
Answer: The ladies semi-finals at Wimbledon are, unless delayed, played on the second Thursday of the Championship so the match will have been on the 1st July. (The men's semi-finals follow on the Friday, followed by the ladies final on the Saturday). I don't think there are any situations in which the ladies semi-final would be pulled forwards to the Wednesday.
This is supported by the BBC News report of the match which is at 15:25 GMT on the 1st July.
Comment: The "**second Thursday**" is an important background knowledge that is stated nowhere - thanks for that! Are there similar rules for all other matches? The article is not that much of a help - it even states "*Last Updated*", which is never bound to its content. The content never mentions the date, or time - it could refer to any given past. When an article was written and/or published rarily helps identifying the actual time the action has happened.


Rendering a 'google_map_field' when referenced via entity reference field

Question: I have a content type with an entity reference field to another content type. We'll call the first content type A, and the other B.
In my node level template for A, I need to output a google_map_field (https://www.drupal.org/project/google_map_field) from referenced entity (B).
I'm outputting other fields from B by using:
node.field_entity_reference.entity.field_example.value
However, this does not work for the google_map_field. Lots of errors spit out, regarding parts of the google_map_field, such as lat, lng etc. I'm guessing this is because the module usually does some processing of this field, which isn't being done due to the nature of how I'm outputting it?
I need to work out how to tell Drupal to render it as a GoogleMapFieldType (I beleive).
Any guidance on this would be highly appreciated!
Thanks in advance.
Answer: I would recommend using a view mode to render out the referenced entity.
For instance, A's display settings is set to display B using the 'teaser' view mode. Then, you can configure B's teaser display to show what you want.
I know this doesn't answer your direct referenced entity value question, but this is how I would tackle this problem.
I hope that helps!
Comment: Just to clarify, I'm not using a view (sorry if I wasn't clear). If you're talking about adjusting the display settings of either A or B content types, that's also not going to help. The issue arises just to the type of the field.
Comment: Daniel, he's talking about "view modes", not "views", see /admin/structure/display-modes/view on your Drupal installation, and /admin/structure/types/manage/article/display.  See where it says default, RSS, teaser?  Those are "view modes".  You can select which field formatters and which fields you want to display per view mode.
Answer: The most out of the box way to display a referenced entity is this:
1) Create a custom view mode "google_map".
2) Set field_entity_reference to render the entity with that view mode.
3) Output the field from the content variable, like this:
 {{ content.field_entity_reference }}

In your case, as you're pulling raw values out in your question, it looks like you want the control that comes from having all of your variables (including those from a referenced entity) in one template.
You can do this in a preprocess hook.  For example in hook_preprocess_node() in your custom theme or module, you can assign the google map from the referenced entity to a variable:
 if ($node->field_entity_reference->isEmpty() === FALSE) {

    $referenced_entity = $node->field_entity_reference->referencedEntities()[0];

    $vars['google_map'] = $referenced_entity->field_example->view();

  }

If you want to pass a view module in to the view() method, you can do it like this:
$vars['google_map'] = $referenced_entity->field_example->view('default');

or
$vars['google_map'] = $referenced_entity->field_example->view('google_map');

Then in your twig, you would just access it like this:
{{ content.google_map }}

If you want to pull other raw values out of your referenced entity, you can access them easily like this:
$vars['referenced_entity_field_value'] = $referenced_entity->field_example_description->value;
But if you do this, you lose the formatting from a field formatter.  For plain text fields, that's may be fine for your use case.  But it's something to watch out for.


Dado a determinada String abaixo, como faço para definir esta divisão?

Question: Tenho a seguinte string:

"Dados do Usuário: JOAQUIM DE OIVEIRA, NASCIDO
  EM 2010, FORMADO EM: DIREITO, HOBBIE: FUTEBOL"

Como faço para dar um explode nessa string só validando o primeiro sinal de separação e a dividindo em dois ? Exemplo:
pedaço1="Dados do Usuário";
pedaço2="JOAQUIM DE OIVEIRA, NASCIDO EM 2010, FORMADO EM: DIREITO, HOBBIE: FUTEBOL";

Answer: Utilize a função explode. Veja a documentação aqui.
$string = "Dados do Usuário: JOAQUIM DE OIVEIRA, NASCIDO EM 2010, FORMADO EM: DIREITO, HOBBIE: FUTEBOL";
$array = explode(":", $string, 2);

// $array[0] = "Dados do Usuário"
// $array[1] = "..."

Answer: Podes usar o preg_match que é semelhante ao explode só que usa uma expressão regular.
$string = "Dados do Usuário: JOAQUIM DE OIVEIRA, NASCIDO EM 2010, FORMADO EM: DIREITO, HOBBIE: FUTEBOL";
preg_match("/^([^:]*:\s)(.*)/", $string, $pedacos);
echo $pedacos[2]; // "JOAQUIM DE OIVEIRA, NASCIDO EM 2010, FORMADO EM: DIREITO, HOBBIE: FUTEBOL"

Exemplo: http://ideone.com/rZDzvR
Neste exemplo vai ter uma array de 3 elementos. O primeiro é a string completa, o segundo tem só "Dados do Usuário: " e o terceiro ($pedacos[2]) o resto.


python pygtk how to put a window on a specific display monitor

Question: I'm using Python PyGTK library on OS Linux based (suse, ubuntu)
Working on devices with multiple Display Monitors.
I'm trying to put a Full Screen Window (in python, gtk.Window) on a Specific Display monitor connected to the Device.
I'm using the following code:
n_monitors = gtk.gdk.Screen.get_n_monitors()  # Get number of monitors.
gtk.gdk.Screen.get_monitor_geometry(*monitor_number*)  # Get the size of a specific monitor.

The second api returns the monitor size and offset information.
gtk.Window.move(offset_x, offse_y) can be used for moving a window on a specific monitor.
Though this doesn't seem to work all the time. It looks like the window has an affinity to the mouse location or if the monitor resolutions are not the same this does not work.
Is there any property of the gtk.Window which would help mitigate this issue.
I tried playing with following which didn't help :
gtk.Window.set_position(gtk.WIN_POS_NONE)
gtk.Window.set_gravity(gtk.gdk.GRAVITY_NORTH_WEST)

Any ideas.
Comment: Updated with some more info..
Answer: Your monitors collectively form one screen. You can query a screen to find out about its monitors. You can then position your window on a given monitor by ofsetting the window's (x,y) with that of the monitor.
Assuming your window is window, you can get the screen like this
screen = window.get_screen()

and then get the monitor data like this
monitors = []
for m in range(screen.get_n_monitors())
  monitors.append(screen.get_monitor_geometry(m)

monitors are numbers 0,1,2,... You can get the current monitor, if you need to, like this:
screen.get_monitor_at_window(screen.get_active_window())

To position a window on a monitor, you add the monitor's (x,y) to the window's (x,y). Calculate those x,y values and then move the window:
window.move(x,y)

See a similar answer I provided here.
Comment: Thanks for answering starfry. I'll look into what you are suggesting and let you know the result.


Stopping Windows service does not kill processes (service uses ant)

Question: I have a Windows service on Windows Server 2008 R2 that I set-up using instsrv on the srvany.exe executable. The three values in the Parameters key are set as follows:
AppDirectory  C:\selenium-grid
Application   C:\ant\bin\ant.bat
AppParameters launch-hub

The service starts fine and two Java processes appear in the Task Manager when it starts (one process is ant and the other is a Java class launched by ant). When I stop the service the status of the service changes to stopped but the two Java processes do not go away.
How do I get the processes to stop when I stop the service?
Comment: Is this an installation of the srvany.exe service?
Comment: whats in ant.bat if there is more then one exe in there that may be the issue.
Comment: Yes, the service install uses `srvany.exe`. I have added that clarification to the question.
Comment: One process is ant itself while the other is a Java class launched by ant. (Updated the question to clarify this.)
Answer: Unvortunately, SRVANY sucks. There is an alternative which is the "Non-Sucking Service Manager" (NSSM) - it will shut down your application and all child processes on the service stop signal.
Answer: Unfortunately, srvany.exe does not provide any method for killing the process(es) when the service is stopped, so basically your options are to (a) look for a third-party alternative which does provide this functionality or (b) write such a replacement yourself.
Perhaps another reader knows about a good third-party alternative, or you might get lucky with a Google search.  If you decide to go with option (b) I may be able to give you a head start, so drop me an email if you like - my address is in my profile.  Or you could post a question to StackOverflow.
Answer: Srvany has a few well known shortcomings, one of which is not terminating the process it starts.
Be sure to read about other potential issues on this page comparing Srvany to AlwaysUp (our commercial application which will close all sub-processes as you expect) to reduce the surprises...


How to analyze this chord in Moonlight Sonata 3rd movement?

Question: In Beethoven's Moonlight Sonata 3rd movement, I'd like to understand the Fx (double sharp) in measure 8.

Measure 8 has a bass of A and an arpeggio with the notes C# E Fx C# which sounds like an A7, but the Fx can't be the seventh, since otherwise it would have been written as a G. If it's not, it serves a specific purpose that I don't get.
With Fx, this chord would be more like an A6, but with an augmented sixth... which I think is unusual.
Is there a reason to avoid the dominant 7th by keeping the "F" name?
Putting measure 8 in context: the previous measure 7 is F#m, and the next measure 9 is G#. I'd like to think that this may be a II-V-I chord progression, and I would expect in that sense a C#m chord. A7 would be the relative major so that would fit...
Would it be the C#m I expect, but with an "augmented sus4" (that sounds like G natural...) and on top of an A bass?
Comment: "which I think is unusual": not in the 19th century!  In fact the augmented sixth chord has its roots in the early baroque.  It's enharmonically equivalent (and typically functionally equivalent) to the tritone dominant seventh substitution of jazz theory.
Answer: This is an augmented sixth chord. Whereas an A7 chord would be expected to resolve to D, an Aaug6 chord resolves to G# — as can be seen in the score.
Augmented sixth chords arise from the b6 of a minor key and contain b6 and #4. Given that this movement is in C# minor, the b6 is A, and the #4 is Fx. The interval of an augmented sixth resolves "outward", to the octave (G#), giving the V chord, which then typically resolves to the I chord.
This particular chord is known as a "German" augmented sixth. The name is traditional and has no known connection to the region. There are three types of augmented sixth chords:

German: b6-1-b3-#4 (sounds like a dominant seventh chord)
Italian: b6-1-2-#4
French: b6-1-#4
Comment: @Richardissteppingdown thanks. I was picturing a piano keyboard.
Comment: Does the German look like a dominant seventh, or does it sound like it?
Answer: A supplementary answer here, let's consider the voice leading in this harmonic motion:

A C# F#
A C# E F##
G# B# D# G#

Voice leading
There's only one note which really moves between the first two chords: the submediant (scale degree 4) F# getting raised up a half step to F## and then again to the dominant (5) G#. This is a really common voice-leading pattern, 4 - #4 - 5, and you see it in many common chromatic harmonies of this style.

Functionally equivalent chords
As you may notice, this crops up in every type of augmented 6th chord, and this voice leading movement explains the funky spelling of the augmented 6th interval formed over the chord root. It also appears in the common secondary dominant V/V, where the major 3rd of the chord is the #4 of the key. Same with the vii°/V, spelled off of the #4 degree since by definition that's the leading tone to the dominant. Incidentally, in jazz, the tritone substitution sub(V)/V has the same notes as the classical German augmented 6th, but spells it as the key's b5 because the note tends to resolve down to the chordal 7th (scale degree 4) of the dominant.
Often times, complex harmonies can be best understood from the horizontal voice leading perspective; if you understand why certain notes lead to others, strange-looking chords will sort themselves out quite handily.
Comment: "because the note tends to resolve down": I always figured it was because A7 is a much more straightforward chord symbol to write than whatever you'd write for a "properly" spelled augmented 6th (and I've assumed that this led to tritone substitution theory rather than the other way around).
Comment: That's also a fair point. Personally I like the resolution-based spelling because it's a nice instructive principle about chromatic spelling, but the actual jazz history might have been more about simplicity.
Answer: Look at the following chord, which is G# major. So the F## has some sort of secondary leading note character. This means that chord should be some variation of a D# dom. chord. Given we have the notes c# and f## we have 7th and 3rd. We also have e (m9th). This form a classic diminished 7th chord on the leading note as substitute for the dominant (just leaving out the 3rd (the 5th of the dominant chord)).
The A in the bass works as a second phygian leading tone and is the diminished 5th of the dominant chord. So this should be seen as a D# b5 7 b9 chord without the root note.
Regarding II - V - I: This does not work out exactly. Basically this is a not that uncommon progression IV - #IVø - V, so reaching the dominant chromatically from the subdominant by sharpening the IV into a secondary leading tone. As already elaborated this is functionally equivalent to a IV - II7 - V progression.
Comment: @Aaron Not _dominant_, _secondary dominant_. The dominant of the dominant.
Comment: The downvote is probably because the secondary dominant is a less convincing explanation than the Ger+6 explanation... or possibly because this answer talks about a diminished 7th chord built on the F## leading tone where there is none (the A would have to be A#). Nevertheless, the comparison to the secondary dominant D#7 is interesting, both serve similar function to the jazzier tritone substitution concept.
Comment: @Lazy - Weird, I've read "'root position' augmented 6th chords should be treated as inverted" more often than "augmented 6th chords are dominant(-function) chords with omitted roots". In fact, **your post is the first time I've read the latter**.
Comment: @Dekkadeci There's a first time for everything :). The said reading can be found e.g. in Schönberg's treatise on harmony.
Comment: Augmented sixth chords do not have a dominant function; they have a pre-dominant function.
Comment: @Aaron If you read my answer this comment is posted under you will find that I did use the terms _a dominant chord_, _secondary leading tone_ and _II7_. And in what world does II7 resolve to bII?
Comment: @Aaron But we are talking about II7, not bVI7.
Comment: @user45266 In fact I believe my explanation does explain *better* why things work out like this, while the other one is a blackbox slapping a name onto something and claiming _it just works like this_. It is worth pointing out that the interpretation of this sort of chord as dominant with omitted root is not something I made up but more or less the standard function theoretic reading of this chord. And yes, this principle is pretty much the same thing as tritone substitutions.
Comment: I know what a secondary dominant is. Your comment doesn't say "secondary". And it doesn't function like a secondary dominant. If it did, it would resolve to bII, not V.
Comment: bVI is a secondary dominant to bII.


Failed due ftp PORT command

Question: I am trying to implement IPv6/IPv4 dual stack FTP connection. I succesfully implemented almost all  parts of functionality, but I got stacked on PORT command. When I am trying to send it I got :
421 Service not available, closing control connection. Timeout expired.

This is kind a stange, cause I know that on IPv6 you do not actually need port command, and first four numbers are ignored. I am sending PORT command in this format:
h1,h2,h3,h4,p1,p2

Thanks on advance.
Answer: Wrong assumption: a port-like command is necessary and has a different syntax. The new commands are ERPT and EPSV. Some examples:
EPRT |2|1080::8:800:200C:417A|5282|
EPSV 2

Look at RFC 2428 for the full specifications.
Comment: do you mean that these commands should be used in case of IPv6 ?

Failed due ftp PORT command


How to play notes with evenness

Question: I am learning to play the piano and while playing pieces, I generally find that I tend to hit some notes louder than others despite me wanting to have them at the same dynamic level. How can I develop my fingers to have the dynamic independence to have all the notes exactly the same (dynamically) and only have changes when crescendos and diminuendos are required?
Comment: what instrument?
Comment: @Peter I agree, but I don't want to assume. Could be marimba, could be hang drum; could even conceivably be oboe, violin, or ocarina, if "hit" is used in a general kind of way. I guess the answer is pretty much the same in all cases—"careful practice"—though it would be nice to address the physical mechanics. Voting to close lacking clarity; I look forward to retracting the close vote once it's edited.
Comment: The answer may depend upon _which_ keyboard instrument. Obviously the question doesn't apply to non-touch-sensitive ones such as organ or harpsichord — but if you practise on a lightweight synth-action keyboard, you're much more likely to have trouble controlling the exact level than if you have a fully-weighted keyboard or even a grand piano.
Comment: Hey! I have edited the question, I was referring to a piano, thanks for making the question clear!
Comment: @AndyBonner Sounds like a keyboard to me. The question refers to 'hit'.
Answer: We're talking keyboard?
Check your posture, arm and hand positions.  Do some finger independence exercises - place five fingers over five notes, play four of the notes and hold them down, play repeated notes with the remaining finger.(Yes, it's tricky with 4 and 5 isn't it!  LIFT that finger!  It can't come down unless it was up first!)
Then scales, arpeggios etc.  You know, all the usual piano lesson stuff :-)
And a teacher would be good.  Have you got one?
Comment: Yes, I do have a teacher!
Comment: And I guess the teacher is telling you the same thing!
Answer: Generally speaking, for almost every style of piano playing (I assume you're talking about keyboard of some sort), it is ideal to have some dynamic variation between notes. It ends up sounding robotic if you play with the exact same dynamics on every note!
If you're having issues where the notes you play are way louder than others accidentally, that sounds like a technique issue you'll want to work on with the help of a qualified teacher.
Comment: This is good musical advice. Downvoted just because it doesn't really answer the OP's question, and the question is valid as well. You can't do intentional, controlled dynamic variation if you can't consistently achieve the dynamic you intend.
Comment: I think you missed "despite me wanting to have them at the same dynamic level"
Comment: I caught that! I suppose I misinterpreted "having them at the same dynamic level" meaning "consistently Piano" or "consistently Forte" rather than the exact same decibel level.
Comment: There's a huge difference between playing with controlled dynamic variation and every note at random.

How to play notes with evenness


What is causing heap corruption and extraneous values in my code?

Question: I'm writing code for a project in my class, and it is producing incredibly unusual results. Row and column values end up with random numbers in the millions and it eventually throws exceptions and I can't understand why.
#include <iostream>
using namespace std;

class SparseRow {
protected:
    int row;
    int col;
    int value;
public:
    SparseRow();
    SparseRow(int inRow, int inCol, int inVal);
    SparseRow(const SparseRow& newRow);
    SparseRow& operator=(const SparseRow& newRow);
    ~SparseRow();
    void display();
    int getRow();
    int getCol();
    int getValue();
    void setRow(int inRow);
    void setCol(int inCol);
    void setValue(int inVal);
};

class SparseMatrix {
protected:
    int noRows;
    int noCols;
    int commonValue;
    int noSparseValues;
    SparseRow *myMatrix;
    void setNoSparseValues(int noSV);
public:
    SparseMatrix();
    SparseMatrix(int rows, int cols, int cv, int noSV);
    SparseMatrix(const SparseMatrix& matrix);
    SparseMatrix& operator=(const SparseMatrix& matrix);
    ~SparseMatrix();
    void readMatrix();
    SparseMatrix* transpose();
    SparseMatrix* multiply(SparseMatrix& M);
    SparseMatrix* add(SparseMatrix& M);
    void display();
    void displayMatrix();
    int getNoRows();
    int getNoCols();
    int getCommonValue();
    int getNoSparseValues();
    int getValue(int row, int col);
    void setValue(int row, int col, int val);
};

SparseRow::SparseRow() {
    row = -1;
    col = -1;
    value = 0;
}

SparseRow::SparseRow(int inRow, int inCol, int inVal) {
    row = inRow;
    col = inCol;
    value = inVal;
}

SparseRow::SparseRow(const SparseRow& newRow) {
    row = newRow.row;
    col = newRow.col;
    value = newRow.value;
}

SparseRow& SparseRow::operator=(const SparseRow& newRow) {
    if (this != &newRow) {
        row = newRow.row;
        col = newRow.col;
        value = newRow.value;
    }
    return *this;
}

SparseRow::~SparseRow() {
    cout << "Deleting SparseRow with values: " << endl;
    display();
}

void SparseRow::display() {
    cout << "Row: " << row << ", Column: " << col << ", Value: " << value << endl;

}

int SparseRow::getRow() {
    return row;
}

int SparseRow::getCol() {
    return col;
}

int SparseRow::getValue() {
    return value;
}

void SparseRow::setRow(int inRow) {
    row = inRow;
}

void SparseRow::setCol(int inCol) {
    col = inCol;
}

void SparseRow::setValue(int inVal) {
    value = inVal;
}

SparseMatrix::SparseMatrix() {
    noRows = 0;
    noCols = 0;
    commonValue = 0;
    noSparseValues = 0;
}

SparseMatrix::SparseMatrix(int rows, int cols, int cv, int noSV) {
    noRows = rows;
    noCols = cols;
    commonValue = cv;
    noSparseValues = noSV;
    myMatrix = new SparseRow[rows * cols];
}

SparseMatrix::SparseMatrix(const SparseMatrix& matrix) {
    noRows = matrix.noRows;
    noCols = matrix.noCols;
    commonValue = matrix.commonValue;
    noSparseValues = matrix.noSparseValues;
    myMatrix = matrix.myMatrix;
}

SparseMatrix& SparseMatrix::operator=(const SparseMatrix& matrix) {
    if (this != &matrix) {
        delete[] myMatrix;

        noRows = matrix.noRows;
        noCols = matrix.noCols;
        commonValue = matrix.commonValue;
        noSparseValues = matrix.noSparseValues;
        myMatrix = matrix.myMatrix;
    }
    return *this;
}

SparseMatrix::~SparseMatrix() {
    cout << "Deleting SparseMatrix with values: " << endl;
    display();

    delete[] myMatrix;
}

void SparseMatrix::readMatrix() {
    int count = 0;
    int val;

    for (int i = 0; i < noRows; i++) {
        for (int j = 0; j < noCols; j++) {
            cin >> val;
            if (val != commonValue) {
                myMatrix[count].setRow(i);
                myMatrix[count].setCol(j);
                myMatrix[count].setValue(val);
                // Why does C++ prevent me from calling a constructor on objects in an array? It doesn't make sense.
                count++;
            }
        }
    }

    if (count != noSparseValues) {
        cout << "ERROR: Incorrect number of sparse values! Changing to correct number." << endl;
        noSparseValues = count;
    }
}

SparseMatrix* SparseMatrix::transpose() {
    SparseMatrix *newMatrix = new SparseMatrix(noCols, noRows, commonValue, noSparseValues);

    for (int i = 0; i < noSparseValues; i++) {
        newMatrix->setValue(myMatrix[i].getCol(), myMatrix[i].getRow(), myMatrix[i].getValue());
    }

    return newMatrix;
}

SparseMatrix* SparseMatrix::multiply(SparseMatrix& M) {
    if (noCols != M.getNoRows()) {
        cout << "ERROR: Matrices cannot be multiplied!" << endl;
        return NULL;
    }

    SparseMatrix *newMatrix = new SparseMatrix(noRows, M.getNoCols(), commonValue, noRows * M.getNoCols());
    // Why does C++ prevent me from creating an array to store this information? It doesn't make sense.

    int SVCount = 0;
    for (int i = 0; i < noRows; i++) {
        for (int j = 0; j < M.getNoCols(); j++) {
            int sum = 0;
            for (int k = 0; k < noCols; k++) {
                sum += getValue(i, k) * M.getValue(k, j);
            }
            if (sum != newMatrix->getCommonValue()) {
                SVCount++;
            }
            newMatrix->setValue(i, j, sum);
        }
    }
    newMatrix->setNoSparseValues(SVCount);

    return newMatrix;
}

SparseMatrix* SparseMatrix::add(SparseMatrix& M) {
    if (noRows != M.getNoRows() || noCols != M.getNoCols()) {
        cout << "ERROR: Matrices cannot be added!" << endl;
        return NULL;
    }

    SparseMatrix *newMatrix = new SparseMatrix(noRows, noCols, commonValue + M.getCommonValue(), noRows * noCols);

    int SVCount = 0;
    for (int i = 0; i < noRows; i++) {
        for (int j = 0; j < noCols; j++) {
            int sum = getValue(i, j) + M.getValue(i, j);
            if (sum != newMatrix->getCommonValue()) {
                SVCount++;
            }
            newMatrix->setValue(i, j, sum);
        }
    }

    newMatrix->setNoSparseValues(SVCount);

    return newMatrix;
}

void SparseMatrix::display() {
    for (int i = 0; i < noSparseValues; i++) {
        myMatrix[i].display();
    }
}

void SparseMatrix::displayMatrix() {
    for (int i = 0; i < noRows; i++) {
        for (int j = 0; j < noCols; j++) {
            cout << getValue(i, j) << " ";
        }
        cout << endl;
    }
}

int SparseMatrix::getNoRows() {
    return noRows;
}

int SparseMatrix::getNoCols() {
    return noCols;
}

int SparseMatrix::getCommonValue() {
    return commonValue;
}

int SparseMatrix::getNoSparseValues() {
    return noSparseValues;
}

void SparseMatrix::setNoSparseValues(int noSV) {
    noSparseValues = noSV;
}

int SparseMatrix::getValue(int row, int col) {
    for (int i = 0; i < noSparseValues; i++) {
        if (myMatrix[i].getRow() == row && myMatrix[i].getCol() == col) {
            return myMatrix[i].getValue();
        }
    }
    return commonValue;
}

void SparseMatrix::setValue(int row, int col, int val) {
    bool replacingSparse = (getValue(row, col) != commonValue);
    bool replacingWithSparse = (val != commonValue);

    int index = -1;

    if (replacingSparse) {
        for (int i = 0; i < noSparseValues; i++) {
            if (myMatrix[i].getRow() == row && myMatrix[i].getCol() == col) {
                index = i;
                break;
            }
        }
        if (replacingWithSparse) {
            myMatrix[index].setValue(val);
        }
        else {
            for (int i = index; i < noSparseValues; i++) {
                myMatrix[i] = myMatrix[i + 1];
            }
            noSparseValues--;
        }
    }
    else {
        if (replacingWithSparse) {
            for (int i = 0; i < noSparseValues; i++) {
                if (myMatrix[i].getRow() > row || (myMatrix[i].getRow() >= row && myMatrix[i].getCol() > col)) {
                    index = i;
                    break;
                }
            }
            for (int i = noSparseValues; i > index; i--) {
                myMatrix[i] = myMatrix[i - 1];
            }
            myMatrix[index].setRow(row);
            myMatrix[index].setCol(col);
            myMatrix[index].setValue(val);
            noSparseValues++;
        }
    }
}

int main() {
    int n, m, cv, noNSV;
    SparseMatrix* temp;

    cin >> n >> m >> cv >> noNSV;
    SparseMatrix* firstOne = new SparseMatrix(n, m, cv, noNSV);
    firstOne->readMatrix();

    cin >> n >> m >> cv >> noNSV;
    SparseMatrix* secondOne = new SparseMatrix(n, m, cv, noNSV);
    secondOne->readMatrix();

    cout << "First one in sparse matrix format" << endl;
    firstOne->display();

    cout << "First one in normal matrix format" << endl;
    firstOne->displayMatrix();

    cout << "Second one in sparse matrix format" << endl;
    secondOne->display();

    cout << "Second one in normal matrix format" << endl;
    secondOne->displayMatrix();

    cout << "After Transpose first one in normal format" << endl;
    temp = firstOne->transpose();
    temp->displayMatrix();

    cout << "After Transpose second one in normal format" << endl;
    temp = secondOne->transpose();
    temp->displayMatrix();

    cout << "Multiplication of matrices in sparse matrix form:" << endl;
    temp = secondOne->multiply(*firstOne);
    temp->display();

    cout << "Addition of matrices in sparse matrix form:" << endl;
    temp = secondOne->add(*firstOne);
    temp->display();
}

Input:
3 3 0 3
2 2 2
0 0 0
0 0 0

3 3 0 3
2 2 2
0 0 0
0 0 0

Expected output: (not formatted exactly the same, but the numbers should be identical)
First one in sparse matrix format
0, 0, 2
0, 1, 2
0, 2, 2
First one in normal matrix format
2     2     2
0     0     0
0     0     0
Second one in sparse matrix format
0, 0, 2
0, 1, 2
0, 2, 2
Second one in normal matrix format
2     2     2
0     0     0
0     0     0
After Transpose first one
2     0     0
2     0     0
2     0     0
After Transpose second one
2     0     0
2     0     0
2     0     0
Multiplication of matrices in sparse matrix form:
0, 0, 4
0, 1, 4
0, 2, 4
Addition of matrices in sparse matrix form:
0, 0, 4
0, 1, 4
0, 2, 4

Actual output:
First one in sparse matrix format
Row: 0, Column: 0, Value: 2
Row: 0, Column: 1, Value: 2
Row: 0, Column: 2, Value: 2
First one in normal matrix format
2 2 2
0 0 0
0 0 0
Second one in sparse matrix format
Row: 0, Column: 0, Value: 2
Row: 0, Column: 1, Value: 2
Row: 0, Column: 2, Value: 2
Second one in normal matrix format
2 2 2
0 0 0
0 0 0
After Transpose first one in normal format
0 0 0
2 0 0
2 0 0
After Transpose second one in normal format
0 0 0
2 0 0
2 0 0
Multiplication of matrices in sparse matrix form:
Row: 0, Column: 1, Value: 4
Row: 0, Column: 2, Value: 4
Row: 369, Column: -33686019, Value: 9
Addition of matrices in sparse matrix form:
(Exceptions thrown here, line 222 in code)

Exceptions thrown:
Project1.exe has triggered a breakpoint.

Unhandled exception at 0x777E8499 (ntdll.dll) in Project1.exe: 0xC0000374: A heap has been corrupted (parameters: 0x77825890).

Comment: If you are new to C++, I highly recommend reading [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), rather than trying to figure it out based on your knowledge of Java. Smart pointers (like `std::unique_ptr`) are great; they automatically manage the lifetime of the pointer, freeing you from having to call `delete` yourself. In this case, you don't even seem to need smart pointers. You could get away with `std::vector`.
Comment: I would suggest that modern developers almost *never* have a reason to use naked `new` and `delete`, when smart pointers are so much better.
Comment: `for (int i = 0; i < noSparseValues; i--)` What do you think is going on here?
Comment: Is the use of the auxiliary class SparseRow a design choice of yours or is it mandatory for the assignment? I find its name misleading at best, it doesn't model a row, not to mention a sparse one and it could be replaced for any means by a `struct Element {int row, col, value;};`, if needed at all. You may want to look at other possible implementations of [sparse matrices](https://en.wikipedia.org/wiki/Sparse_matrix), if you are allowed to.
Comment: @Bob__ I definitely agree with you (except that I don't know what `struct Element` means), but SparseRow is a part of the assignment and I can't do much about it. I can't even rename it to something more accurate.
Comment: @draket333 Well, it's another keyword used to define a class, the only difference is that the member of a class defined with the keyword `class` are private by default, while the members of a class defined with the keyword `struct` are public by default. My point is that for every member of `SparseRow` you define getters and setters that expose them without any check, so you could just make those members public and access them directly. *Unless* the interface of your objects is defined by your assignment.
Comment: I forgot to mention, I'm used to Java and very new to C++, so I really don't know how most of these things work. For example, I've heard of a "double pointer," but I have no idea what it is or how to use it.
Comment: The problem first arises in the first transpose, and since we know `SparseMatrix::display()` works from the input matrices, `SparseMatrix::transpose()` must be wrong. Try putting a `std::cerr` line inside the loop to see how many values are actually being set (should be 3 for the first transpose, may only be 2).

If only 2 values are being set, you have to figure out why the third one doesn't happen (probably the count is wrong); if all 3 are "set", you have to figure out why nothing is recorded inside the matrix (maybe it's written to an invalid address).
Comment: @CodyGray Using vectors sounds like a wonderful idea, but unfortunately my professor specifically requires no #include statements on this project other than iostream, and if I understand it correctly, you have to use #include to use vectors.
Comment: @n.m. I'm really not sure how I missed that. I had a lot of issues related to the next for loop after that because it had i++ instead of i--. Thanks for pointing it out!
Comment: @BaryonsforBreakfast I'm not certain, but I think this is the root of the issue: Row: 369, Column: -33686019, Value: 9
I would assume the same thing happens in the transpose method, although I could test it and make sure. But why does that happen?
Comment: Turn on more warnings (MSVC: warning level 4, gcc: -Wall -Wextra) and check the compiler output. Learn how to use a debugger. The code that you post is much too many lines long to easily be checked by us.
Answer: I'll address only some of the issues in the posted code.
pointers
Their explict use is always prone to error and it's increasingly discouraged at every new version of the standard.
In OP's code they own the responsability of managing memory resources, but in C++ they don't automatically call the destructor of an object when it goes out of scope.
That's what a smart pointer like std::unique_ptr can do.
Let's see what happens in main:
int n, m, cv, noNSV;
SparseMatrix* temp;  // <- Declaration far from initialization

cin >> n >> m >> cv >> noNSV;
SparseMatrix* firstOne = new SparseMatrix(n, m, cv, noNSV);
//          ^^^^^^^^^^^^^^^^ Why?
// ...
temp = firstOne->transpose();  // <- Here the pointer is initialized
// ...
temp = secondOne->transpose(); // <- Here the pointer is overwritten, but the allocated memory
                               //    isn't released, it leaks.
// ...
temp = secondOne->multiply(*firstOne); // <- Again...
// ...
temp = secondOne->add(*firstOne);  // <- ...and again
// ...
// No 'delete' calls at the end, so no destructor is called for the previously allocated objects

The only reason to use pointers here, is that SparseMatrix::transpose() is designed to return one, but it could easily retrun a SparseMatrix instead (Return Value Optimization would avoid unnecessary copies).
To every call of new should correspond a delete and since functions like transpose return a pointer to a newly allocated objects, delete temp; should be called before overwriting temp, to make sure that the proper destructor is called.
In C++, though, we should take advantage of RAII (Resource Acquisition Is Initialization, also named Scope-Bound Resource Management):
{   // <- Start of a scope
    int n, m, cv, noNSV;

    std::cin >> n >> m >> cv >> noNSV;
    // Declare a variable using the constructor. Its lifetime begins here.
    SparseMatrix firstOne(n, m, cv, noNSV);
    // The same for 'secondOne'
    // ...
    // SparseSparse::transpose() here should return a SparseMatrix, not a pointer
    SparseMatrix temp = firstOne.transpose();

    // ...
    // Here the matrix is reassigned (which can be cheap if move semantic is implemented)
    temp = secondOne.transpose();
    // ...
    temp = secondOne.multiply(firstOne); // <- Again...
    // ...
 }  // <- End of scope, all the destructors are called. No leaks.

special member functions
That's actually related to previous point, looking at how e.g. the copy assignment operator is implemented in the posted snippet:
 SparseMatrix& SparseMatrix::operator=(const SparseMatrix& matrix) {
     if (this != &matrix) {     // <- debatable, see copy-and-swap idiom
         delete[] myMatrix;     // <- putted here makes this function not exception safe ^^

         noRows = matrix.noRows;
         noCols = matrix.noCols;
         commonValue = matrix.commonValue;
         noSparseValues = matrix.noSparseValues;
         myMatrix = matrix.myMatrix; // <- The pointer is overwritten, but this is shallow copy
                                     //    what you need is a deep copy of the array
     }
     return *this;
 }

A proper implementation of this and the other special functions would take advantage of the copy-and-swap idiom, which is masterfully described here:
What is the copy-and-swap idiom?
Also, regarding this comment in OP's reading function:
for (int i = 0; i < noRows; i++) {
    for (int j = 0; j < noCols; j++) {
        cin >> val;
        if (val != commonValue) {
            myMatrix[count].setRow(i);
            myMatrix[count].setCol(j);
            myMatrix[count].setValue(val);
            // Why does C++ prevent me from calling a constructor on objects in an array? It doesn't make sense.
            count++;
        }
    }
}

The asker could use the placement parameter of new (placement new), there:
for (int i = 0; i < noRows; i++) {
    for (int j = 0; j < noCols; j++) {
        cin >> val;
        if (val != commonValue) {

            new (myMatrix + count) SparseRow(i, j, val);

            count++;
        }
    }
}

Many other issues are left to the OP to solve.


How to use sprintf in Url::fromUri?

Question: I am trying to convert this from D7 to D8:
l(drupal_strtoupper($field),
sprintf('http://finance.google.com/finance?q=%s',
$exchange . ':' . $field),
array('attributes' =>
array('target' => '_blank',
       'title' => (drupal_strlen($title)) ? $title : $field)
)
);

I am doing this and it produced error:
return Link::fromTextAndUrl(Unicode::strtoupper($field), Url::fromUri(sprintf('http://finance.google.com/finance?q=%s'),$exchange . ':' . $field))->toString();

InvalidArgumentException: The URI '' is invalid. You must use a valid URI scheme. in Drupal\Core\Url::fromUri() (line 281 of core/lib/Drupal/Core/Url.php)
Answer: It doesn't really make sense to use sprintf (or any other string formatting/replacement functions) here - the API can already accommodate what you need in a much more structured manner:
$options = ['query' => ['q' => $exchange . ':' . $field]];
$url = Url::fromUri('http://finance.google.com/finance', $options);
$link = Link::fromTextAndUrl(Unicode::strtoupper($field), $url);

How to use sprintf in Url::fromUri?


JavaScript - Conteúdo de uma TD comparando com uma variável

Question: Estou fazendo um script que limpa os 3 elementos a seguir.
No If a clausula tem que cair no verdadeiro (Fiz a consulta através do console.log e tem que cair no verdadeiro, porém cai na posição false.
Podem me ajudar a descobrir o porque??

 function teste(){
     var idAntigo = "123"
        var tds = document.querySelectorAll("#tblItens td");
        var values = [];
        var tabela = document.querySelector("#tblItens");
        var TDs1 = tabela.getElementsByTagName("td");
        console.log("Caiu aqui");
        for (i = 0; i < TDs1.length; i++) {
        console.log("Aqui também");
            if (TDs1[i].innerHTML === idAntigo ) {
        console.log("Aqui não");
                TDs1[i].innerHTML = "";
                TDs1[i + 1].innerHTML = "";
                TDs1[i + 2].innerHTML = "";
                TDs1[i + 3].innerHTML = "";
                break;
            } else { console.log("false")}
        }
    }

    123
    124
    123

    123

    125
    124

 <button onclick="teste()"> teste </button>

Comment: (TDs1[i].innerHTML === TDs1) nunca vai ser verdadeiro, você está comparando a td atual com o objeto que armazena todas as td´s, o que você realmente quer fazer nessa parte?
Comment: Ata entendi seu problema
Comment: Perdão @Felipe, a comparação deve comparar o elemento da td com a `idAntiga`, ainda sim nem cai no If, corrigi a pergunta lá, perdão novamente
Answer: Repare que os elementos na td estão com um espaçamento, o innerHTML pega esse espaçamento, e ao fazer a verificação isso vai interferir, uma alternativa é o innerText que pega somente a área do texto, exemplo...

function teste(){
     var idAntigo = "123"
        var tds = document.querySelectorAll("#tblItens td");
        var values = [];
        var tabela = document.querySelector("#tblItens");
        var TDs1 = tabela.getElementsByTagName("td");
        for (i = 0; i < TDs1.length; i++) {
            if (TDs1[i].innerText == idAntigo ) {
            console.log("agora caiu");
                TDs1[i].innerHTML = "";
                TDs1[i + 1].innerHTML = "";
                TDs1[i + 2].innerHTML = "";
                TDs1[i + 3].innerHTML = "";
                break;
            } else { console.log("false")}
        }
    }

    123
    124
    123

    123

    125
    124

 <button onclick="teste()"> teste </button>
Comment: Ah, entendi !! Obrigado pela explicação e pela ajuda @Felipe !!


Prove that this limit may exist, even though $f$ is not differentiable at $x$

Question:
Consider the limit $\displaystyle \lim_{h \to 0} \dfrac{f(x+h)-f(x-h)}{2h}$. Prove that this limit may exist, even though $f$ is not differentiable at $x$.

This is a follow-up question to this so you may assume that the given expression equals $f'(x)$. This seemed sort of interesting to me since we know that it equals $f'(x)$ for any $x$ value such that the function is differentiable at that point but if it is not $\displaystyle \lim_{h \to 0} \dfrac{f(x+h)-f(x)}{h}$  still has a value. I think in order to prove this we just need one example of a function, but I am not sure which one.
Comment: how about $f(x)=|x|$ at $0$?
Comment: Hint: indicator of $\{0\}$ at $0$
Answer: Consider this function:
$$
f(x)=\left\{
  \begin{array}{ll}
    1, & \hbox{if $x\neq 0$;} \\
    0, & \hbox{if $x=0$.}
  \end{array}
\right.
$$
It is not continuous at $x=0$, so it is not differentiable at $x=0$. However, the limit you talked about exists and is equal to $0$.
Comment: What do you mean "is equal to $x = 0$"?
Comment: it is a typo. Corrected.


How many homomorphims from $Z_{12}$ to $S_{5}$

Question: I'm trying to calculate how many homomorphisms exists from $Z_{12}$  $\longrightarrow$  $S_{5}$ .
Here are the options :
$(x x x x x)$ order 5
$(xxxx)$ order 4
$(xx) (xx) $ order 2 ???
$(xxx)(xx) $ lcm(2,3)=6 , hence order 6
$(xxx)$ order 3
$(xx)$ order 2
$id$  , meaning every element is mapped to itself , order 1
My questions are :

why is the order of $ (xx) (xx) $ is 4 , and not 2 ?
We need $Z_{12}$ , so all the above has order 12 in common (lcm) except for $(x x x x x)$ with order 5 . Then this means that I need to find the ones that divide with 5  and subtract it from $|S_{5}|$

Regards
Comment: Regarding your question 1: why do you think the order of an element which is a product of two disjoint transpositions is $4$? Regarding your question 2: what you wrote is in fact *not* a question!
Comment: $\mathbb Z_{12}$ is a cyclic group so you only need to know where to send $\bar 1$. Let $\sigma$ be that image. Then the order of $\sigma$ must divide 12. So what are the possibilities for $\sigma$?
Comment: I wasn't totally sure regarding this solution , just wanted to make sure . Furthermore , as I can see , I was wrong regarding the order of $(xx)(xx)$ being 4 , since it's indeed 2 . thanks :)
Answer: An homomorphism $\phi:\mathbb Z_{12}\to S_5$ is completely specified by the image of $1$, and there is one for each element of $S_5$ whose order is a divisor of $12=2\cdot 2\cdot 3$.
Now, let $\pi$ be an element of $S_5$. The sizes of the cycles in its cycle decomposition are one of
<code>cycle sizes          order
1, 1, 1, 1, 1        1
2, 1, 1, 1           2
2, 2, 1              2
3, 1, 1              3
3, 2                 6
4, 1                 4
5                    5
</code>
and this table also shows the order of the corresponding elements.
We see that all elements of $S_5$ have orders which divide $12$, except those of order $5$. There are $4!$ $5$-cycles in $S_5$, so there are $5!-4!$ elements in $S_5$ whose order divide $12$, so there are exactly that many homomorphisms $\mathbb Z_{12}\to S_5$.
Comment: Great , I understand now my mistake ! thank you!
Comment: Can you please explain what do you mean by saying "completely specified by the image of 1" ?
Comment: What I mean is, two homomorphims $\mathbb Z_{12}\to S_5$ which take the same value at $1$ are equal.


What or who decides whether extra time is given in football?

Question: How is extra time decided to be given in football, either when the teams have scored the same number of goals, or when one team has scored more goals?
Can teams have extra time by requesting it, in either of the above cases?
Can they request extra time if extra time has already been given?
Answer: You have 2 kinds of "extra time"
The first is a couple of minutes added to a half time because the match was delayed for various reasons. (injuries, subs, fouls, etc...). This one is called Stoppage time.
The second is 2 additional half times of 15 minutes each (30 min total).
This extra time is only given when the match is a knockout phase and there is no winner yet. If there is still no winner after the extra time, the game proceeds in penalties.
So, to answer the question:
Extra time can only be given by the referee at the end of a knockout phase when there is no winner (score is equal).
Teams can not ask for extra time.
Ref: wikipedia
Comment: extra time is extra time, stoppage time is stoppage time, there are NOT 2 kinds of extra time.
Comment: Perhaps you can add a reference?
Comment: The first example is more commonly referred to as "additional/injury/stoppage time". The second example is what most people know extra time to be (or overtime if you're in US/Canada).
Comment: In the English League Cup Semi Final 2nd Leg, if the two teams are tied at full time then it proceeds to extra time. If at the end of extra time, the teams are tied but one team leads on the `away goals` rule then it does ***not*** proceed to extra time.
Comment: This being an old Q&A, I don't expect much to change, but extra time is specifically different from additional time. It is also not clear whether additional time always consists of "a couple of minutes" or (the actual practise) is variable to account for exactly the time lost as determined by the referee.
Comment: @Nij - you're right, this answer is horrible, but not only for that reason. It further perpetuates the misuse of the term "extra time" (when that term has a very clear meaning in the Laws), and furthermore, it references Wikipedia when there are much more direct sources available.
Answer: Extra time is played, when at the end of the match for which there must be a winner (ie a knockout, final or cup match), both teams have the same number of goals1.
Law 10 - Determining the Outcome of a Match, Section 2 - Winning Team:

When competition rules require a winning team after a drawn match or home-and-away tie, the only permitted procedures to determine the winning team are:

away goals rule
two equal periods of extra time not exceeding 15 minutes each
kicks from the penalty mark

A combination of the above procedures may be used.

Teams have no say in whether extra time is played and cannot request more. The full time allotted (usually two equal periods of 15 minutes) must be played, and if the scores are level after this time, kicks from the penalty mark must be used to determine the winner.
If the competition rules do not allow kicks from the penalty mark to be used, the match is drawn and the teams must be separated (for the purposes of qualification, or deciding the winner of the final or cup being contested) by some other procedure - such as a replay, a coin toss, or some other method as determined by the competition rules or competiton administrator.
Extra time is commonly confused with the allowance for time lost (or, as it also known, additional time) played at the end of each period to compensate for significant delays to restarts during the period. The term extra time should only be used to refer to the procedure used to determine the winner at the end of a drawn match.
1 - in some competitions, the away goals rule is used - in these competitions, extra time is only played if the teams cannot be separated based on both the aggregate score over both of the home-and-away matches and the number of away goals scored.
Answer: Extra time is added if the game is tied at the end of the regular time in certain knockout competitions, the game goes into two extra periods of 15 minutes each (30 minutes total), if the score is still tied by the end of the extra time, the game proceeds into kicks from the penalty mark (as named in the laws of the game) to decide the winner, and extra time is added according to competition regulations.
Also, you shouldn't mix between "extra time" and "stoppage time", as stoppage time (or injury time) are a few minutes added at the end of each half at the discretion of the referee due to injuries, time lost through substitutions, general time wasting etc.
Source


Highly correlated features in text mining despite mutual information criterion

Question: I'm trying to classify documents into two classes using the Bernoulli Naive Bayes algorithm, as described here in chapter 13.
I've extracted 500 tokens (out of more than 30,000) from my sample documents (about 500) using the mutual information criterion as described in the same chapter.
I calculate the conditional probabilities for all tokens as the empirical frequency of documents in class1 or class2 in my sample to contain this token. I also use the Laplace (+1) smoothing, as suggested in the book chapter. So if in class1, 3 documents contain the token "china" and one does not, then the conditional probability of token "china" being in class1 is:
P(china|class1) = (3 + 1) / (3 + 1 + 2) = 2/3 = 0.6667.
(where the 1 in the numerator is the +1 smoothing and the 2 in the denominator comes from there being 2 classes.)
When I plot these, they look like this:

The two series have a correlation of 0.89. So this means that if a document in class1 contains, say, the token "china", then it is also likely that a document in class2 contains the token "china".
This worries me, as I thought the information criterion would make sure tokens would show up more in one of these classes than in the other.
So my question is:

has anybody encountered a similar situation?
is this plausible or does this look wrong?

Thank you very much.
[This is my output from a relatively lengthy and idiosyncratic analysis, so I don't have a minimum working code example right now, but I hope you can follow my verbal explanation here. Thank you very much for any ideas.]
Comment: 1. Can you provide a table of the mutual information for the top 10 tokens that you have chosen and for the bottom 10 tokens when tokens are sorted in descending order of MI
2. Did you build the Naive Bayes model? If yes what was the AUC of the model?
Comment: My guess is that you have confounding based on document length. If you split docs into sub documents with, eg, 500 words each this would go away. If a doc has many words, all words are more likely, regardless of class.
Comment: make a 2d non-parametric density on top of your right plot.  There are clean multiple modes.
Comment: "the 2 in the denominator comes from there being 2 classes" Why is the number of classes relevant? Is this part of the smooting?
Answer: Ok, I think I know what's going on. I'll first give my tentative explanation and then answer @Wabbits and @Greg Ver Steeg's comments.
Answer
Even after picking tokens that rank highly using the mutual information criterion we still have a lot of tokens in there that appear relatively often in both classes of documents. They all have conditional probabilities of being in either class more than 0.78. That's mainly because they appear many times, all of them more than in more than 400 out of our about 500 training documents.
So apparently the information criterion was still high for them, so that we included them in the top ranked 500 tokens.
Here is a matrix of scatterplots of stats on these tokens against each other:

On the top left (1,1) we have the scatterplot from above that irritated me with the high correlation of the conditional probabilities of 0.88. We can see that the high conditional probabilities are particulary high for tokens that simply appear more often (see the right column, or subplots (1,3) and (2,3)).
But it's interesting to see that they are not necessarily the documents with the high mutual information criterion values (subplots (1,2), (2,2) and (3,3)).
Overall I think things should be fine.
@Wabbit

Yes, I've build everything myself
Some classification statistics on the training sample:

true positive: 99
false positive: 52
true negative: 284
false negative: 48
Recall: 0.66
Precision: 0.66
AUC: 0.76

Here are the then most highly ranked documents (with mutual information criterion):

0,116 'automat'
0,0967    'output'
0,0849    'signal'
0,083 'execut'
0,0825    'inform'
0,0782    'input'
0,0766    'detect'
0,0736    'user'
0,0725    'display'
0,07015   'sensor'

Here are the number 490-500 in the ranked tokens:

0,01108   'lamp'
0,01104   'solid'
0,01101   'concept'
0,01101   'offer'
0,0109    'declin'
0,0109    'diagnosi'
0,0109    'ethernet'
0,0109    'flood'
0,0109    'handheld'
0,0109    'inappropri'
0,0109    'markup'

I'm not sure what you mean with "MI 2". I've been using the version of the mutual information criterion here on page 272 (there's the base 2 log in there, maybe that's where the name comes from).

@Greg Ver Steeg:

The unit on the x-axis on my plot in the first question are tokens, not documents. And the same in the scatterplot on the right side.
The way I've understood your comment is that you think I might classify a lot of documents on the unseen sample because some are longer and some are shorter. Or maybe I got it wrong?
If that's your concern (classifying documents to easily with longer text), I think it's valid, but it wasn't the question here.
Answer: You can check whether this is correct comparing to other feature selection approaches.
Also if you can use sklearn SGDClassifier (and others) there is classifier.coef_[0] property where you will find the coefficient for your model after it is fitted.
This is how you can extract feature names (words in your setting) from that
<code>feature_names = vectorizer.get_feature_names()
coefs_with_fns = sorted(zip(classifier.coef_[0], feature_names))
</code>


Fourier Series problem involving complex notation

Question: I've been trying to solve a problem regarding Fourier series. I will show you my approach and where I get stuck, as well as the teacher's approach (which I do not understand). So, basically, I'd like you to please explain to me how I can solve the problem using my method (if it is possible) and to explain to me what exactly my teacher is doing.

Problem:
a) Using complex notation, compute the Fourier series of the $2\pi$-periodic and odd function given over $[0,\pi]$ by: $$f(x)=\begin{cases}
      x & \text{if}\ \ 0\leq x\leq \frac{\pi}{2} \\
      \pi-x & \text{if} \ \ \frac{\pi}{2}< x\leq \pi\\
   \end{cases}
$$
b) Show that $$\sum_{k=-\infty}^{+\infty} \frac{1}{(2k-1)^2} = \frac{\pi^2}{4}$$

My approach:
I was able to find the Fourier series, which is the following: $$Ff(x) = \frac{2i}{\pi} \sum_{k=-\infty}^{+\infty} \frac{(-1)^k}{(2k-1)^2}\ e^{i(2k-1)x} $$
The way I thought about it is that I somehow need to find an $x$ for which I get a sum that resembles the one that I have to show (informally, I want to eliminate the $(-1)^k$ and get $1$). So I thought I need to find an $x$ such that $e^{i(2k-1)x} = (-1)^k$. So, I did that in the following way. $$e^{i(2k-1)x} = (-1)^k \\i(2k-1)x = k\cdot \text{ln}(-1)$$ Now, I'm not sure if I can do this (and I am assuming that's where my mistake comes from, even though I don't know why it might be a mistake), but I assumed that $\text{ln}(-1) = i\pi$  since $e^{i\pi} = -1$, so I have that: $$i(2k-1)x = k\cdot i\pi \\ x = \frac{k}{2k-1}\pi$$ So this tells us that at $x  = \frac{k}{2k-1}\pi$, we have: $$Ff(x) = \frac{2i}{\pi} \sum_{k=-\infty}^{+\infty} \frac{1}{(2k-1)^2}$$ If we take $k = 1$, we have that $x=\pi$. Using Dirichlet's theorem, we have that $$Ff(\pi) = \frac{1}{2}(f(\pi+)+f(\pi-)) = -\pi$$ But then, this would give me the following equation: $$-\pi = \frac{2i}{\pi} \sum_{k=-\infty}^{+\infty} \frac{1}{(2k-1)^2}$$ which is clearly incorrect. But I can't spot my mistake and I don't know if my approach leads to the right answer.

Teacher's method:
The teacher found the same Fourier series that I did and he said the following:
Since f is continuous, we have that for $x \in [-\pi/2,\pi/2]$: $$x=\frac{2i}{\pi} \sum_{k=-\infty}^{+\infty} \frac{(-1)^k}{(2k-1)^2}\ e^{i(2k-1)x}$$ If we take $x\in [-a,a]$ we have that $(\pi/2a)x \in [-\pi/2,\pi/2]$ and therefore $$x = \frac{4ia}{\pi^2} \sum_{k=-\infty}^{+\infty} \frac{(-1)^k}{(2k-1)^2}\ e^{\frac{i\pi(2k-1)x}{2a}} $$ This is the step that I don't understand at all. First of all, what is $a$ ? And how does he get to the previous expression?
And hence, if we take $x=a$, we obtain :$$\sum_{k=-\infty}^{+\infty} \frac{1}{(2k-1)^2} = \frac{\pi^2}{4}$$ That last step makes sense to me (as all he did was substitute $x$ by $a$ in his previous expression, which indeed allows us to show what we want).
Comment: It would seem as if one could simply take $x=\pi/2$. Then $e^{i(2k-1)\pi/2} = e^{i k \pi}e^{-i \pi/2} =-i(-1)^k$, at which point the result follows immediately. (This is equivalent to taking $a=\pi/2$ in the teacher's route, but I honestly don't see the sensibility behind their approach.) By contrast, when $x=\pi$ one instead has $e^{i(2k-1)\pi} = e^{2\pi i k}e^{-i \pi}=-1$ for all $k$ which is not that helpful.
Answer: In your solution, you get a value of $x$ that depends on $k$. As $k$ varies over all integers, you get different values each time. So you are effectively doing a sum
$$\sum_{k=-\infty}^\infty a_k e^{i(2k-1)x_k},$$
which has no meaning whatsoever.
Let's just think about this: As you pointed out, we have $e^{i\pi} = -1$ and so $e^{i\ell\pi} = -1$ whenever $\ell$ is an odd integer and $e^{i\ell\pi} = +1$ whenever $\ell$ is an even integer. The way to take advantage of this observation, as Semiclassic commented, is to look at the expression $2kx$ appearing in the formula $e^{i(2k-1)x} = e^{i(2k)x}e^{-ix}$. $2k$ is always even, but if we put $x=\pi/2$, then $e^{i(2k)(\pi/2)} = e^{ik\pi} = (-1)^k$, by our beginning observation. Then, remembering that $e^{-i\pi/2} = -i$, we have
\begin{align*}
F(f)(\pi/2) &= \frac{2i}{\pi}\sum \frac{(-1)^k}{(2k-1)^2} e^{i(2k-1)(\pi/2)}  \\
&= \frac{2i}{\pi}\sum \frac{(-1)^k}{(2k-1)^2}(-1)^k e^{-i\pi/2} \\
&= \frac2{\pi} \sum \frac 1{(2k-1)^2}.
\end{align*}
Since $f$ is continuous at $\pi/2$, we have $\mathcal Ff(\pi/2) = f(\pi/2) = \frac{\pi}2$, and the result follows.
Final comments: No, your approach cannot be salvaged. You need to find a single value of $x$ to use. And I have no idea why your teacher put in the unnecessary parameter $a$. He's changing the "periodic domain" from $[-\pi,\pi]$ to $[-2a,2a]$, but for what reason I have no idea.
Comment: Got it, thank you
Comment: @TedShifrin - Hi Dr. Shifrin, I have a bit of a quick question after reading your post: given two variables $x$ and $y$, does the statement "$y$ depends on $x$" usually mean that $y=f(x)$ for some function $f$?


Estimate of an AR model

Question: I have this part of a project which states this:
Once you choose the best three models for each series (according to AIC, the PACF and ACF, and "from general to specific), the next step is to estimate these
6 models. You should present the final models (estimates and t-stats) and the proof that the residuals are white noise (you can use for this Q-stat or check if residuals have serial correlation with 5% significance level).
In the previous step I had to find the parameters of the AR model, and in order to check if residuals are white noise I run the Ljung-Box test in this way (given the cutoff of the PACF of my differentiated time series is 6, I wanted to validate an AR(6). I defined x as my diff(log(gdptimeseries)).
ar6=arima(x,order=c(6,0,0)
Call:
arima(x = gdplogdiff, order = c(6, 0, 0))

Coefficients:
         ar1      ar2     ar3      ar4      ar5     ar6  intercept
      3.3058  -4.5471  3.0440  -0.6789  -0.3044  0.1651      0e+00
s.e.  0.0579   0.2025  0.3345   0.3343   0.2021  0.0576      4e-04

sigma^2 estimated as 8.669e-09:  log likelihood = 2250.22,  aic = -4484.44

What I'm I now supposed to do? how do I estimate the parameters and the t-stats of the model?
Answer: The estimated values of the autoregressive parameters are already reported in the output you provided:
Coefficients:

         ar1      ar2     ar3      ar4      ar5     ar6  intercept
      3.3058  -4.5471  3.0440  -0.6789  -0.3044  0.1651      0e+00

The associated standard errors are listed immediately below these estimated values:
         ar1      ar2     ar3      ar4      ar5     ar6  intercept

s.e.  0.0579   0.2025  0.3345   0.3343   0.2021  0.0576      4e-04

The t-values are obtained as the ratio of the estimated autoregressive coefficient to its corresponding standard error. For example, the t-value for testing the null hypothesis thar the (true) first autoregressive coefficient is 0 against the alternative hypothesis that it is different from 0 is given by:
t = 3.3058/0.0579

and you can compare its absolute value against the critical value 1.96 from a standard normal distribution to decide whether you can reject the null hypothesis in favour of the alternative hypothesis based on the evidence in your data at the usual 5% significance level.

Estimate of an AR model


How to interpret KPSS test

Question: I have been trying to understand the kpss test and I have read this answer and have been reading information from this KPSS Test: Definition and Interpretation , but am still confused about my own results.
I am confused because the critical values for 1,5,10% etc. I receive on my own data  do not follow the order I would expect.
The null hypothesis is that the data is stationary.
I reject the null hypothesis if the test statistic > the critical value.
I would expect it to be "easier" to reject the null at the 1% and "harder" to reject the null at 10%.  In other words I expect the critical values to be in a sequence 1%<2.5%<5%<10%
I have a series of hourly temperature data and if I run the KPSS test from statsmodels I get the following output
kpss(series, lags = 230)
(0.70411510645393605,
 0.013171353958733086,
 230,
 {'1%': 0.739, '10%': 0.347, '2.5%': 0.574, '5%': 0.463})

Do my results mean that I would reject the null hypothesis at the 10%, but not at the 1%?
Also in the KPSS Test: Definition and Interpretation  table for the critical values they are in the order 1%>5%>10%, which would imply at a given test statistic you can reject at the 5 or 10%, but not at the 1%.
Can someone tell me what I am missing?
Comment: That's a basic property of hypothesis tests, 1% is further out in the tail, than 5% or 10%.
Comment: Ok, from [Hypothesis Testing (Critical value approach)](https://onlinecourses.science.psu.edu/statprogram/node/137), "Compare the test statistic to the critical value. If the test statistic is more extreme in the direction of the alternative than the critical value, reject the null hypothesis in favor of the alternative hypothesis. If the test statistic is less extreme than the critical value, do not reject the null hypothesis."  In my data it starts out larger then gets smaller, the implication with 1>10 is that the larger number is in direction of the null hypothesis.
Comment: Look at the plots in your link, and compare critical values at 5% and 10% (or 0.05 and 0.025 for one-sided case)
Comment: I see 10%<5%<1% for critical values.  I also read that "If the test statistic is more extreme in the direction of the alternative than the critical value, reject the null," but KPSS states "reject the null hypothesis if the test statistic > the critical value".  However, to me a larger test statistic is heading in the direction of the null hypothesis, farther out on the tail in the direction of the null.
Answer: As already mentioned in the comments the statistic value have to be more extreme than the chosen critical value. In your linked blog there is good image describing it:

The statistic value determines the position in this probability distribution. As you can see a more extreme value can be lower or higher than your signifance level (left or right tail of the distribution).
Because the distribution has zero mean you can just use the absolute value of both test value and critical value:
|kpss_val| > |critical_value| = null rejected
You may also use the p value which is returned by the statsmodel implementation. Note that it's only in the range [0.01, 0.1]. You can reject it with p=0.01 and you may not reject it at p=0.1.
p < significance_level = null rejected
If it's still not clear I propose reading the related chapter in the Wikipedia article. It explains more the intuion behind the hypothesis test and its rejection.
Concluding here the code I came up with for my time series analysis (testing KPSS and ADF):
import statsmodels.tsa.stattools as stats
import numpy as np

# Reject any null hypothesis if p value is below a significant level / statistic value is more extreme than the related critical value
# Weak assumption: If we can't reject a null hypothesis we assume that it's true
# p=100% would mean the null hypothesis is correct. Below 5% we can "safely" reject it

# Null hypothesis: is stationary
def is_stationary(X): # = not able to reject null hypothesis
    # Null hypothesis: x is stationary (not trend stationary); Note: test tends to reject too often
    kpss_stat, p_value, lags, critical_values = stats.kpss(X)
    return abs(kpss_stat) < abs(critical_values['5%'])
    # Same as return p_value >= 0.05

# Null hypothesis: has unit root = I(1)
def has_unit_root(X): # = not able to reject null hypothesis
    # Null hypothesis: x has a unit root (= is not stationary, but might be trend stationary)
    adf_stat, p_value, used_lag, nobs, critical_values, icbest = stats.adfuller(X)
    return abs(adf_stat) < abs(critical_values['5%'])
    # Same as return p_value >= 0.05

a = np.arange(100)
print('Has test #1 (linear function) a unit root ? ->', has_unit_root(a))
print('Is test #1 (linear function) stationary ? ->', is_stationary(a), end='\n\n')
b = np.random.rand(100)
print('Has test #2 (white noise) a unit root ? ->', has_unit_root(b))
print('Is test #2 (white noise) stationary ? ->', is_stationary(b), end='\n\n')
c = np.cumsum(b - 0.5)
print('Has test #3 (random walk) a unit root ? ->', has_unit_root(c))
print('Is test #3 (random walk) stationary ? ->', is_stationary(c), end='\n\n')

Output:

Has test #1 (linear function) a unit root ? -> True
Is test #1 (linear function) stationary ? -> False
Has test #2 (white noise) a unit root ? -> False
Is test #2 (white noise) stationary ? -> True
Has test #3 (random walk) a unit root ? -> True
Is test #3 (random walk) stationary ? -> False

I hope I did everything right. Otherwise don't hesitate to give me feedback so we have a final answer to this problem.
Greetings,
Thomas
Comment: I think you could make it more explicitly answer what the confusion is. I think the OP is looking for a simple clear concise answer on why the critical values are the opposite to their intuition. As the comments make clear the intuition is wrong, so the answer needs to show why and what the correct understanding should be.
Comment: Thanks for your valuable feedback! I just wanted to put my two cents worth in since I guess my code is useful for other people ending up here. I hope I'll find soon the time to write a deeper explanation. However until now I'm not thaaat much into econometrics so I wouldn't say that I can describe/explain it easily (if I got it right at least xD).

How to interpret KPSS test


How to pass form input to ctools modal

Question: I have a regular Drupal form that is not in a modal. When the user submits the form, a ctools modal popup opens (as per http://drupal.org/node/1482968).
My question is, what is the best method for passing form input to the modal? So that e.g. if the user enters their name ("Alex") in the form, the modal popup can read, "Welcome Alex!" ?
I am using Drupal 7 and the latest stable release of Ctools. (Also, I've asked this question in the ctools issue queue at http://drupal.org/node/1556856, but haven't had a reply in twenty days.) I've been trying to crack this one for a while, so would be incredibly grateful for any help!
Answer: Ended up just grabbing the passed variables from $_GET.

How to pass form input to ctools modal