Spring AOP BeanCreationException when adding a simple Before advice

Question: I am new to Spring AOP. I wrote an aspect with a simple @Before advice, which looks like this
package testing_spring;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class MyTestAspect {

  @Before("execution(public void open())")
  public void runThis() {
    System.out.println("About to open something ...");
  }
}

This is the context.xml file:
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

  <aop:aspectj-autoproxy />

  <bean class="testing_spring.House" name="house">
    <property name="windows">
      <list>
        <ref bean="window1"/>
        <ref bean="window2"/>
        <ref bean="window3"/>
      </list>
    </property>
    <property name="doors">
      <list>
        <ref bean="door"/>
      </list>
    </property>
  </bean>

  <bean class="testing_spring.Window" name="window1" id="window1"/>
  <bean class="testing_spring.Window" name="window2" id="window2"/>
  <bean class="testing_spring.Window" name="window3" id="window3"/>

  <bean class="testing_spring.Door" name="door" id="door"/>

  <bean class="testing_spring.MyTestAspect" name="mta"/>
</beans>

The rest are just some simple classes for testing:
package testing_spring;

public abstract class Openable {

  private boolean open;

  public void open() {
    open = true;
  }

  public void close() {
    open = false;
  }

  public boolean isOpen() {
    return open;
  }
}

package testing_spring;

public class Door extends Openable {

}

package testing_spring;

public class Window extends Openable {

}

import java.util.*;

public class House {

  private List<Window> windows;
  private List<Door> doors;

  public void setWindows(List<Window> windows) {
    this.windows = windows;
  }

  public void setDoors(List<Door> doors) {
    this.doors = doors;
  }

  public List<Window> getWindows() {
    return windows;
  }

  public List<Door> getDoors() {
    return doors;
  }
}

package testing_spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

  public static void main(String[] args) {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");

    House house = (House) ctx.getBean("house");
    printHouseInfo(house);
  }

  public static void printHouseInfo(House house) {
    System.out.println("My house has " + house.getDoors().size() + " doors and " + house.getWindows().size() + " windows.");
  }
}

So, when I run the main method, what I get is:
cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'house' defined in class path resource [context.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException

But when I comment out the @Before annotation, everything works fine, it prints:
My house has 1 doors and 3 windows.

So there must be something wrong with the before-advice, but I do not understand, what it is.
Comment: There is nothing wrong with your advice. You just don't have the needed dependencies for applying AOP. That is what the `java.lang.NoClassDefFoundError` is telling you.
Comment: Thanks, you were totally right!
Answer: You might have not added classpath for aspectj-weaver.jar


More than one ejb found with interface of type for binding

Question: I have an interface like this:
<code>@Local
public interface MyInterface {
}
</code>
And two classes that implements this interface:
<code>@Singleton
public class FirstBean implements MyInterface {
}

@Singleton
public class SecondBean implements MyInterface {
}
</code>
And another class like below:
<code>@Singleton
public class ThirdBean {

    @EJB
    private MyInterface xpto;

}
</code>
And i am receiving the following error on deploy:
More than one ejb found with interface of type for binding
How to solve it?
Answer: Try to use qalifier
<code>@java.lang.annotation.Documented
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE,ElementType.FIELD})
@javax.inject.Qualifier
public @interface First {

}
</code>
Mark bean using this qualifier
<code>@Singleton
@First
public class FirstBean implements MyInterface {
}
</code>
Then inject it
<code>@Singleton
public class ThirdBean {

    @Inject
    @First
    private MyInterface xpto;

}
</code>


Python, cannot use geometry manager pack inside

Question: I am having several errors after the installation of Anaconda.
When I run a program I get the message:
TclError: cannot use geometry manager pack inside . which already has slaves managed by grid

The program was written using Python 3.3. The Anaconda version is for 3.4. But I don't think there were any syntax differences between 3.3 and 3.4.
I searched and could not find any solution for this error.
I don't even know what it means.
Thank you.
Answer: This error can occur if you mix pack() and grid() in the same master window. According the docs, it is a bad idea:

Warning: Never mix grid and pack in the same master window. Tkinter
  will happily spend the rest of your lifetime trying to negotiate a
  solution that both managers are happy with. Instead of waiting, kill
  the application, and take another look at your code. A common mistake
  is to use the wrong parent for some of the widgets.

For example, this code is working for Python 3.3.x, but isn't working on Python 3.4.x (throws the error you mentioned):
from tkinter import *
from tkinter import ttk

root = Tk()

mainframe = ttk.Frame(root)
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))

nb = ttk.Notebook(root)
nb.pack()

root.mainloop()

And this code isn't working for both Python versions:
from tkinter import *
root = Tk()

Label(root, text="First").grid(row=0)
Label(root, text="Second").pack()

root.mainloop()

To avoid this, use only one geometry manager for all children of a given parent, such as grid().
Answer: The error means that you're doing something like this:
widget1 = tk.Label(root, ...)
widget2 = tk.Label(root, ...)

widget1.grid(...)
widget2.pack(...)

You cannot mix both pack and grid on widgets that have the same parent. It might work on some older versions of tkinter, but only if you're lucky. The solution is straight-foward: switch to using only grid, or only pack, for all widgets that share the same parent.
The code was appearing to work in one version but not the other likely because the later version uses a newer version of tkinter. Tkinter didn't use to give this warning -- it would try to continue running, usually with disastrous results. Whether the program worked or froze was dependent on many factors. Usually the program would freeze and use close to 100% cpu, sometimes it would work, and sometimes it would work until you resized the window. Regardless, it's something you shouldn't do any any version of Tkinter.


How to import Custom Post Types of wordpress into Drupal?

Question: I've a wordpress site with around 500+ posts of a Custom Post Type with some custom fields attached to them.
I want to migrate them to Drupal. I've tried using wordpress_migrate. But it doesn't seem to work! This module didn't even seem to recognize the Custom Post Types. How can I import them?
Answer: This isn't currently available in wordpress_migrate however there is a feature request open here. https://drupal.org/node/1580412
Your best option would be to write a custom migration using Drupal's migrate module. You would need to write a custom source to load your data from WordPress and you'd be able to look at wordpress_migrate for help as needed.


SPF/DKIM/DMARC for Gmail "Send mail as" via smtp.gmail.com on external domain

Question: Since "Google Apps" / "Google Apps for business" / "G-Suite" / "Google Workspaces" free tier is being discontinued, I need a solution to migrate my ~30 extended family to a sustainable solution.
I'm looking at the option of having them each piggy-back off a personal @gmail.com address they should each create, forwarding the email, and adding the address using "Send mail as" in gmail, using Google's gmail SMTP server and an app-specific password:

I'm using CloudFlare for DNS, and I've activated the CloudFlare Email routing (beta) feature, and I've set the MX records to the various .mx.cloudflare.net servers. I also added the CloudFlare SPF TXT record: v=spf1 include:_spf.mx.cloudflare.net ~all.
Now, it all seems to be working, except what is happening is sent emails seem to often end up in junk/spam. I guess this is possibly something to do with SPF/DKIM/DMARC but this is way outside my domain of knowledge.
I've modified the SPF header from v=spf1 include:_spf.mx.cloudflare.net ~all to v=spf1 include:_spf.mx.cloudflare.net include:_spf.google.com ~all as I saw suggested elsewhere, but that doesn't seem to have solved the problem.
Is it possible to add DKIM and/or DMARC records, and if so, how? My (limited) understanding is that Google would need to give me a key (probably unique to my account) to add, which validates that not only is it Google/gmail that's sending the mail, but specifically me and not some other random gmail user.
Moreover, how would this work with the other users? I need all users to be able to reliably be able to send/receive emails and not have them end up in spam/junk.
If this were like SSH, I would generate a key pair, put the public key on the DNS and each user would add the same private key somewhere in their "Send As" on their gmail settings.
I guess this is probably unrelated to emails getting into spam/junk but I added the _dmarc TXT record: v=DMARC1; p=none; rua=mailto:{{email@example.com}}; ruf=mailto:{{firstname.lastname@example.com}}; sp=none; fo=1; ri=86400.
Comment: Did you already found a way to use DKIM for your custom domain? I have the same configuration in gmail where I use "Send mail as" to use my custom domain, and use Google Domains email forwarding to receive mails.
Comment: No, I just paid for a POP/SMTP server for my non-gmail address. I still use the "Send mail as" feature. Since it's going through the 3rd party SMTP server, it's possible to use DKIM.
Comment: There is a very good chance this solution will forever be in and out of spam folders. The better solution is a hosted mail solution. Some spam conditions can only be cleared by reviewing the transactions with the MTA in the mail logs.
Answer: Sometime i would advise to try is a test email thing like this one : https://tools.redsift.com/sift/investigate
there you can see how your email is evaluated and if theres a problem it will flag it.
they also has an extensive knowledge base article on cloudflare and how to set it up correctly:
https://knowledge.ondmarc.redsift.com/en/articles/2699998-what-is-a-dmarc-record-and-how-do-i-create-it-in-dns-using-cloudflare
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: I found a free solution. It requires hosted mail, though.
There are other transactional email providers out there, but I used SendGrid because it's free (up to 100 emails/day). https://app.sendgrid.com
You just have to add and verify your domain with the given DNS registers.
You then create the sender identities of the different email users in your domain and then use the SMPT tool they have.
They will generate an API key for you (it's really important to save it somewhere because it won't be shown to you again) and then you add your address to the "Send mail as" section of your Gmail account, using smpt.sendgrid.net, "apikey" as the username and the API key you were given as the password.
The user and password are the same for every email address of your domain, it won't be a personal key like when using smpt.gmail.com.
By doing this, emails of your domain will have DKIM security. To obtain SPF security you just have to add sendgrid and gmail (just in case) to the SPF register of your DNS. I haven't been able to add DMARC security yet, but I'm certain that it is possible.
In relation to the original question, I don't think there is a way to get DKIM and DMARC using smpt.gmail.com. Sorry if this was out of topic.
Answer: I haven't done this myself yet, but I assume I'll have to do something similar.
This question was linked from https://www.reddit.com/r/gsuite/comments/s9n7b9/gsuite_email_host_alternatives_with_prices/, I'm surprised no-one from there has responded here.
It looks to me like you should be able to avoid your DKIM issues by configuring Gmail to use a custom SMTP server, and there are free SMTP hosts for personal amounts of email (e.g. <30 per day). A popular one seems to be https://www.sendinblue.com/.
A downside of that appears to be that they will add a forwarding tracking domain to links in any outgoing email. This may or may not bother you. But I believe it should solve the spam problem.
Curious to hear if anyone else knows of free SMTP hosts who don't add the tracking domain.


Sending intent to another application without opening it in android

Question: I have two application and i want to start second application from first one when button pressed. However i dont want the second one to come front. It will do its work on background. How can i do this? Please give me a guide. I tried this but it opens the application and comes front and thats not what i want
<code>       Intent intent = getPackageManager().getLaunchIntentForPackage(
                "com.example.abc");
        if (intent == null) {
            Toast.makeText(this, R.string.app_not_found, Toast.LENGTH_SHORT)
                    .show();
        } else {
            intent .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent .putExtra("str", "str");
            startActivity(intent );
        }
</code>
Thanks in advance
Comment: Reading your question and your comments to the answers that have been provided leads me to think that your architecture is flawed. It sounds like you need 2 different things: You need an `Activity` that is launched by the user, that has UI; and you need a `Service` that other applications can use to reuest that your application do something for them. These are completely different things.
Answer: You are calling an activity so it will open up the activity in front. You should call BroadCastReceiver, this will open up in background. Click Here this is how i have done using BroadCastReceiver.
Answer: Activities are used when you want a UI. They should not be dealing with background tasks if your code architecture is good.
What you need to be doing instead is separate the "background" stuff of the other activity into an exported Service, and call that instead.
Comment: my application should run with UI when directly opened but it must run in background when opened from another application
Comment: Yes, this is why when you open it directly, you start an Activity that starts the Service for the background stuff. And you don't launch your app from another application, you start its exported Service.


The implicit differentiation of trignometry equations

Question: Use the process of implicit differentiation to find $\dfrac{dx}{dy}$
given that  $\sin(x)+ \sin(3y) = 1 $
Can anyone give me hints or steps on what to do?
Answer: If the implicit derivative confuses you then think of both $x$ and $y$ being functions of $t$ and take $\dfrac{d}{dt}$ of both sides:
\begin{equation}
\cos(x)\dfrac{dx}{dt}+3\cos(3y)\dfrac{dy}{dt}=0
\end{equation}
Then rewrite as
\begin{equation}
\cos(x)\,dx+3\cos(3y)\,dy=0
\end{equation}
And solve to obtain
\begin{equation}
\dfrac{dx}{dy}=-\dfrac{3\cos(3y)}{\cos(x)}
\end{equation}
Comment: Than you so much and for the tip of thinking of it as t, I struggle with implicit derivative and this has helped me so much thank you/
Comment: I accidentally solved for $\dfrac{dy}{dx}$ instead of $\dfrac{dx}{dy}$ as you asked but have corrected that.


Me foi passado este exercicio: "TODOS OS CLIENTES QUE COMPRARAM MAIS DE R$ 200,00 NO ÚLTIMO MÊS"

Question: SELECT clientes.nome,clientes.sexo,
       SUM(pedidos.valor_pedidos) AS total_gasto,clientes.cidade

FROM clientes

INNER JOIN pedidos
  ON clientes.id_clientes = pedidos.id_clientes

WHERE sexo LIKE 'F%'
AND valor_pedidos >= 100

GROUP BY nome;

porem minha query não retorna o valor da soma, retorna o valor unitário. Alguém pode me ajudar?
Comment: Me parece que você está desconsiderando a restrição "no último mês".
Answer: Você esqueceu de agrupar o sexo. Faltou algumas boas praticas de programação para facilitar a leitura e evitar erros, eu não gosto de utilizar as condicionais no cruzamento (Inner Join) como o sexo like 'f%' e sim no Where, recomendo esse método para evitar dores de cabeça, segue o código ajustado:
SELECT clientes.nome,clientes.sexo,
       SUM(pedidos.valor_pedidos) AS total_gasto,clientes.cidade

FROM clientes

INNER JOIN pedidos
  ON clientes.id_clientes = pedidos.id_clientes

WHERE sexo LIKE 'F%'
AND valor_pedidos >= 100

GROUP BY clientes.nome,clientes.sexo;

Nesse exercício que te passaram, você irá precisar trazer o campo mês e agrupar ele, se só tiver a data você deverá realizar o MONTH() e ignorar esse AND valor_pedidos >= 100, pois você só poderá verificar esse resultado depois da soma. Particularmente eu utilizaria um subselect para trazer o resultado dessa consulta:
SELECT nome,sexo,mes,total_gasto

FROM(

     SELECT clientes.nome,clientes.sexo,pedidos.mes
            SUM(pedidos.valor_pedidos) AS total_gasto,clientes.cidade

     FROM clientes

     INNER JOIN pedidos
       ON clientes.id_clientes = pedidos.id_clientes

     WHERE sexo LIKE 'F%'

     GROUP BY clientes.nome,clientes.sexo,pedidos.mes) --SUBSELECT

WHERE total_gasto >= 200;

Answer: A cláusula HAVING poderá ser útil para a solução de seu problema.
Supondo que exista um campo data em sua tabela pedidos e que "último mês" seja o mês anterior ao mês corrente tente:
SELECT clientes.nome, clientes.sexo, SUM(pedidos.valor_pedidos) AS total_gasto, clientes.cidade
FROM clientes
INNER JOIN pedidos ON (clientes.id_clientes = pedidos.id_clientes)
WHERE clientes.sexo LIKE 'F%'
  AND YEAR(pedidos.data) = YEAR(DATE_SUB(CURDATE(),INTERVAL 1 MONTH))
  AND MONTH(pedidos.data) = MONTH(DATE_SUB(CURDATE(),INTERVAL 1 MONTH))
GROUP BY clientes.nome, clientes.sexo, clientes.cidade
HAVING SUM(valor_pedidos) >= 200;


Java: How do i split a string, to read commands and call methods?

Question: I am currently making a small Java program which features multiple rooms.
I am still new to Java so the less complicated the code, the better.
The player has to be able to travel between rooms, but can only do so via the "go (direction)" command, eg: go west.
How do i split this input so i can call my travel method when the player enters "go" as the first part of their input?
At the same time, a direction will need to be registered so the game knows what the next room will be. (Split the second part of the input).
Help will be much appreciated.
Answer: Sounds like you could use substring in Java and operate on your commands that way :
   String str= new String("quick brown fox jumps over the lazy dog");

   System.out.println("Substring starting from index 15 and ending at 20:");
   System.out.println(str.substring(15, 20));

output:
   Substring starting from index 15 and ending at 20:
   jump

you could also use regular expressions along with split like this :
        public static void main(String[] args) {

        String str = "abdc124psdv456sdvos456dv568dfpbk0dd";

        // split the array using a single digit, e.g 1,2,3...

        String[] parts = str.split("[0-9]");

        System.out.println(Arrays.toString(parts));

        // split the array using a whole number, e.g  12,346,756

        parts = str.split("[0-9]+");

        System.out.println(Arrays.toString(parts));

    }

link: using split with regex
link : using substring
Answer: Based on your description the input will be go west or go east or go south or go north, suppose if we have string with value go west
String input = "go west";

Then split input string based on space delimiter will return String array
String[] dir = input.split(" ");
dir[0] // will be `go`
dir[1] // will be direction `west`

Then compare dir[0] using equals() method, if true call the method with direction
if(dir[0].equals("go")){
   //action
   }

Comment: I would use String.spit(" +") (empty space followed by plus). Since split uses regex you could handle the situation that someone enters more than one space.
Comment: This seems to work, thanks.EDIT: does it also work with a scanner? if so, do you know how?
Comment: I know, but you should give a try, it's so simple just google it, try and if you stuck at any point post the code i will help you out


Java-TestNG : Read an excel file, assert and write back to the excel file through TestNG & Apache POI

Question: I am working on a POC with Selenium Java and TestNG using Apache POI. I have an excel sheet in which Column A contains urls, Column B contains a status (yes or no) whether to read/execute with the corresponding url or not.I want to save back the execution status Pass/Fail in a Column C.
My excel sheet "TestData.xlsx" .
My calling file "read_write_excel.java" is as follows:
package Read_Write_Excel;
import org.testng.annotations.Test;
import libraries.read_excel_data;
public class read_write_excel
{

    String path = "C:\\SeleniumUtilities\\excelData\\TestData.xlsx";
    @Test
    public void read_excel() throws Exception
    {
        read_excel_data excel = new read_excel_data(path);
        excel.read_data(0);
    }
}

Reading the excel sheet through "read_excel_data.java" as follows:
package libraries;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class read_excel_data
{

    XSSFWorkbook workbook;
    XSSFSheet sheet;
    String location;
    int SheetNo;
    write_excel_data write_excel;
    public read_excel_data(String excelPath)
        {
            location = excelPath;
            try {
                File src = new File(excelPath);
                FileInputStream fis = new FileInputStream(src);
                workbook = new XSSFWorkbook(fis);
                write_excel = new write_excel_data(location);

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

    public void read_data(int sheetNumber) throws Exception
    {
        SheetNo = sheetNumber;
        sheet = workbook.getSheetAt(sheetNumber);
        int rows = sheet.getLastRowNum();
        System.out.println("Total number of Rows to read : "+(rows+1));
        for(int i=0;i<=rows;i++)
        {
            XSSFRow now_row = sheet.getRow(i);
            if(now_row.getCell(1).getStringCellValue().equalsIgnoreCase("yes"))
            {
                String data = now_row.getCell(0).getStringCellValue();
                System.out.println("Data from Row "+i+" is: "+data);
                String status = assertion.asserting(data);
                System.out.println("Status is : "+status);
                write_excel.write_data(SheetNo,i,status);
            }
        }

        workbook.close();
    }

}

Assertions are done in "assertion.java" like:
package libraries;
public class assertion
{

    public static String asserting(String url)
    {
        String result;
        if(url.contains("com"))
            {
                result = "Pass";
                System.out.println("Result is : "+result);
                return result;
            }
        else
            {
                result = "Fail";
                System.out.println("Result is : "+result);
                return result;
            }

    }
}

Writing back to the excel file through "write_excel_data.java" like:
package libraries;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class write_excel_data
{

    File des;
    XSSFSheet sheet;
    XSSFWorkbook wb;
    public write_excel_data(String location)
    {
        try {
            des = new File(location);
            FileInputStream fis = new FileInputStream(des);
            wb = new XSSFWorkbook(fis);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

    public void write_data(int sheetNo,int i, String status) throws Exception
    {
        sheet = wb.getSheetAt(sheetNo);
        int rows = sheet.getLastRowNum();
        System.out.println("Total number of Rows to write : "+(rows+1));
        sheet.getRow(i).createCell(2).setCellValue(status);
        FileOutputStream fos = new FileOutputStream(des);
        wb.write(fos);
        wb.close();
    }
}

The issue I am facing are:

Sometimes I run into a NullPointerException
Sometime the Excel sheet gets corrupted and doesn't writes at all.

Can you please let me know:

Is my approach correct?
Any suggestion for betterment?
If I am doing any mistakes here.

Update -1:
Latest Stacktrace:
[TestNG] Running:
  C:\Users\DEDLY\AppData\Local\Temp\testng-eclipse--1619303069\testng-customsuite.xml

Total number of Rows to read : 3
Data from Row 0 is: a.com
Result is : Pass
Status is : Pass
Total number of Rows to write : 3
Data from Row 1 is: b.com
Result is : Pass
Status is : Pass
Total number of Rows to write : 3
[Utils] Attempting to create C:\Users\DEDLY\workspace\SeleniumJavaTestNG\test-output\Default suite\Default test.xml
[Utils]   Directory C:\Users\DEDLY\workspace\SeleniumJavaTestNG\test-output\Default suite exists: true
FAILED: read_excel
org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: Rule M2.4 exception : this error should NEVER happen, if so please send a mail to the developers team, thanks !
    at org.apache.poi.openxml4j.opc.internal.ContentTypeManager.getContentType(ContentTypeManager.java:342)
    at org.apache.poi.openxml4j.opc.internal.ContentTypeManager.removeContentType(ContentTypeManager.java:255)
    at org.apache.poi.openxml4j.opc.OPCPackage.removePart(OPCPackage.java:943)
    at org.apache.poi.openxml4j.opc.PackagePart.getOutputStream(PackagePart.java:522)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.commit(XSSFWorkbook.java:1546)
    at org.apache.poi.POIXMLDocumentPart.onSave(POIXMLDocumentPart.java:332)
    at org.apache.poi.POIXMLDocument.write(POIXMLDocument.java:195)
    at libraries.write_excel_data.write_data(write_excel_data.java:38)
    at libraries.read_excel_data.read_data(read_excel_data.java:51)
    at Read_Write_Excel.read_write_excel.read_excel(read_write_excel.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:100)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:646)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:811)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1137)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
    at org.testng.TestRunner.privateRun(TestRunner.java:753)
    at org.testng.TestRunner.run(TestRunner.java:607)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:368)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:363)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:321)
    at org.testng.SuiteRunner.run(SuiteRunner.java:270)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1284)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1209)
    at org.testng.TestNG.runSuites(TestNG.java:1124)
    at org.testng.TestNG.run(TestNG.java:1096)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)

===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================

Update - 2:
When I try to open the "TestData.xlsx" manually, I get the following error as .
Comment: Please paste a stack trace from your null pointer exception.  Also when you don't have issue 1 or 2, does it work correctly as you expect?
Comment: @BillK Thanks, I have updated my Question with the latest stacktrace. Would you please have a look?
Comment: before wb.close(); try to use wb.flush();
Comment: @AnandGaneshSS Thanks. But Eclipse IDE shows an error as `The method flush() is undefined for the type XSSFWorkbook` while I try to add the line.
Comment: The file is opened twice at the same time. You should try to pass `XSSFWorkbook` in `write_excel_data` first.
Answer: Just looking at your stack trace it looks like it might have something to do with cell types (the top-most calls are "removeContentType" and "getContentType".  I assume that this means it's trying to put a string in an int cell or perhaps a cell that doesn't exist.
Try putting text in each of the three cells in column C for a start.  If that works you might look through the API to see if there is a way to set the type for that cell.
If that doesn't work you could try to save your initial spreadsheet (from Excel) as an older type.  Sometimes Poi doesn't work as well with the newest excel versions.
I can't figure out where you are setting "des", have you omitted some code or did you forget to set it?  At any rate, try a different source/destination, don't overwrite (I can't tell if you are).
Also, since you asked for suggestions:

Java wants ALL packages (in the world) to be uniquely named, so instead of using "libraries" as a package, consider com.mycompany.project.libraries or something like that.
All your variables should always be private.  Just do that.  The only exception is "public final static" constants, and they should only reference immutable objects (int, String, ...)
Class names should be (for example) WriteExcelData instead of write_excel_data.  Although this is only a pattern, it is very consistently used in the community.


What is a record for a football player in converting consecutive penalties in official matches?

Question: Various sources mentioned that Mario Balotelli recently missed a penalty for the first time in his career (in a professional match).
For example here:

Balotelli has never failed to convert any of his previous 21 penalties in official matches but saw his remarkable run halted when Pepe Reina stooped low to save the Italian's effort to his right just after the hour mark.

And another source:

The Italy striker has developed a reputation as a deadly penalty-taker and up until the miss against Napoli he had successfully converted all 26 of his spot-kicks for club and country.

What is the largest number of consecutive penalties converted by a player in competitive matches?
Comment: Some statistics of remarkable penalty takers are mentioned in this question on Quora: [Who are some of the best penalty takers in the history of football?](http://www.quora.com/Football-soccer-2/Who-are-some-of-the-best-penalty-takers-in-the-history-of-football-and-has-a-record-to-prove-it)
Answer: Rickie Lambert converted all of his 34 penalties for Southampton FC. (Although he missed some penalty kicks in some of his previous clubs. And after transfer from Southampton to Liverpool he did not convert his first penalty in a friendly against AC Milan.)

Wikipedia article which provides some further references. (Link to current revision.)
Masters from the penalty spot; article on the UEFA website. (17 August 2013, Wayback Machine)
Daily Mail article Right from the Le Tissier school! Lambert is Southampton's new penalty king as textbook spot-kick at West Brom preserves flawless record of 32 goals from 32 (19 August 2013, Wayback Machine
Daily Mail article Rickie Lambert's long-standing penalty scoring record comes to an end as Liverpool striker sees spot-kick saved in Milan friendly which includes list of his penalties. (3 August 2014, Wayback Machine)

Based on his statistics on soccerway, he scored penalty goals for Southampton in the following competitions:

Premier League: 3 in 2012/13, 3 in 2013/14
Championship: 9 in 2011/12
League One: 8 in 2010/11, 8 in 2009/10
2009-10 Football League Trophy: in penalty shootout against Torquay, and in the final against Carlisle United.

It is worth mentioning that only the last 6 penalties in this series were in Premier League, previously he played in lower competitions.
This only adds up to 33 penalties. I am not sure where the discrepancy from the sources saying that he scored 34 penalties comes from.
Comment: The statistics I've listed only add up to 31 penalties. I do not know where the difference between these numbers and the statistics from the sources I quoted come from.
Comment: Today he scored a penalty in the [match against Hull City](http://int.soccerway.com/matches/2013/11/09/england/premier-league/southampton-fc/hull-city-afc/1483563/). So if the number given by the sources were correct as of August 203, his series is now at 33.
Comment: I see that this information now appeared also in the [Wikipedia article](http://en.wikipedia.org/wiki/Rickie_Lambert#Penalty_Record) about this player. Here is link to the [current revision](http://en.wikipedia.org/w/index.php?title=Rickie_Lambert&oldid=600943867#Penalty_Record); just in case the article changes in the future.
Comment: ...but, according to the other answers, this isn't the player with the most consecutive converted penalties.
Answer: Peter Noble of Swindon Town.
Following taken from Wikipedia:

Noble ended his career having scored every penalty he took. This
  record of 28 consecutive penalties is widely believed to be a world
  record. In 1985 a question about Noble's penalty kicks appeared in the
  first edition of the popular board game 'Trivial Pursuit'.
Answer: http://sv.wikipedia.org/wiki/Rune_%C3%85ngstr%C3%B6m
Translated from the Swedish Wikipedia link:
About Rune Ångström:"
As a football player, he is renowned for the number of successful penalty kicks in a row: he made 57 successful consecutive penalties from 1949 to 1953 , and 53 consecutive pieces during the years 1942-1949
Answer: Albanian Ledio Pano has perfect record scoring over 50 penalties for various teams in Greece and Albania.
Sources:

Masters from the penalty spot; article on the UEFA website
Which highest-capped player has the fewest caps? Plus: Perfect penalty takers, The Guardian
Answer: Matthew Le Tissier was well known for his penalty taking ability. This isn't a definitive "he is the best", but his record of 47 out of 48 must be hard to beat!
Comment: I wonder why someone downvoted this. It was a honest attempt to answer the question and - as you can see from the timestamp - this answer appeared here before the information given in the other answers. (So it was, for some time, the best what we were able to find.)
Answer:
Gaizka Mendieta was considered the ultimate penalty taker. There are
  no records shown, even according to his own testimony, of him ever
  missing a penalty during his professional career!

http://www.history-of-soccer.org/mendieta.html

Ivan Krstanović (Croatia, 2000-present) The GNK Dinamo Zagreb forward
  has by all accounts never missed a penalty in his career, assuring
  UEFA.com that "it's at least 30 goals".
Hans-Joachim Abel (Germany, 1972-84) ..., but Fortuna Düsseldorf, VfL
  Bochum 1848 and FC Schalke 04 striker Abel is statistically the
  Bundesliga's best, reportedly converting all 16 of his spot-kicks.
Ledio Pano (Albania, 1986-2001) Midfielder Pano boasted a 100% record
  in over 50 penalties in his career in Albania and Greece

http://www.uefa.com/memberassociations/news/newsid=1913517.html
Answer: Dave Juneman converted 42 consecutive penalties for Tooting and Mitcham United in the 1970s.
Comment: Welcome to Sports.SE! Could you provide a source for this? If you could, this would be an excellent (if very obscure) answer.
Answer: Jonny Hubbard who played for Glasgow Rangers was another exceptionally good penalty taker. According to Wikipedia:

Hubbard was nicknamed the "Penalty King" by Rangers fans, due to his exceptional record of 65 goals scored from 68 penalty kicks, 22 consecutively.

The reference given in Wikipedia article is: http://www.thefreelibrary.com/Football%3A+THE+PERFECT+PENALTY%3B+Model+yourself+on+van+Nistelrooy+says...-a0102522683
Comment: But how many did he make consecutively?
Comment: @PhilipKendall I [have edited](http://sports.stackexchange.com/posts/12143/revisions) the post and added information I found on Wikipedia.


How are Wald type tests better asymptotically?

Question: I heard that Wald tests are better asymptotically than other tests. But what does this mean? Does it mean that it's better at testing for population level differences? Is it better for "big data" and high sample sizes?
Comment: What other tests?
Comment: don't know, lr test, score test?
Comment: Those are asymptotically equivalent. I think you'll need to provide more context to the claim, ideally a citation, for your q. to be answerable.
Answer: The Wald test is asymptotically equivalent to the likelihood ratio and (Rao) score tests. They are not better. In fact, the likelihood ratio test is the uniformly most powerful test. The score test has the advantage over the other two of 1. not requiring an evaluation of the variance under the alternative hypothesis and 2. being the framework that unifies many popular tests—the Log rank test, Cochran-Mantel Haenszel, and Pearson Chi-square tests are all Score tests.


How do I make link act like a view or a view look like a link?

Question: Good morning!
I want to create a link that displays a node, the most recently created for example. What is the best way to do that in Drupal?
I have a menu link that does what I want with:
moneymap/Pro/EURUSD/Day?sort_by=field_map_id_value&sort_order=DESC
but I don't know how that works or how to make that work in an HTML link.
I've made a few views but still a beginner? How should I proceed?
Thanks!
Comment: Thank you Anil for your time and help. I'm a little confused about the last part. I can create the view. But how do I get that view into my currently static link:

Thank you for any clarification!
Answer:
Easiest way to achieve above is using Views
Create a new view with block view

Sort Content by Post Date
Select fields as Content Display and show only one item
Enable the block by Navigating to blocks list page "admin/structure/block"

Please find the view code which you can simply import using "admin/structure/views/import"
<code>$view = new view();
$view->name = 'latest_node';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Latest Node';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Latest Node';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
</code>


Rank of Sets and Hierarchy of Sets

Question: I am trying to learn set theory from a book, Elements of Set Theory by Herbert Enderton.  His book has some practice exercises and I was hoping you could help me determine if I understand them and, if not, where I went wrong.

Define the rank of a set c to be the least "a" such that c ⊆ Va (where Va is the general notation he uses for each iteration in a hierarchy of sets).  Compute the rank of {{∅}}.  Compute the rank of {∅,{∅},{∅,{∅}}}
Answer:  V0 = ∅.  V1 = V0 ⋃ P(V0) = {∅,{∅}}.  V2 = V1 ⋃ P(V1) = {∅,{∅},{{∅}},{∅,{∅}}}.  Therefore, {{∅}} is rank 1 and {∅,{∅},{∅,{∅}}} is rank 2.

We (the author) have stated that Va+1 = A ⋃ P(Va) (where A = ∅).  Prove this for at least a < 3.
Answer:  I'm not sure how to prove this except using the kind of expansion I tried to do above??
Please let me know if I have misunderstood, the text is fairly concise and well-written but not simple to grasp when trying to learn it on my own.  Thank you!
Answer: You should prove by induction that for all natural numbers $\alpha$, $V_\alpha \subseteq P(V_\alpha)$.
For $\alpha = 0$, this is trivial since $V_\alpha = \emptyset$.
For $\alpha = \beta + 1$, we see that $V_\alpha = V_\beta \cup P(V_\beta) = P(V_\beta)$. Since $V_\beta \subseteq V_\alpha$, we have $V_\alpha = P(V_\beta) \subseteq P(V_\alpha)$.
Note that you can extend this to all ordinals $\alpha$ by doing ordinal induction. We need only add the following clause:
For $\alpha$ a limit ordinal, we see that $V_\alpha = \bigcup\limits_{\beta < \alpha} V_\beta \subseteq \bigcup\limits_{\beta < \alpha} P(V_\beta) \subseteq P(\bigcup\limits_{\beta < \alpha} V_\beta) = P(V_\alpha)$.

Rank of Sets and Hierarchy of Sets


Finding the missing number in a sequence of factorials

Question: On one of our tests, the extra credit was to find which number you would take out from the set $\{1!,2!,3!,...(N-1)!,N!\}$ such that the product of the set is a perfect square. My answer was as follows:
Assume $N$ is even. First note that  $(n!)=(n-1)!\cdot n$.
Apply this to the odd numbers to get the product:
$$(2!)(2!)\cdot 3 \cdot(4!)(4!)\cdot 5\cdots ((N-2)!)((N-2)!)\cdot (N-1)\cdot N!$$
Let $ 2!4!6!...(N-2)!=E$. Then our equation is equal to:
$$E^23\cdot 5\cdot 7\cdots (N-1)\cdot (N!)$$
Expand $N!$:
$$E^2\cdot 3\cdot 5\cdot 7\cdots (N-1)\cdot 2\cdot 3\cdot 4\cdots N$$
Group the odd terms together:
$$E^2\cdot 3\cdot 3\cdot 5\cdot  5\cdot 7 \cdot 7\cdots (N-1)\cdot 2\cdot 4\cdot 6\cdots N$$
Let $O=1\cdot3\cdot5...\cdot (N-1)$:
$$E^2O^2 2\cdot 4\cdot 6\cdots N = E^2O^2\cdot (2\cdot 2)\cdot (2\cdot 3)\cdot (2\cdot 4)\cdots (2\cdot (N/2))$$
Group together the $2$'s:
$$E^2O^22^{(N/2)}1\cdot2\cdot3...(N/2)=E^2O^22^{(N/2)}\cdot(N/2)!$$
So, if $N/2$ is even, it can be expressed as $2m$ for some $m$. So we have:
$$E^2O^22^{2m}(N/2)!=(EO2^m)^2(N/2)!$$
Therefore, if $N$ is even, the number missing is $(N/2)!$ if $N/2$ is even. For example, for $N=4$, $2!$ is missing, $N=6$ is impossible ($3$ is odd), and for $N=100$, $50!$ is missing.
I got partial credit - but my teacher said I missed a case, and that I should leave a sticky note on her desk with a number on it to show that I've fixed the proof.
I think the flaw might be in assuming $N$ is even, but I'm not sure how to deal with the case of $N$ odd.
And, I've found that my solution gives $4!$ for $N=8$, but $3!$ is also a solution.
Past that, how can one number show that I've fixed the proof?
Comment: Yes, don't you have to consider the case $N$ is odd?
Comment: @JimmyR. Yes! But I don't know how to go about that, nor how I would express the solution in one number.
Comment: Look at $N = 9$.
Comment: It is true that $\dfrac{1!2!3!4!5!6!7!8!}{4!}$ is a square.  But so too is $\dfrac{1!2!3!4!5!6!7!8!}{3!}$.  And something similar when $N=8k^2$ for other $k$
Answer: According to the paper "Square products of punctured sequences
of factorials" by Rick Mabry and Laura McCormick. The  given problem for $N\geq 2$ has at least a solution if ad only if $N$ is even and has one of the following forms:
1) $4k$ or $4k^2-2$ for any positive integer $k$ (take away $(2k)!$ and $(2k^2)!$ respectively);
2) $2k^2$ or $2k^2-4$ for any positive odd integer $k\geq 3$ such that $2(k^2-1)$ is a perfect square (take away $(k^2-2)!$ and $(k^2)!$ respectively).


T-SQL CASE behavior in a WHERE clause

Question: Thanks in advance for your interest!
I want to send a work order status parameter (@WOStatusCriteria) to a stored procedure (in SQL Server 2016) for use in a SELECT.  I want to query on status of either "R" (Released) or "F" (Firm) OR BOTH, depending on the need at the moment.
As the possible status codes are C, F, R, U and X, I wrote the following CASE in a WHERE clause, hoping that if R or F were not explicitly sent in the parameter, both R and F statuses would be returned by virtue of the NOT C, NOT U, NOT X phrase.  It doesn't work, and I'm looking for a solution that does.  Any thoughts on this would be appreciated.
(wo.STATUS = CASE
    WHEN @WOStatusCriteria = 'R' THEN 'R'
    WHEN @WOStatusCriteria = 'F' THEN 'F'
END)
AND (NOT wo.STATUS = N'C' AND NOT wo.STATUS = N'U' AND NOT wo.STATUS = N'X')

Comment: Read erland's discussion (and everything else) [here](http://www.sommarskog.se/dyn-search.html).
Answer: Your current code should work if you add:
ELSE wo.STATUS

to your CASE expression.
since wo.STATUS will always equal wo.STATUS, the CASE will be ignored and the other conditions will be evaluated.
Comment: Thanks very much!  That worked.  I believed that the answer was in an ELSE, but wasn't sure how to go about it.

T-SQL CASE behavior in a WHERE clause


Map preserving intervals but discontinuous

Question: Let $f:\mathbb{R}\to\mathbb{R}$ be a map sending closed intervals to closed intervals. Prove that $f$ is continuous or find a counter example.
WLOG we just have to prove continuity at $0$ and we can also assume that $f(0)=0$ and $f(1)=1$ (by considering $x\mapsto (f(x)-f(0))/(f(1)-f(0))$ ).
I build up this question while thinking of the question Mappings preserving convex polyhedra.
Comment: You tagged it with "compactness" but didn't make any mention in the question, so I feel like some telepathy (or some subliminal messaging) might be going on here. Can you clarify any hypotheses you are thinking of?
Comment: @rschwieb, I had in mind that closed and bounded interval are the compact sets. Sorry for not mentioning it in the post.
Comment: @rschwieb It is useful to note that closed intervals are precisely the compact connected subsets of $\mathbb R$.
Comment: @AlexBecker It's useful to know that's what the poster means by closed intervals, too, if that's the case.
Comment: @GillesBonnet Thanks! That makes everything clear.
Answer: This is false. Consider
$$f(x)=\begin{cases}
\sin \frac{1}{x} & x\ne 0\\
0 &x = 0
\end{cases}$$
which is discontinuous at $0$. However, for any closed interval $I$ not containing $0$, we have that $f(I)$ is a closed interval since $f$ is continuous on $I$, and for any closed interval $I$ containing $0$ we have $f(I)=[-1,1]$.
Comment: @AlexBecker, $\frac{\sin x}{x} \rightarrow 1^-$ when $x\rightarrow 0$ so the image of  $(-\varepsilon,\varepsilon)$ (for $\varepsilon$ small enough)its of the form $\{0\}\cup (1-\delta,1)$ tha it isnt a closed interval
Comment: ohh! classic! Wonder how I did not think about it myself!
Comment: @GillesBonnet What I noticed was that your property is very much like the Intermediate Value Property, and this function is famously discontinuous but satisfies IVP.
Comment: ok, thanks. Meta question: should I edit the title to: "Map preserving intervals but discontinuous." in order to make it more clear.
Comment: @themaker You're right, I made a typo. Should be right now.
Comment: @GillesBonnet Either is fine (although your current title should read "then", not "than")
Comment: @GillesBonnet Please edit the title.  The title very misleading right now.
Answer: A closed map* is not necessarily continuous. As mentioned in e.g., Wikipedia's page, the argument function assigning to a point p in $S^1$ its "total argument" (in the range $[0, 2\pi)$), i.e., the arc-length in radians at any x in  $S^1$ , measured from a fixed point p, is both open, closed, but not continuous ; specifically near the fixed point $p$ , where the value goes from being close to $2\pi$ to being $0$.
Comment: This property is stronger than being a closed map however.


Validate two properties are equal

Question: Is it possible to validate that two object properties of type string are equal using Joi?
I found Joi.ref() but I wonder if there's another way of doing it. Especially as Joi.ref() doesn't seem to support any.error()
Comment: I remember you, you created the npm package `docker-compose`, thanks for that!
Could you describe in detail what do you try to do with `any.error()`? Should a password match the other one and which error messages do you want?
Comment: Password match is excactly the intented use case here. How it is done using `Joi` doesn't matter. I just want to use `Joi` when possible.
Comment: I found a solution that works with `Joi.ref()`
Answer: Yes, it is possible to check if two properties on a object are the same. And using Joi.ref() is the preferred way to do it.
If you want to use custom error messages the Joi.any.messages() option works the best. The Joi.any.messages() lets you overwrite the different error messages that a property is producing.
You could also use the Joi.any.error() option but that is not that elegant and you would need to switch between the different error codes (like string.base, any.required, any.only...)
Complete Solution using Joi.any.messages()
const Joi = require('@hapi/joi');

const schema = Joi.object().keys({
  first: Joi.string().required(),
  second: Joi.string().required().equal(Joi.ref('first'))
          .messages({
            'string.base': 'second is not a string', // typeof second !== 'string || second === null
            'any.required': 'second is required', // undefined
            'any.only': 'second must match first' // second !== first
          })
});

const value = {
  first: 'hello',
  second: 'hello',
};

const result = schema.validate(value);
console.log(JSON.stringify(result.error, null, 2));

Validate two properties are equal


Como verificar se um processo esta rodando no servidor?

Question: Pensando na nescidade de se verificar se uma certa aplicação está sendo executada no servidor, me veio a mente se tem como fazer essa verificação utilizando Delphi e se positivo como seria?
No caso, pela aplicação do lado Cliente verificar se uma outra aplicação está aberta no servidor.
No momento eu só consigo fazer essa verificação na maquina local com o código abaixo:
var
  Path: string;
  Hwnd: THandle;
begin
    // FindWindow vai procurar pela classe TApplication
    Hwnd := FindWindow('TApplication', 'AutoPub');
    // se o Handle e' 0 significa que nao encontrou
    if (Hwnd = 0) and (DataModuleGeral.tbParametrosCODESCRITORIO.AsInteger <> 0) then
    begin
      Path := ExtractFilePath(Application.ExeName);
      ShellExecute(Handle,'open',PChar('AutoPub.exe'),'',PChar(Path),SW_SHOW);
    end;
end;

Answer: Praticamente tudo tem um jeito huahuahua
Existe um protocolo chamado SNMP(Simple Network Management Protocol) utilizamos esse protocolo para monitorar máquinas remotas, com ele é possível pegar informações como:

Tráfego de rede
Espaço no hd
Processamento
Memória em uso
Processos em uso etc

Ou seja esse protocolo é muito utilizado para gerencia de servidores e computadores, imagina um parque com 100 servidores rodando, vc acha que entramos nos 100 servidores e ficamos olhando se o HD tá lotando, se o consumo da placa de rede tá no talo, etc, etc, ??? claro que não né, criamos sistemas automáticos de alertas, um servidor client conecta via SNMP em todos os servers e fica coletando os dados a cada X minutos, se algo estiver errado, esse servidor cliente gera alertas, manda email, liga, bate tambor, etc rsrs
Então o que vc pode fazer é habilitar o snmp server no windows/linux na qual vc quer coletar o nome do programa/processo, veja aqui como isso pode ser feito no windows, feito isso seu programa terá que se conectar ao pc que vc deseja via algum client SNMP, no delphi eu sei que existe o Indy-SNMP.
Ex:
program snmptest;
{$APPTYPE Console}

uses
  SysUtils, IdBaseComponent, IdComponent, IdUDPBase, IdUDPClient, IdSNMP;

var
  Snmp: TIdSNMP;
  Idx: Integer;

begin
  Snmp := TIdSNMP.Create(nil);
  try
    Snmp.Query.Host := 'Hostname or IP'; //IP do computador que habilitou o snmp server
    Snmp.Query.Community := 'public'; // comunidade configurada no snmp server
    Snmp.Query.PDUType := PDUGetRequest;
    Snmp.Query.MIBAdd('184.108.40.206.184.108.40.206.0',''); //OID que retorna o que deseja

    if Snmp.SendQuery then
    begin
      WriteLn('Replies: ' + IntToStr(Snmp.Reply.ValueCount));
      for Idx := 0 to Snmp.Reply.ValueCount - 1 do
        WriteLn(Snmp.Reply.Value[0]);
    end;
  finally
    Snmp.Free;
  end;
end.

Esse parâmetro Snmp.Query.MIBAdd é o OID que vc seta para colher a informação que vc quer, cada número retorna algo diferente, ou seja vai ter um OID que retorna informações de memória, OID que retorna espaço de disco, OID que retorna os programas rodando, etc, etc, etc esse OID ai do código vc terá q testar e verificar o q vai ter como retorno, dá uma pesquisada e teste o OID hrSWRunName, acho que ele retorna todos os processos rodando no windows...
Além disso se não quiser usar o Indy-SNMP instale o client executável chamado snmpwalk no computador que vai fazer a consulta no server SNMP, eu acabei de testar o OID hrSWRunName, em um PC qualquer da rede instalei o snmpwalk e usei o comando para ele mostrar o que tem rodando no servidor windows (claro esse servidor tem o serviço snmp server habilitado e configurado)...
segue comando e resultado:
snmpwalk -v 2c -c public 192.168.32.23 hrSWRunName

tive como retorno:
HOST-RESOURCES-MIB::hrSWRunName.1 = STRING: "System Idle Process"
HOST-RESOURCES-MIB::hrSWRunName.4 = STRING: "System"
HOST-RESOURCES-MIB::hrSWRunName.288 = STRING: "smss.exe"
HOST-RESOURCES-MIB::hrSWRunName.336 = STRING: "csrss.exe"
HOST-RESOURCES-MIB::hrSWRunName.360 = STRING: "winlogon.exe"
HOST-RESOURCES-MIB::hrSWRunName.408 = STRING: "services.exe"
HOST-RESOURCES-MIB::hrSWRunName.420 = STRING: "lsass.exe"
HOST-RESOURCES-MIB::hrSWRunName.576 = STRING: "svchost.exe"
HOST-RESOURCES-MIB::hrSWRunName.660 = STRING: "svchost.exe"
HOST-RESOURCES-MIB::hrSWRunName.732 = STRING: "svchost.exe"
HOST-RESOURCES-MIB::hrSWRunName.768 = STRING: "svchost.exe"
HOST-RESOURCES-MIB::hrSWRunName.784 = STRING: "svchost.exe"
HOST-RESOURCES-MIB::hrSWRunName.916 = STRING: "spoolsv.exe"
HOST-RESOURCES-MIB::hrSWRunName.940 = STRING: "msdtc.exe"
HOST-RESOURCES-MIB::hrSWRunName.1152 = STRING: "svchost.exe"
HOST-RESOURCES-MIB::hrSWRunName.1176 = STRING: "ibguard.exe"
HOST-RESOURCES-MIB::hrSWRunName.1196 = STRING: "sqlservr.exe"
HOST-RESOURCES-MIB::hrSWRunName.1252 = STRING: "svchost.exe"
HOST-RESOURCES-MIB::hrSWRunName.1304 = STRING: "snmp.exe"
HOST-RESOURCES-MIB::hrSWRunName.1608 = STRING: "WUSyncSvc.exe"
HOST-RESOURCES-MIB::hrSWRunName.1636 = STRING: "mssearch.exe"
HOST-RESOURCES-MIB::hrSWRunName.1840 = STRING: "sqlagent.exe"
HOST-RESOURCES-MIB::hrSWRunName.1876 = STRING: "svchost.exe"
HOST-RESOURCES-MIB::hrSWRunName.1896 = STRING: "ibserver.exe"
HOST-RESOURCES-MIB::hrSWRunName.2024 = STRING: "alg.exe"
HOST-RESOURCES-MIB::hrSWRunName.2172 = STRING: "wmiprvse.exe"
HOST-RESOURCES-MIB::hrSWRunName.2232 = STRING: "cmd.exe"
HOST-RESOURCES-MIB::hrSWRunName.2432 = STRING: "notepad.exe"
HOST-RESOURCES-MIB::hrSWRunName.2712 = STRING: "explorer.exe"
HOST-RESOURCES-MIB::hrSWRunName.2780 = STRING: "ctfmon.exe"
HOST-RESOURCES-MIB::hrSWRunName.2792 = STRING: "sqlmangr.exe"
HOST-RESOURCES-MIB::hrSWRunName.2864 = STRING: "svchost.exe"
HOST-RESOURCES-MIB::hrSWRunName.3980 = STRING: "isqlw.exe"

isso significa que outra opção então é vc fazer o seu delphi executar um snmpwalk e pegar o retorno do comando, tratar o retorno e comparar se o .exe que deseja está no retorno (na vdd o Indy-SNMP é um client SNMP, praticamente é um snmpwalk né, bem melhor usar o indy-snmp do que ter que ficar instalando client externo)...
Como vc pode perceber, isso pode ser perigoso, um hacker na sua rede pode descobrir qual community vc configurou nos servidores e tentar varrer sua rede procurando por portas SNMP abertas, com isso ele pode conseguir informações de serviços e programas rodando na rede, e depois tentar explorar, então quando for configurar o serviço SNMP server não esqueça de permitir que somente IP's de confiança consigam fazer consultas de somente leitura ....
Comment: Obrigado!
vou fazer os testes. quando terminar eu posto um retorno.
Comment: legal boa sorte ai ...
Comment: @ederwander cara gostaria de falar com vc sobre o googletts que vc tem no github. como posso entrar em contato ?


Pass an array item to a function in PowerShell

Question: I've already read many articles about PowerShell functions and passing parameters to them but I haven't found a solution on how to pass a specific array item to a function and not the full array.
This is how my code looks:
$log = "C:\Temp\test.txt"
$test = "asdf"
$arrtest = @("one", "two", "three")

Function Write-Log($message)
{
    Write-Host $message
    $message | Out-File $log -Append
}

Now I want to pass single items of the array to the Write-Log function like this:
Write-Log "first arr item: $arrtest[0]"
Write-Log "second arr item: $arrtest[1]"
Write-Log "third arr item: $arrtest[2]"

But in the commandline I'll always get the full array plus [number] as a string:
first arr item: one two three[0]
second arr item: one two three[1]
third arr item: one two three[2]

I think the problem is my syntax, can someone please point me in the right direction?
Thanks a lot!!
Answer: This will do the trick:
Write-Log "first arr item: $($arrtest[0])"
In your attempt, your passing entire array, because PowerShell interprets $arrtest as variable, and [0] as string.
Comment: Thanks a lot for the fast solution!


Can defenders hold each other in the air at a free kick?

Question: I have noticed players standing in a line to block free kicks in the World Cup, with some teams choosing to have a player lay along the ground to block lower shots.
Are there any rules preventing teams from stacking players? For example: 3 players standing as the base holding 2 players elevated?
I realize it may not be the greatest strategy for defending, but is it allowed?
Comment: I wouldn't want to be a player standing on the shoulders of others, and to take a direct hit of the ball, off the boot of Marcus Rashford's left foot. One might end up in the back of the net.
Comment: It's funny, I was watching a Rugby match, back in Nigel Owen's days, when a player flopped and the ref (may have been Owen, may have been another) said something to the effect of "what do you think this is, football? Show some respect" ... I would kind of expect the same thing in reverse if a soccer team used a prop/jumper combo that way..
Answer: I don't believe there is anything in the Laws of the Game (most likely Law 12.3 "Disciplinary Action") which would specifically forbid this; Law 12.3 does include the catch-all allowing a player to be cautioned if they "show a lack of respect for the game" which a referee could use if they felt it necessary.
That said, the rules for sports in general don't need to include things forbidding behaviour which is likely to result to degrade a team/player's performance because there's no need for it unless people are being deliberately silly - in which case the "lack of respect for the game" clause does come into play.
Comment: I'm pretty sure such action would not be legal. I just need to find something in the LotG to quote for an own answer.


Dealing with very large time-series datasets

Question: I have access to a very large dataset. The data is from MEG recordings of people listening to musical excerpts, from one of four genres. The data is as follows:

6 Subjects
3 Experimental repetitions (epochs)
120 Trials per epoch
8 seconds of data per trial at 500Hz (=4000 samples) from 275 MEG channels

So each "example" here is a matrix of size [4000x275], and there are 2160 of such examples, and that's before any feature extraction. The goal is to predict genre based on the brain signal (4-class classification).
Clearly there are some challenging issues here, namely:

The dataset does not fit in memory
There will be strong temporal correlations in the data, and the inter-subject variation will be huge. As a result it's not obvious how to split the data
The signal-to-noise ratio is very low
It's not obvious what the correct features for a classifier would be

Taking these in turn:

There are various things one can do. Firstly we can safely downsample from 500Hz to ~200Hz, as even taking the Nyquist limit into account, brain activity doesn't really occur at over 100Hz. We could also subsample from the the set of channels (e.g. centre over auditory areas) but we'd rather not do this a-priori, as there may be activity in other areas (frontal etc) that could be of interest. We can probably also drop a portion of the time window. Perhaps only the first 2s is important for the task? It's not really known. Of course everyone will shout "Dimensionality reduction!", but that's not trivial either. Firstly, we'd have to be very careful about our train/test splits (see 2.) and it's also not obvious whether to do this before or after feature generation. Secondly, other than expensive cross-validation, or painstaking visual inspection, there's no obvious way to select either the appropriate method or the appropriate number of dimensions. We could of course just use e.g. PCA, ICA, or random projections and hope for the best ....
This is tricky. If we have successive samples in the training set we are likely to overfit the training set, whereas if we have successive samples split into to the train and test sets we're likely to underfit the training set, but could still overfit the testing set. There seem to be various options here:

Single Subject Classification. Take each individual subject on their own, and split according to epochs. This should be the easiest task, as we're not trying to predict across brains. Within this one could use the two remain epochs for cross-validation. For completeness one should rotate all combinations. We would simply report the average accuracy over all subjects. Of course we would not expect these models to generalise well at all.
Within subjects classification. Take all of the subjects together, and split according to epochs. This may in fact be the easiest task, as we will have seen all of the subjects in training. However we probably wouldn't expect the models to generalise well to new subjects. Within this one could use the two remain epochs for cross-validation. For completeness one should rotate all combinations.
Between subjects classification. Also known as "leave-one-out", where a single subject is taken as test data, and the rest are used for training. We would then rotate through all subjects. Cross-validation would then be performed over subjects. We would expect this to be a much more difficult task, as we are trying to predict on a "new brain" each time. Here we would expect the models to generalise well to the larger population, although there is an issue of test-retest reliability (i.e. how much overfitting is caused by temporal correlations).

This is a classical "needle in a haystack" problem - the actual signal relating to the recognition of musical genre, or any genre-specific processing, is likely to be minuscule compared to the "soup" of activity in the brain. There are also notable artefacts which can only be partially removed (mainly related to movement). Any features that we derive from the data, and any ways in which the data is treated, should avoid destroying part of the signal of interest.
Here one could imagine doing various things. The first would be to simply use the raw data (concatenated into a vector) as the feature vector. I'm not sure how fruitful that is though - I think these vectors would probably be essentially uniformly random. This is then really a signal processing question, but there are some general guidelines one can follow. One is to do standard Fourier Analysis over a sliding window, from where the components can be split into distinct frequency bands (alpha/beta/gamma etc), and statistics of these (mean, std. deviation) can be used as features. Or one could use Wavelets, Hilbert Transforms, or even attempt to look for chaotic attractors. Of course then we have the choice of kernels (linear, polynomial, RBF etc) which multiplies up the number of permutations. Perhaps the best thing to do here is generate as many different feature sets as possible, and then use MKL or boosting methods to combine them together.

How would you approach this kind of dataset (if not this one specifically)? Is there anything I've missed along the way? What is the most likely strategy to succeed, without spending endless amounts of researcher time and computational resources?
Answer: @tdc. All and many more issues which you have mentioned here regarding the analysis of neuroscience data including: Dimensionality reduction, Within/between subjects classification, signal-to-noise ratio, etc. etc. are being handle by the EEGLAB toolbox, which were specifically designed for handling those kind of neuroscience data :

EEGLAB is an interactive Matlab toolbox for processing continuous and event-related EEG, MEG and other electrophysiological data incorporating independent component analysis (ICA), time/frequency analysis, artifact rejection, event-related statistics, and several useful modes of visualization of the averaged and single-trial data.

Thus, with regard to your question "What is the most likely strategy to succeed, without spending endless amounts of researcher time" I would like to encourage you to watch the EEGLAB on line workshop , and to continue from there...
Update: for more ML stuff take a look on the (new) BCILAB model
Comment: I have actually used EEGLAB in the past, although mainly it's underlying functions rather than the full GUI (which tended to be a bit slow and unstable). However it's mostly geared towards mass univariate analysis rather than multivariate analysis, although I admit I haven't looked at it in a while. Do you have experience of it?
Comment: ok interesting. In principle I don't see any difference between EEG & MEG, as they're essentially both measuring electrical brain activity, apart from the types of artefacts and the number of sensors. Have you combined EEGLAB with Machine Learning?
Comment: This is a great answer for its scope, but it would be nice to see a summary of how each of these issues are handled independent of a toolbox relying on a proprietary system.
Comment: I think They have made big progress in the last two years...and I'm using both the GUI and the matlab-function. This workshop from 2010 is very useful and many bugs were fixed, many models were added like STUDY and other. I am very pleased with it saves me time and money however please note that I'm working mainly with EEG data and not MEG.
Comment: sure. all the time. it's all in matlab...so once you load your data into EEGLAB. you can use PCA/ICA (this what i'm doint) and then train your favorite classifier/clustering SVM, fisher or k-mean..just name it.
Comment: for more ML stuff take a look on the BCILAB there..


The value of adding the ROC graph if the AUC is given

Question: I always see in papers that when they want to show how they classifiers performed, they provide ROC graph and the AUC score. Now as far as I know only the AUC tells how well the classifier performed, so what is the advantage of adding the ROC graph? What can one tell from it?
Comment: This isn't really any different from lots of cases where the data are described numerically in the text, but people like to present the information visually as well.
Answer: I usually give the ROC plot but not the AUC: For my applications it is usually clear that either a specific or a sensitive regocognition is needed. The ROC is different for classifiers that are specific but not sensitive vs. sensitive but not specific while the AUC hides this information.
Besides, one can put a whole lot of further information into the plot, e.g. color-coding the thresholds (check whether the classifier is well calibrated if the primary output is posterior probability), model stability (after resampling validation), or confidence regions for a chosen classifier (if one chooses a threshold). Finally, you can even put "extented" measures of sensitivity and specificity which do not require the thresholding @FrankHarrell fights against, e.g. it is possible to extend the concept of sensitivity and specificity and the concept behind Brier's score to yield such measures.
Comment: Is there something about probabilistic decision making that doesn't work in your situation?
Comment: @FrankHarrell: Well, yes: communication. I spend quite a lot of my working time doing translations: physicist <-> chemist (<-> chemometrician) <-> statistician <-> medical doctor, and I find the art of doing this well has a lot to do with allowing simplifications and finding compromises (and trying to avoid to gross misconceptions). I tackle the "don't throw away information" problem by  sneaking in continuous measures (as chemist I prefer MSE/RMSE) which are well (or at least better) behaved, but their names and purpose are familiar.
Comment: I feel that probabilities can work well if communication is careful or the problem involves sports or card playing.
Answer: I have not seen a single example where the graph changes our actions or the way we think.  I think the ink:information ratio in an ROC graph is enormous.  But the worst thing about it is that it tempts us to try to select a cutoff for the predicted risk, which is arbitrary, and inconsistent with optimum decision making.
Beware of the word classifier which implies discarding continuous information.
Comment: Only if sensitivity and specificity are helpful.  I find them not to be.  If we were regressing age on blood pressure we'd never create an ROC curve.  Why we do it when $Y$ is binary is beyond me.
Comment: Temptation for a cutoff is a point, but OTOH giving the ROC IMHO is already much better than reporting sensitivity and specificity at some arbitrary default cutpoint without any further information.
Comment: @FrankHarrell regression doesn't help when you need to make a *decision*, rather than a prediction. At some point you need to define a threshold. You can't treat a patient for 70%. In those settings, ROC curves provide a valuable summary of the model at different operating settings (in part due to the fact that ROC curves are understood by many). That said, I agree on the high ink:information ratio.
Comment: I have to disagree [and medical diagnosis is one of my main areas of research].  There are only two situations I can think of where your reasoning applies: (1) when the analyst is the possessor of the utility function (highly unusual) or (2) when decisions must be made instantly without the time to assess utilities.  Not only are probabilities the optimum inputs to true decision makers, they allow one to make no decision, when more data are needed.
Comment: @FrankHarrell: I totally agree that lots of valuable information are lost with the dichotomization. As chemist, my primary philosophical concept of the world is quantitative (substances come at concentrations). So qualitative analysis ("native chemical" version of classification) is the result of comparing a primarily quantitative result to a threshold. However, there are situations which are more basically grouped than continuous. Few people are 20% pregnant... And even in some fundametally continuous situations it just doesn't make sense to cry over the threshold: (...)
Comment: (...) If there is a legal threshold for Pb in drinking water, that's what I have to use. Note that it won't keep me from reporting the quantitative estimate in addition. I agree that the blood pressure is yet different in that there is no external need to dichotomize. Note also that in my legislation reporting continuous scores and normal ranges would be the way to go for clinical diagnostics: only medical doctors are allowed to convert those into the actual diagnosis (= dichotomize).
Comment: The only time I have seen thresholds be necessary is when forced by law.  Even then it's not optimal.  There would be less cheating on federal income tax if taxes were continuously graduated instead of using tax brackets.  Normal ranges are not that useful in decision making because they come only from normals.
Answer: The ROC curve is the specificity/sensitivity plot; the AUC is the Area Under Curve.
To be brief, the ROC curve can be interesting because it allows comparison of the sensitivity/specificity behaviour of the model. More simply:
$ROC = (x,y) \in R^2 \Rightarrow AUC = z$ but $AUC = z \nRightarrow ROC = (x,y) \in R^2$
Comment: I still don't get it. What could one use the ROC graph for if he only needs the AUC to really evaluate the performance?
Answer: There is great value in showing the entire ROC esp. when comparing two different classifiers, as it helps us to see whether different curves cross each other. One is not superior to the other, overall, if they cross - see the Figure 3 (screenshot shown below) from
Seong Ho Park, J. M. G. C.-H. J. (2004). Receiver Operating Characteristic (ROC) Curve: Practical Review for Radiologists. Korean Journal of Radiology, 5(1), 11–18.

In our own study, we noticed this behaviour for biomarkers that have similar performance, and partial AUCs can be studied to demonstrate their utility for particular applications e.g. in high specificity regions for early detection of Alzheimer's disease.
Citation: Raamana, P. R., Weiner, M. W., Wang, L., & Beg, M. F. (2015). Thickness network features for prognostic applications in dementia. Neurobiology of Aging, 36, S91–S102.

Hope that helps make the case for presenting the ROC always.


Does one lose information or precision when calculating effect sizes from statistical values rather than from the raw data?

Question: Let's say that I want to compute the effect size of a certain intervention, for which I have both the raw data and some statistical value that can be transformed to an effect size. For example, if one has the t score and the df value of a t-test, one can transform it into Cohen's d by using the equation
$$d=\frac{t*2}{\sqrt{df}}$$
This can also be done for other statistical values, like for example f statistics and Chi square.
Do I lose any kind of information or precision if I chose to make the conversation from the statistical value rather than from the raw data? That is, will these transformations result in exactly the same effect size as if I would make the computations with the raw data instead, or are some of them merely estimates?
Answer: Let's take the example of a two-group comparison conducted with the independent samples t-test. The test statistic is given by $$t = \frac{\bar{x}_1 - \bar{x}_2}{s_p \sqrt{\frac{1}{n_1} + \frac{1}{n_2}}},$$ where $\bar{x}_1$ and $\bar{x}_2$ are the means of the two groups, $s_p$ is the pooled standard deviation, and $n_1$ and $n_2$ are the group sizes.
The standardized mean difference (Cohen's d) is given by $$d = \frac{\bar{x}_1 - \bar{x}_2}{s_p}.$$ Therefore, one can compute $d$ from $t$ with $$d = t \sqrt{\frac{1}{n_1} + \frac{1}{n_2}}.$$ So, one will get the exact same value whether one computes $d$ directly from the means and SDs or by converting $t$ to $d$. Therefore, no information or precision is lost when computing $d$ in this manner.
More generally, this will work, as long as you use the correct equation to convert the test statistic to the corresponding effect size measure.
UPDATE: I'll add two more examples to illustrate this point:

Suppose you conduct a one-way ANOVA on a total of $n$ individuals (all groups combined) with $g$ groups. The usual $F$ statistic is then equal to $F = MS_B / MS_E$, where $MS_B$ and $MS_E$ are the between-group (or treatment) mean square and the error mean square, respectively, which in turn are equal to $MS_B = SS_B / (g-1)$ and $MS_E = SS_E / (n-g)$, where $SS_B$ and $SS_E$ are the between-group sum of squares and the error sum of squares.
The usual effect size measure in this context is "eta-squared" ($\eta^2$), which can be computed with $\eta^2 = SS_B / (SS_B + SS_E)$ (i.e., the between-group sum of squares divided by the total sum of squares). But one can just as easily compute this with $$\eta^2 = \frac{F \times (g-1)}{F \times (g-1) + (n-g)}.$$ The results will be exactly the same.
Suppose you have a $2 \times 2$ table to examine the relationship between two dichotomous variables X and Y of the form:
<code>      |   X    not_X |
------+--------------+
Y     |   a     b    |
not_Y |   c     d    |
------+--------------+
</code>
The usual test of independence yields a chi-square value ($\chi^2$) with one degree of freedom. One measure of the strength of the association between the two variables is the phi coefficient. It can be computed with $$\phi = \frac{a*d - b*c}{\sqrt{(a+b)(c+d)(a+c)(b+d)}}.$$ But one can also compute this with $\phi = \sqrt{\chi^2 / n}$, where $n = a+b+c+d$ (assuming that $\chi^2$ was not computed with a continuity correction -- see this question). One caveat: One does not know the correct sign of $\phi$ when it is computed that way (i.e., whether the coefficient was positive or negative). So, to be precise, we get $\sqrt{\chi^2 / n} = |\phi|$.
Comment: "More generally, this will work, as long as you use the correct equation to convert the test statistic to the corresponding effect size measure." - And I guess these equations are derivable for the all the usual suspects when it comes to hypothesis testing, like t-tests (you showed that it was), Z-tests and different types of ANOVA?
Comment: Yes, in principle. Of course, the devil is always in the details and what kind of effect size measure one wants to compute. So, I would not want to make any sweeping generalizations. But I'll add two more examples to my answer.


How many five-digits numbers are divisible by $125$ and their digits sum are divisible by $4$

Question:
How many five-digit integers exist with the following conditions,
$1.$ be divisible by $125$
$2.$ Sum of their digits be divisible by $4$.
$1) 176 \qquad\qquad 2)178 \qquad\qquad 3)180 \qquad\qquad 4)198\qquad\qquad 5)200$

To solve this problem I noted that the last three digits of these numbers should be either one of the following, $000, 125, 250, 375, 500, 625, 750, 875$. Now if I divide the sum of each of these three digits by $4$, the remainder will be,
$0, 0, 3,3,1,1,0,0$ respectively. Now for four cases, sum of the first two digits should be divisible by four, and for two cases it should be in the form $4k+1$ and finally for the last two cases it should be $4k'-1$.
Now after counting all these cases, which was relatively time-consuming, I got $178$ as the answer.
I'm wondering if it is possible to solve this problem with alternative approaches. Since sum of the digits of a number is related to the remainder of dividing a number by $9$ I think this idea would be helpful, but not sure how to implement it.
Comment: This is the way. Sum of the digits works for divisibility by $3$ and $9$ since $10^n-1$ is divisible by $9$ and one can write every number $d_nd_{n-1}\dots d_1d_0$ as $\sum_{i=0}^nd_i\cdot10^i$. So that won't be of any help for divisibility by $4$.
Answer: There are $720$ 5-digit numbers that are divisible by 125.
We would expect the digital sums to be approximately uniformly distributed, so close to 1/4 should have a digital sum that is divisible by 4.
The answer should be close to 180.  If you wanted to guess and move on, you could take a stab.
But, what is it exactly?
As noted, the last 3 digits must be $\in \{000,125,250,375,500,625,750,875\}$
The associated remainders with these suffixes are $\{0, 0, 3, 3, 1, 1, 0, 0\}$
What are the two-digit prefixes?
With the prefixes $10 - 89$ we have prefixes such that the digitals sums will be uniformly distributed.  i.e. there are 20 prefixes associated with each remainder.
Or, there are $160$ numbers in the range $10,000 - 89,000$ divisible by 125 with digital sums divisible by 4.
We must count the numbers for the prefixes in the range $90 - 99$ independently.
$\{90,94,98\}$ have remainder 1
$\{91,95,99\}$ have remainder 2
$\{92,96\}$ have remainder 3
$\{93, 97\}$ have remainder 0
Count the number that is required for each remainder.
$2+2+2+2+3+3+2+2 = 18$
$178$


A question about differentiation

Question: $g(x)=\sin(1/x)  ,  g(0)=0$
Define $G(x)=\int _{0}^{x}g\left( t\right) dt$
Show $G'(0)=g(0)$
I use the definition
$$G'(0) = \lim _{h\rightarrow 0}\dfrac {G\left( h\right) -G\left( 0\right) } {h}$$
$$=\lim _{h\rightarrow 0}\dfrac {\int _{0}^{h}g\left( t\right) dt} {h}$$
$$=\lim _{h\rightarrow 0}\dfrac {\int _{0}^{h}\sin(1/t) dt} {h}$$
I have no idea about next step
Can you give me some hint
Thank you!!!
Comment: This one is tricky.  Use the fact that $$\frac{d} {dx} x^{2}\cos\left(\frac{1}{x}\right)=2x\cos\left(\frac{1}{x}\right)+\sin\left(\frac{1}{x}\right)$$
Comment: See a similar but more difficult question http://math.stackexchange.com/questions/2063078/does-the-limit-lim-x-to-0-frac-1x-int-0x-left-cos-frac-1t-right-dt Also have a look at alternative approaches given in this question http://math.stackexchange.com/q/1551332/72031
Comment: your suggestion is very useful,thank you!!!
Answer: Expanding my comment, let $F(x) =x^{2}\cos(1/x),F(0)=0,f(x)=2x\cos(1/x),f(0)=0$. We can observe that $F$ is differentiable everywhere, $f$ is continuous everywhere and $g$ is continuous everywhere except at $x=0$ and $g$ is bounded. It is easily seen that $F'(x) =f(x)+g(x) $ for all $x$ and $f(x) +g(x) $ is Riemann integrable on any closed and bounded interval. Thus by second fundamental theorem of calculus we have $$F(x) - F(0)=\int_{0}^{x}\{f(t)+g(t)\}\,dt$$ or $$x^{2}\cos\left(\frac{1}{x}\right)=\int_{0}^{x}f(t)\,dt+\int_{0}^{x}g(t)\,dt$$ or $$x\cos\left(\frac{1}{x}\right)= \frac{1}{x}\int_{0}^{x}f(t)\,dt+\frac{1}{x}\int_{0}^{x}g(t)\,dt$$ Taking limits as $x\to 0$ we get $$0=f(0)+\lim_{x\to 0}\frac{1}{x}\int_{0}^{x}g(t)\,dt$$ where the limit for the first term on right evaluates to $f(0)$ because of the first fundamental theorem of calculus and the fact that $f$ is continuous at $x=0$. Since $f(0)=0$, it follows that $$G'(0)=\lim_{x\to 0}\frac{1}{x}\int_{0}^{x}g(t)\,dt=0=g(0)$$
Answer: Use L'Hopital!

Remembering that $${d\over dx}\int _{f(x)}^{g(x)}h(t)dt=g'(x)h(g(x))-f'(x)h(f(x))$$
Comment: How come the limit (and therefore $G'(0)$) is not undefined at 0?
Comment: @alphacapture This was addressed to me? Okay... Because $G'(0)$ is undefined at $0$, the OP has expliciltely defined it to be $0$ .
Comment: This does not apply here.  The question is not as trivial as it appears. Your answers as it stands is wrong. - 1

A question about differentiation


Showing existence of Linear transformation such that $T(v)\neq0$, for any non zero vector v

Question: I'm trying to prove this:

Let $v$ be a non-zero vector of a Vector space $V$ of finite dimension, given any non-zero vector space, prove that exists a Linear Transformation such that   $T(v)\neq0$

My thinking: I think that the linear transformation must be defined as $T:V\to V$, and I should somehow guarantee that I can always define an isomorphism in V (which is my Transformation) and because $v\neq0\,$ then because $T$ is injective this must happen $T(v)\neq0$ . But I don't how to guarantee that.
Comment: Take $T(av)=av$ and $T(w)=0$ whenever $w\neq v$
Comment: If we don't know the codomain of the linear transformation, this isn't true.
Comment: the OP says that $T:V\to V$
Comment: He says that he thinks it should be defined that way, but that is not specified in the question statement.
Comment: Yeah, probably they don't say how it should be defined in order for the student to make sense out the question and guarantee that such transformation always exists. As a I said and agreeing with the answer provided if I define and Isomorphism between V it should get the job done.
Answer: What about $\xi : V \to V, x \mapsto x$ ?
Comment: Nice answer N.H.!
Comment: @CésarRosendo : glad to help you.


Image reflection effect using pure CSS

Question: I have an image in  tag. My aim is to create a reflection of that image using only CSS.
It also has to be compatible with all browsers. I tried various ways to do it one of them is in this JS Fiddle
What I want:
The Fade to Zero opacity from top to bottom on the reflection. Right now it works only in webkit browsers using combination of -webkit-box-reflect and -webkit-gradient.
I want it to work on Mozilla too.
What I have right now:
As it can be seen in the JSfiddle I got it working in the webkit browsers using:
-webkit-box-reflect: below 0px
-webkit-gradient(linear, left top, left bottombottom, from(transparent), color-stop(70%, transparent) , to(rgba(250, 250, 250, 0.1)));

I tried the following for Mozilla:
#moz-reflect:after {
    content: "";
    display: block;
    background: -moz-element(#moz-reflect) no-repeat;
    width: auto;
    height: 200px;
    margin-bottom: 100px;
    -moz-transform: scaleY(-1);
}

where #moz-reflect is the container div for the .
I'd appreciate answers which can solve the problem with CSS only. There are a lot of images  (Icons) to which this effect has to be applied.
If there is no way it can be made to work in Mozilla using just CSS then I wouldn't mind going down the JavaScript road.
Update
It has to work on custom background which may be an image or black or any other color.
Comment: how are you going to do this for IE with pure CSS??
Comment: I'm not concerned with IE at the moment, that'll ofcourse be a bonus ;) my main concern is Mozilla
Answer: I've changed your code totally, I am using CSS3 gradients with transform property, this is Pure CSS with maximum compatibility.
Here, the key thing I am using is rgba() along with the transform property applied to second img which am targeting using nth-of-type pseudo.
Also, make sure that you have called position: relative; on the parent element because I am using :after pseudo for the gradient overlay from the bottom, so am using position: absolute; for that with the bottom set to 0
Demo (Had made a bit mistake here by using rotate() as it won't give reflection effect, will just rotate the image infact, please refer to my second demonstration)
Demo 2 (Using scale for mirroring images, can use rotateY as well, as pointed out in the comments..)
#moz-reflect:after {
    content:"";
    width: 100%;
    height: 200px;
    position: absolute;
    bottom: 0;
    left: 0;
    background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.67) 49%, rgba(255, 255, 255, 1) 100%);
    /*I've removed proprietary gradient codes from here, you can get it in the demo*/
}

#moz-reflect img:nth-of-type(2) {
    -webkit-transform: scaleY(-1);
       -moz-transform: scaleY(-1);
        -ms-transform: scaleY(-1);
         -o-transform: scaleY(-1);
            transform: scaleY(-1);
}

#moz-reflect {
    position: relative;
}

Demo 3 (Only difference is, that am using height: 50%; for the :after pseudo so we don't have to hard code it)
Only code to modify in the above block of code is the height property which am setting to 50%
#moz-reflect:after {
    content:"";
    width: 100%;
    height: 50%; /* Changed the unit over here */
    position: absolute;
    bottom: 0;
    left: 0;
    background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.67) 49%, rgba(255, 255, 255, 1) 100%);
}

Note: Inorder to create the gradients best suited, say black opaque gradients will be required for websites with black background, than you can make your own using Color Zilla.
Image reflection, using black as the body background. Only changes in the above snippet of code is that am applying background: #000; to body and I've tweaked the gradient accordingly.
background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.67) 49%, rgba(0, 0, 0, 1) 100%);

Demo (For websites using darker backgrounds, black in this case)
Note: Didn't added proprietary properties for gradient in the black demo
Comment: @Charles380 if you have another solution post it - editing content in answers (aside from grammar, broken links, etc) is bad mojo.
Comment: To get the desire effect I suggest use `scaleY` instead of `rotate` Check this http://jsfiddle.net/FWB7K/7/. With rotate seems not fine the effect
Comment: Thanks for the answer. Albeit what you did there will work when there is white background alright, but with custom background it wouldn't look great. I have just updated my question. I forgot to include that part earlier.
Comment: @Danko was editing the answer only, cuz I realized when I was watching the demo, I made this on an image where it wasn't y axis conscious, refreshed 2 to 3 times but didn't striked that the thing was wrong at first place :) though thanks for the comment...
Comment: @FillipPeyton yes we can, I was bit excited while posting, so fixed the codes now, thanks for the inputs.. appreciated...
Comment: @vineetrok well, that's all from me, if you add the conditions lately I cannot help it :) and you welcome.. you can wait for another solutions if this didn't sufficed..
Comment: @Mr.Alien Yep, my bad! Your answer will suffice for now. If my updated condition is satisfied it'll be a bonus. So, i'll wait for other answers if they are coming.
Answer: You can also use a single image element along with ::before and ::after, however it's not very useful (yet), since you have to hard-code a background-image:url() for the ::before pseudo-element. I'm posting this answer because someone else may want to do it this way, and hopefully one day we'll be able to use background-image: attr(src, url); syntax. (1) As of June 2014, no browsers support this.
A fiddle: http://jsfiddle.net/DeedH/5/
I'm assuming you have a black background.
Structure:

img - main image (actually displayed as a background-image),
::before containing the reflection. Must be display:inline-block in order to use the transform:scaleY to flip the image.
::after containing a gradient mask.

The html: (note that currently the src is not used).

The CSS:
.reflect {
    position:relative;
    display:block;
    height:300px;
    width:300px;
    background-image:url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSYXWxD2yC7m2m1ZylyVq_r6yWE4ewJv64cmt3CpgbGdqZq3wEx');
    background-repeat:no-repeat;
    background-size:contain;
    content:'';
}
.reflect::before {
    position:relative;
    top:20%;
    height:100%;
    width:100%;
    display: inline-block;
    -moz-transform: scaleY(-.7);
    -o-transform: scaleY(-.7);
    -webkit-transform: scaleY(-.7);
    transform:scaleY(-.7);
    opacity:0.2;
    background-image:url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSYXWxD2yC7m2m1ZylyVq_r6yWE4ewJv64cmt3CpgbGdqZq3wEx');
    background-repeat:no-repeat;
    background-size:contain;
    content:'';
}
.reflect::after {
    position:relative;
    top:-40%;
    height:70%;
    width:100%;
    background-image:-webkit-radial-gradient(top center, 50% 75%, rgba(0,0,0,0), rgba(0,0,0,1));
    background-image:-moz-radial-gradient(top center, 50% 75%, rgba(0,0,0,0), rgba(0,0,0,1));
    background-image:-o-radial-gradient(top center, 50% 75%, rgba(0,0,0,0), rgba(0,0,0,1));
    background-image:radial-gradient(top center, 50% 75%, rgba(0,0,0,0), rgba(0,0,0,1));
    background-repeat:no-repeat;
    background-size:contain;
    content:'';
}

Note that you must use content:''; on the img itself, otherwise the pseudo-elements won't display.
Also be aware that this is not really applicable to a class of images because you have to hard-code the image url. But this could be useful if you used it by id and used js to write the rules to a document level stylesheet.  Otherwise, this is only helpful for single images.
(1). Using HTML data-attribute to set CSS background-image url

Image reflection effect using pure CSS


Can't delete file from bucket supabase-bucket

Question: I am trying to delete a file from a bucket from which I have created two policies, although I can save in the bucket I cannot delete the data, it returns data: []
my code is:
    const deleteVideoFromBucket = async(videoFile) => {
        const videoFilePath = videoFile.split('/').pop();
        console.log(videoFilePath)
        try {
            const { data, error } = await supabase
            .storage
            .from('video_course_presentation')
            .remove([`${videoFilePath}`])
            console.log('return', data, error)
            if(data && data.length > 0) {
                videoDeletedFromBucketToaster();
            }

        } catch (err) {
            console.log('There was an error deleting the video file from the bucket ', err);
        }
    }

Answer: My mistake i was missing a select policy with the delete.
CREATE POLICY "Select video can be done only for authenticated users"
ON storage.objects FOR SELECT TO authenticated USING
(bucket_id = 'video_course_presentation');

CREATE POLICY "Delete video can be done only for authenticated users"
ON storage.objects FOR DELETE TO authenticated USING
(bucket_id = 'video_course_presentation');


Unbounded Solution for 2nd Order PDE.

Question: Suppose that $\Omega=(a,b)\times\mathbb{R}^+$ and that $\phi:\Omega\to\mathbb{R}$ and $\phi=\phi(x,t)$ satisfies
\begin{equation} L(\phi)=0,\;\;\;\;\;(1) \end{equation}
where $L$ is a 2nd order differential operator in the first variable $x$ only. Furthermore, suppose that $$\phi(a,t)=\phi(b,t)=f(t),\;\;\text{ for all }t\in\mathbb{R}^+.$$
If $f$ is bounded, can there be a differential operator $L$ and a function $\phi\in\ker L$ such that $|\phi|$ is unbounded? What if $f$ is unbounded?
Note 1: The function $\phi$ is in $H^2\left((a,b\right))$ for all $t$ and $C(\mathbb{R}^+)$ for all $x\in(a,b)$ but these conditions can be changed for the sake of an example/counter-example.
Note 2: Of course, a suitable choice $\phi_0(x)=\phi(x,0)$ is to be given also as part of the problem.
My try: Suppose that we take $f\equiv 0$. If $\phi(x,t)$ is a solution for
(1), I claim that $t\cdot\phi(x,t)$ is also a solution for (1).
Comment: What are the coefficients of $L$ like? Are they constant or non constant?
Comment: there is no restriction on $L$ except what is provided above.
Comment: If $f$ is unbounded then $|\phi|$ is unbounded too, due to the boundary conditions.
Answer: I can propose a following counterexample. Let $a=0$, $b=\pi$, and $f\equiv 0$. For any function $g:\Bbb R^+\to\Bbb R$, a function $\phi:\Omega\to\Bbb R$ such that $\phi(x,t)=g(t)\sin x$ for each $(x,t)\in\Omega$, satisfies the boundary condition. If the function $g$ is unbounded then the function $\phi$ is unbounded too. If $L=\tfrac{\partial^2}{\partial x^2}+1$ then $L(\phi)=0$.

Unbounded Solution for 2nd Order PDE.