How are curling percentage determined by each shot?

Question: This is the scoreboard for the gold medal final for 2017 Tim Hortons Brier.
It is possible to see the percentage (PCT) for each curler for this match.
This percentage coming from every single shot, but
How is it possible to determine this percentage in an objective way?
Comment: Please do not use codeblock for emphasis. It interferes with screenreaders and is difficult to read for some people.
Answer: The stones are given points (normally between 0 and 4) depending on how close to the task (as the judges see it) the stone is. This often does not include secondary tasks that the team my set up for a stone, if it is not perfect. So while in theory a game should have the same score independent on who runs the scoring, there are quite a few "grey areas" (eg how good is a guard, should it have 2 of 3 points).
There is also a system of bonus points, but I don't know exactly how these are calculated.
Divide the total points with 4 times the number of stones, and you have a percentage.


SDR /search mapping collision

Question: I'm using Spring Data REST with Spring Boot 1.5.4 and I have a trouble.
I defined repository:
public interface TicketRepository extends JpaRepository<Ticket, Long> {

    @RestResource(path = "find-by-ticket-list-id")
    Page<Ticket> findByTicketListIdOrderByPosition(@Param("ticketListId") Long ticketListId, Pageable pageable);
}

I need a specific GET method. So I defined the controller:
@RepositoryRestController
public class TicketController {

    @GetMapping("/tickets/{id}")
    public ResponseEntity<?> getTicket(@PathVariable Long id, PersistentEntityResourceAssembler assembler) {
        ...
    }
}

And now, when I try to get a list of search resources, I get an error

Failed to convert value of type 'java.lang.String' to required type
  'java.lang.Long'

I understand that this is due to a collision of /tickets/{id} and /tickets/search, but I do not understand how to deal with this. I tried to put @Order before the getTicket method and before TicketController definition, but it did not change anything.
How to resolve both URI's?
Answer: Use Regular Expressions in URI Template Patterns:
@GetMapping("/tickets/{id:\\d+}")
public ResponseEntity<?> getTicket(@PathVariable Long id, PersistentEntityResourceAssembler assembler) {
    ...
}

More info...

SDR /search mapping collision


Reliable way to check server availability

Question: I am using scheduler/API to scan target machines for Vulnerabilities(Using Nessus). But before the scan starts, I want to check if the servers are available or not for scan. I understand from this question that, "ping sends icmp, that can be filtered by the firewall".
So other than ICMP ping , what can I use to verify if the servers are available or not ?
Answer: The good way to test if the server is online and delivering some service... is to test the given service.
So, if they are used as a web server, do an HTTP/HTTPS query and see if you get a reply. You may even want to check the content of the reply to make sure that it comes from the server you thing about, and not some proxy.
If they are mail hosts, do an SMTP or IMAP connection (based on their services), and verify that you get a valid reply.
If they allow remote SSH connection, try to establish an SSH connection.
Etc.
Comment: Thanks for the answer. But here I have many different servers, and checking each depending on their service would be difficult and time consuming. Is there any one or two commands using which I can check the availability ?
Comment: You do not provide specific details enough so the main idea is still to test the relevant service of each. Or `ssh` if you connect to each with `ssh`, or SNMP queries if each of your server is remotely monitored and has a running SNMP daemon.
Comment: The main idea is to scan the servers using network scanner such as Nessus (I might now have no information about the servers' services as they are in thousands). But as you might know, network scanners will take a lot of time in case the servers are not up. So, I want to check if servers are up or down before network scanner start the scan.


Finding $\int^{2\pi}_0 \cos(n\theta - 2\sin\theta)d\theta$

Question: I have been asked to prove that:
$$\int^{2\pi}_0 \cos(n\theta - 2\sin\theta)d\theta = 2\pi \sum^\infty_{r=0} \frac{(-1)^r}{r!(n+r)!}$$
I have also been given a hint, to consider the function $f(z) = \exp(z - z^{-1})$.
It looks to me like I'm supposed to integrate $\exp(z - z^{-1})$ on the unit circle path, since I see a $z^{-1}$ and this equals $\bar{z}$ when $z$ is on the unit circle.
It's not as simple as just $\int_C \exp(z - z^{-1}) \;dz$ since I am supposed to get an infinite sum and I can't work out where that comes from, since it looks to me like there's only 1 possible singularity of $f$, at $z=0$ but $f$ isn't unbounded near $0$ so this can't be a pole.
I would appreciate if someone helped me get started on this, I am completely lost.
Comment: $\exp (z - z^{-1})$ has an essential singularity at $0$. Note that your integral is [the real part of, but by parity and periodicity the imaginary part vanishes] $$\int_0^{2\pi} \exp(in\theta - 2i\sin \theta)\,d\theta = \int_0^{2\pi} e^{in\theta}\cdot e^{-2i\sin \theta}\,d\theta.$$ That might make it easier to see where the $\exp (z - z^{-1})$ comes from.
Comment: First, write the integral as one over circle $|z| = 1$. Next, expand $e^{-z^{-1}}$ as a power series $z^{-1}$ and verify you can exchange the order of integration and sum (remember all $|z| = 1$ at this step). Finally evaluate individual integral (if you want, you can do that by expanding $e^{z}$ as a power series in this step and once again verify you can exchange the order of integration and sum).
Comment: Right, so I guess that I have to calculate something like $\oint_C z^n \exp(z^{-1}-z) dz$, then the residue at 0 can be worked out by doing the Laurent expansion at 0. I think I can use the power series for $z^n\exp(z^{-1}-z)$, then just extract the $z^{-1}$ term by looking at the binomial coefficients, which is where I suppose the factorials come from. Is this correct?
Answer: I am not sure if this what you're looking for, but here's a solution. Don't want to contribute to the noise, so if it isn't useful I will delete it. A representation of the Bessel function is
$$
J_{n}(x) = \frac{1}{\pi}\int_{0}^{\pi}{\rm d}y\;\cos(n y - x\sin y)
$$
So, the integral you're trying to calculate is
$$
\int_0^{2\pi}{\rm d}\theta\;\cos(n\theta - 2\sin \theta) = 2\pi J_n(2) = 2\pi \sum_{r=0}^{+\infty}\frac{(-1)^r}{r!\Gamma(r + n + 1)}\left(\frac{2}{2}\right)^{2r + n} = 2\pi\sum_{r=0}^{+\infty}\frac{(-1)^r}{r!(r + n)!}
$$


Relacionamento MORPH

Question: Estou modificando uma table do banco de dados, no caso é para ser feito um relacionamento morph dos campos que estão conforme a imagem.
Estou usando o Laravel 5.6
Como faço essa relação dentro da migration?
Answer: Na documentação diz para fazer o Morph assim
$table->morphs('taggable'); Adds taggable_id UNSIGNED BIGINT and  taggable_type VARCHAR equivalent columns.

conforme https://laravel.com/docs/5.6/migrations

Relacionamento MORPH


how can I change digits from latin to persian digits

Question: I am using Drupal with localization module,
 in persian language,
I want in persian show persian digits instead latina digits?
Answer: You can use persiantools module, it change digits from latina to persian and some another features.....
persiantools


Why the observable collection returns correct number of objects but the object are empty?

Question: I have the following service
    @Injectable()
export class LMSVideoResulful {
    getVideos( enrolmentId : number ) :Observable<Array<Video>> {
        var x = new Array<Video>();
        //https://www.youtube.com/embed/MV0vLcY652c
        x.push( new Video( "SQL 1", "https://www.youtube.com/embed/qMvDsarDdK0", "sdsdssdss" ));
        x.push( new Video( "SQL 2", "https://www.youtube.com/embed/hVBALRtY8g0", "sdsdssdss" ));
        x.push( new Video( "SQL 3", "https://www.youtube.com/embed/qMvDsarDdK0", "sssdssds" ));
        x.push( new Video( "SQL 4", "https://www.youtube.com/embed/8Fo_KTDrBSU", "sdsdssdss" ));
        return from([x]);
    }
}

Here is the video model
export class Video{
    constructor(

        title : string,
        videoUrl: string,
        description : string
    ){}
}

In the component's constructor  i call the service as
constructor( private _sanitizer: DomSanitizer, public myVideoService : LMSVideoResulful ){//https://www.youtube.com/watch?v=cm196HOdSzI

    this.safeURL = this._sanitizer.bypassSecurityTrustResourceUrl("https://www.youtube.com/embed/MV0vLcY652c");

    this.myVideoService.getVideos(1).subscribe( x => {
      this.videoList = x;
      console.log(JSON.stringify(x));
    }, error => error)

  }

Even there are four objects sent through the service the console.log() line shows array of four objects but the objects are empty

Why this happens and how do i fix this?
Answer: This happens because most likely you have not assigned the values in the constructor to the member variables of your class. Due to which you get the object printed out, but with no properties.
Make sure that the class Video is defined as below:
export class Video {

  constructor(private seq: string, private url: string, private desc: string) { }

}

You need to declare the variables in the constructor with any access specifier. That then becomes a shorthand notation for assigning the values to them. Without them, as you can see the values will not be assigned.
Comment: You need to declare the variables in the constructor with any *access specifier*. That then becomes a shorthand notation for assigning the values to them. Without them, as you can see the values will not be assigned.
Comment: you are absolutely correct....now it working after adding access modifiers, thank you for the insight answer : )
Comment: i have updated my post with the Video class.... and what you have made properties private in your post?


Introductory multivariate statistics reference for beginners

Question: I am from computer science department doing research in data mining and image mining. I remember the last course about stat was introductory to statistics and probability in general. Now I have this course in master degree Multivariate statistical analysis and it's only for 1 month and it's very difficult to understand a lot of concepts. I need an easy to follow book about the subject of Multivariate statistical analysis for beginner!
Comment: What are the topics of your course? Does the course instructor recommend a book?
Comment: The course instructor book is in Chinese! So i need English easy to follow book. I visited the library and i saw Richard Johnson Applied on multivariate analysis and it was very hard, and i saw Anderson introduction to Multivariate statistics and i could not understand the first page!
Comment: Your question does not contain enough information. Do you need a conceptual or a more mathematical introduction? What should be covered in the book? Based on my psychological background I'd probably recommend either the book from [Tabachnik & Fidell](http://www.pearsonhighered.com/educator/product/Using-Multivariate-Statistics-6E/0205849571.page) or [Hair et al.](http://www.pearsonhighered.com/educator/product/Multivariate-Data-Analysis/9780138132637.page). Especially the last one is well written and easily understandable. However, they do not cover anything about data mining.
Comment: Have you searched for `[references] machine learning` on this site? There are already multiple answers for your question.
Comment: I would like the book to be related to data mining and machine learning in general, but looks like those books are advance on me. With that being said i will be happy to have introductory book at least to understand something! i don't understand what is a conceptual or a more mathematical introduction? I am programmer so science words are hard for me :(
Answer: Multivariate statistics is very broad, but given your background I'd recommend "Introduction to Statistical Learning" http://www-bcf.usc.edu/~gareth/ISL/ It's a really nice intro book to modern multivariate techniques that are popular in data mining and machine learning. You can get the PDF for free.
Comment: Thank you so much, but i need one which is easy to follow not advanced or hardcore.
I visited the library and i saw Richard Johnson Applied on multivariate analysis and it was very hard, and i saw Anderson introduction to Multivariate statistics and i could not understand the first page!!
So as you see i am fresh to statistics and this class is a must for me to do.
Comment: The first one aims at being a gentle introduction. It won't get much easier than that.
Comment: You mean Richard Johnson Applied on multivariate analysis? So what i some concept are hard! Do you have prerequisite book for it?
Comment: No, I mean the book in my answer!
Answer: Judging by your question, your program sounds similar to the many accelerated MS degrees with 6-8 week courses on each subject. I would recommend to go for statistics or econometrics texts for executive MBAs to survive. The EMBA level texts are easy to follow and do not expect strong math background. e.g. Wharton's EMBA program has Stat 613 as core course, and it uses Stine and Foster's text.
It's good to set the expectations right though. It's impossible to learn statistics without at least calculus and linear algebra, so if your definition of "easy" is without these two skills, then you're not going to learn anything useful in one month, but it's Ok. It's just the nature of these degrees, you only need to get an exposure to the field, i.e. very similar to EMBA objectives.
For programmers I'd recommend fun books such as R by Example in Springer's Use R! series. I read it while learning R already knowing statistics, but think that it can be used to learn both R and statistics. R is rather interesting language for programmers, it's based loosely on functional programming (FP) paradigm. That's why if your programmer friend is a hardcore programmer, he must know stuff like Haskell or Scala, and will feel comfortable picking a new FP language, especially because FP is fashionable again these days.
Another title in the same series is An Introduction to Applied Multivariate Analysis with R. If your friend is in good school, he will probably have SpringerLink access through his library, i.e. free PDF download of a book.
Comment: @MohammadAhmed, "for Dummies", really?
Comment: "It's impossible to learn statistics without at least calculus and linear algebra" Across many disciplines (no names!) the **majority** of practitioners of statistics have little or no background in those subjects, or at least that they can recall. Naturally it limits their understanding of the foundations, but equally much publishable work using statistics comes from such researchers. But I agree that "easy to follow" is difficult to comment on. I've not met anyone who wanted a book difficult to follow.
Comment: Okay thanks Nick, i mean by easy to follow not for advance but for beginner (programmer not mathematician student).
Comment: Let me see your response Aksakal and i will review it. Yeas actually i am for 2 years not rush master, but the course is for one month !!
Comment: @MohammadAhmed, you don't need to be math student to know calculus or linear algebra, it's a requirement in many quant majors, such as physics or engineering. Programmers are a different kind, they're sort of engineers, yet their math background is more like liberal arts. That's why you better look for texts not for engineers, but for "business" or liberal arts folks.
Comment: Yeah i need it for computer science student whose his background is less mathematical than math students. Do you you have book recommendation?
Comment: @Aksakal In an international and cross-disciplinary forum we can expect all kinds of backgrounds and personal trajectories. Programmers or business people who started as mathematicians or physicists won't fit the picture you sketch. I expect that you will agree, but careless wording can cause puzzlement or even (unintended!) offence here.
Comment: @MohammadAhmed, for a programmer it's more fun to read a book with a lot of coding examples, e.g. this one http://www.springer.com/statistics/statistical+theory+and+methods/book/978-1-4419-9649-7 or many others in the same Use R! series. I think that too much code is often distracting, but this Springer series usually have a good balance of code and background
Comment: @Aksakal what about Richard Johnso Applied multivariate statistics book i think it's good as it has some introduction. The Elements of Statistical Learning Data Mining, Inference, and Prediction. i think they are good. what do you think ?
Comment: @MohammadAhmed, I haven't read these. I know that the latter is mentioned a lot, and the reason is Coursera. JHU's data science courses refer to it.
Comment: Yeah you are right, but i saw the first chapter on amazon, content and some pages, i think it's much easier that introduction to multivariate statistics. i mean Richard Johanson book. Can you check Johanson in Amazon for content and first chapters then give me you opinion? it's very important. Thanks in advance.
Comment: I think i will borrow a book from library for Statistics For Dummies and richard johanson and read them at the same time !! becuase i find both good and easy to understand ? Do you agree with me Aksakal?
Comment: If you need to read introductory statistics texts, you aren't ready for a multivariate course.
Comment: @Aksakal okay i will take An Introduction to Applied Multivariate Analysis with R and Statistics for Business: Decision Making and Analysis (2nd Edition) for easy reading thank you so much.


I downgraded the instance size of my Wordpress GCE instance, the new instance doesnt seem to be running properly

Question: I have a GCE instance on which I was running a g1-small instance that hosted a wordpress site.
I wanted to downgrade the instance size to f1-micro, so I
a) stopped the instancce
b) edited the instance and changed it's size to f1-micro
c) started the instance
Unfortunately when the instance restarted, the wordpress site does not seem to be loading. SSH-ing into the instance reveals that Apache & MySQL are running, but visiting the newly generated external IP in the browser doesn't load the website.
Any ideas what might be wrong?
Sorry for details that might not have been specified well, super new to GCP & wordpress.
Comment: Please provide more details regarding the behavior you're seeing when trying to load the site and any relevant logging in the Apache/MySQL instances.
Answer: The cause of your issue is f1-micro doesn't have enough resources to run LAMP.
If you compare f1-micro and g1-small you'll see that f1-micro provides you significantly less resources even than g1-small. I do not recommend to use f1-micro for any production tasks. Have a look at the documentation N1 shared-core machine types to get more information:

You can slightly improve situation by shutting down some services like Logging agent google-fluentd that preinstalled to VMs or any other unnecessary services, but I'd rather switch back to g1-small.
In addition, you can try some images from Market place like openlitespeed-wordpress that offers preconfigured solution based on f1-micro.


java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener

Question: Well, i'm trying to Run my web application in tomcat, but i got the following error:
Nov 18, 2013 12:19:35 AM org.apache.catalina.core.StandardContext listenerStart
Grave: Error configuring application listener of class org.springframework.web.context.request.RequestContextListener
java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:415)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:397)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4638)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)

My project works with and some classes have strange errors, like this: "JOIN FETCH expressions cannot be defined with an identification variable.". When i run "Maven --> Update Project" the error in "JOIN FETCH.." disappear but i continue don't get start my server.
EDIT 1:
My pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>br.com.sender</groupId>
    <artifactId>Sender</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>sender App</name>
    <url>http://maven.apache.org</url>
    <properties>
        <org.springframework.version>3.0.6.RELEASE
        </org.springframework.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.primefaces.extensions</groupId>
            <artifactId>primefaces-extensions</artifactId>
            <version>0.7.1</version>
        </dependency>

        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1.6</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.1.6</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>3.4.0.GA</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.0.2.GA</version>
        </dependency>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901.jdbc4</version>
        </dependency>
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm-commons</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.7.4</version>
        </dependency>

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>3.5</version>
        </dependency>

        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>bootstrap</artifactId>
            <version>1.0.9</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>1.0</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>prime-repo</id>
            <name>PrimeFaces Maven Repository</name>
            <url>http://repository.primefaces.org</url>
            <layout>default</layout>
        </repository>

        <repository>
            <id>java.net2</id>
            <name>Java.net</name>
            <url>https://oss.sonatype.org/content/repositories/java.net2</url>
        </repository>
    </repositories>

    <build>
        <finalName>sender</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <targetJdk>1.6</targetJdk>
                </configuration>
            </plugin>
        </plugins>
        <resources>
         <resource>
            <directory>src/main/resources</directory>
         </resource>
        </resources>
    </build>
</project>

Comment: Your classpath is not setup properly. You must be missing dependencies.
Comment: can you help me with this ? how can i configure my classpath in correct way ? I think that Maven do it for me, download the librarys and add in classpath.
Answer: For this error, there can be different solutions. I have noted down the ones that had worked for me.
Solution 1. This is always happened in deployment and debugging environment. In deployment environment, just make sure your server classpath has included the Spring jar library (e.g spring-4.0.4.jar).
In debugging environment, the steps may vary from different IDE, but the solution is same. In Eclipse, developers usually will create a tomcat, jboss…whatever application server for debugging, just make sure the correct Spring jars are included.

Double click on your debugging server Click on the "Open launch
configuration" to access the server environment Click on the classpath tab Include the Spring jar file here , it may also
required common log jar due to Spring dependency.
Done, run your
    application again.

.
Solution 2. If you are using Maven as a build tool and downloading dependencies using it, there can be some jar conflict. Because Tomcat servers normally provide some jars such as servlet-api and jpa-api. So if you again included them using maven; there will be problems in identifying them.
Solution 3. If you are using Eclipse as your IDE and using Maven as your build tool and tomcat as your server; remember Tomcat server will not look on the jars which are just inside the folders. For that there's a small trick,

Right click on your project and select properties From the displayed window,
select Deployment Assembly
Select Add
Add Maven dependencies
Click Apply and Click OK

Hope one of these solutions would help you to solve your problem. Happy Coding and make sure that is using Java.
Answer: In eclipse -> Your Project -> Properties -> Java Build Path -> Order and Export -> check Maven Dependencies.
Or in WebProject -> Your Project -> Properties -> Deployment assambly -> check Maven Dependencies.
This work in my case.
Answer:
I had the same issue, but I fixed by adding Maven Dependencies. It was missing for some reason, and I have no clue
Answer: I have faced a similar issue with the same exception "java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener".
It fixed after adding one dummy class in the src/main/java folder, and I really didn't know how this did the trick, it works for me.


Habilitar/Desabilitar Button de acordo com valor Checkbox em um DataGridView

Question: Um formulário em uma aplicação Windows Forms com C# exibe um DataGridView com Checkbox.
Quando um dos Checkbox for marcado quero habilitar um determinado botão.
Se nenhum Checkbox for marcado quero desabilitar.
Tente assim:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    bool marcado = false;
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView1.CurrentRow.Cells["chk"];
        if (chk.Value == chk.TrueValue)
        {
            marcado = true;
            break;
        }
    }

    if (marcado)
        button1.Enabled = true;
    else
        button1.Enabled = false;
}

E não funcionou.
Tentei usar no CellValueChanged e também não esta funcionando.
Como resolver este problema.
Comment: estou sem o Visual Studio para testar, mas tente alterar `DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView1.CurrentRow.Cells["chk"];` para `DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["chk"];`, se der certo eu crio uma resposta!
Comment: @Mateus Ainda não funcionou. O valores `chk.Value` e `chk.TrueValue` estao com `Value` = `null`. Acho que estou usando no método errado. Mas valeu a ajuda.
Answer: Você pode fazer isso utilizando o evento CellValueChanged desse jeito:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    // se a célula alterada for a célula de interesse (1.)
    if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("chk"))
    {
        bool marcado = false;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["chk"]; // (2.)
            // se a célula estiver marcada
            if ((bool)(chk.Value ?? false) == true) // (3.) e (4.)
            {
                marcado = true;
                break;
            }
        }

        if (marcado)
            button1.Enabled = true;
        else
            button1.Enabled = false;
    }
}

Seguem alguns pontos de atenção:

Utilizei um if antes de verificar os valores das DataGridViewCheckBoxCell para evitar que a verificação ocorra em todas as colunas.
Conforme falei nos comentários, foi necessário alterar dataGridView1.CurrentRow para row, pois senão seu for não iria percorrer todas as linhas, mas sim, somente a linha corrente (referente a célula alterada).
O ?? serve para verificar se operador a esquerda dele é nulo, caso seja, retorna o valor da direita, senão, retorna o valor da esquerda, para saber mais veja Qual o significado do operador "??".
A propriedade TrueValue deve ser utilizada de outra forma, como não sei exatamente como você está usando o DataGridView, preferi não utilizá-la, mas você poder ver um exemplo aqui.

Não sei exatamente qual o volume de dados você irá trabalhar, mas fazer esse for toda vez que uma célula for marcada/desmarcada, provavelmente você não terá um bom desempenho, pensei em outra solução, talvez seja necessário que você a melhore, porém já serve como ponto de partida.
Crie uma variável global private int numeroCelulasMarcadas = 0;, essa variável vai servir como um contador de células marcadas, no evento RowsAdded do DataGridView, faça assim:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    DataGridViewCheckBoxCell chk =
        (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["chk"];

    if ((bool)(chk.Value ?? false) == true)
    {
        numeroCelulasMarcadas++;
    }
}

Agora no evento CellValueChanged coloque isso:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    // se a célula alterada for a célula de interesse
    if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("chk"))
    {
        DataGridViewCheckBoxCell chk =
            (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["chk"];

        if ((bool)chk.Value == true)
        {
            numeroCelulasMarcadas++;
        }
        else
        {
            numeroCelulasMarcadas--;
        }

        if (numeroCelulasMarcadas == 0)
        {
            button1.Enabled = false;
        }
        else
        {
            button1.Enabled = true;
        }
    }
}

Lembre-se que essa solução que passei por último é um ponto de partida, pode ser que seja necessário ajustar alguma coisa para funcionar corretamento no contexto da sua aplicação.
Comment: O post tem informações importantes, porém ainda não funcionou. Usando qualquer umas das opções de código o método `CellValueChanged` ao marca o primeiro `CheckBox` ele não é disparado. Nem estou preocupado com a performance a principio, pois seria poucos registros.
Comment: @Jota, após alterar o valor da célula, você tentou pressionar `ENTER` ou sair da célula? Pois testei várias vezes antes de postar a resposta e funcionou perfeitamente!
Comment: Eu não sabia que tinha de teclar `Enter`, realmente funciona. O problema é que o usuário não quer teclar o `Enter`. kkkk Quebrando a cabeça e com o que você postou, consegui uma solução que funciona somente com o click usando o `CellContentClick` e `CellContentDoubleClick`. Mas valeu a ajuda e o conhecimento compartilhado.
Comment: você pode aceitar a resposta se acha que te ajudei a atingir o objetivo da pergunta ou pode criar e aceitar sua própria resposta com a solução que você encontrou, detalhando como você fez.
Comment: As duas soluções podem ser consideradas corretas. kkk Vou ver o que faço. Mais uma vez obrigado.
Answer: A solução que o Mateus propôs funciona, mas é preciso pressionar a tecla Enter, no meu caso o usuário queria somente clicar no CheckBox, então usei a seguinte solução:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("chk"))
    {
        ManipulaBotao();
    }
}

private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("chk"))
    {
        ManipulaBotao();
    }
}

private void ManipulaBotao()
{
    button1.Enabled = false;
    foreach (DataGridViewRow dr in dataGridView1.Rows)
    {
        if (bool.Parse(dr.Cells["chk"].EditedFormattedValue.ToString()))
        {
            button1.Enabled = true;
            break;
        }
    }
}

Assim somente clicando no CheckBox o controle é habilitado/desabilitado.
Vale ressaltar que no meu caso o número de linhas é pequeno então não afeta a performance, como foi muito bem lembrado no post do Mateus.
Note o uso do método CellContentDoubleClick, senão não funciona como o esperado.
Comment: o principal fator para ter funcionado é a propriedade `EditedFormattedValue`, pois havia tentado nesse evento também, mas utilizando a propriedade `Value`, que não retornava o valor atual e sim o que estava quando entrou na célula.


Can a directed graph be a vector space?

Question: I've come across this terminology for "linearly independent paths"

linearly  independent  path  is  any  path  through  the  program  that introduces  at least one new edge that is not included in any other linearly independent paths

is there a way to frame graphs as vector spaces?  I can sort of see how this idea is related, but I'm having trouble seeing how to add paths in a way that makes sense and it well-defined.
https://en.wikipedia.org/wiki/Cyclomatic_complexity
Comment: Well, I've just found [this](https://en.wikipedia.org/wiki/Edge_space), which tells that the edge space is a vector space, so the answer should be yes.
Comment: I don't know if directed graphs in general can be regarded as vector spaces, but there's a notion of independence that generalise that of vector spaces and it's used in graphs and other structures. This concept is introduced in the theory of [Matroids](https://en.wikipedia.org/wiki/Matroid)
Answer: They are talking about power set of the set of vertices or edges. The power set of any set is a vector space over the finite field of order $2$. The addition operation is given by taking the symmetric difference.
$$A+B=(A\setminus B)\cup (B\setminus A)$$
Scalar multiplication can really only be defined in one way.

Can a directed graph be a vector space?


What is the role of GC(Garbage Collection) other then memory management

Question: What is the role of GC (Garbage Collection) other then memory management?
-Anil
Comment: How do you mean? The purpose of GC is memory management, it doesn't have another role.
Answer: Reducing bugs due to memory mis-management.
Comment: The leaks are also easier to find. Because when you leak memory you can find from which GC-root the stuff is reachable. That makes it easy to find the code which produces the leak. The 'forgotten-to-free' leaks are harder to find the trace back.
Comment: I don't think that the GC reduces bugs on itself. It makes memory management easier, but leaks (e.g. due to weak references) are still possible
Answer: The role of the Garbage Collector is just the memory management. It remove non-referenced objects from memory. Therefore memory management is made much easier.
In some rare cases memory leaks are still possible.


Sleep in Smalltalk Squeak

Question: I'm dealing with N*N queens problem and gui of it.
I want to sleep for a few seconds each move so the viewer can see the process.
How do I put smalltalk to sleep?
Thank you
Answer: Instead of sleeping you can just wait.
5 seconds asDelay wait.

e.g. if you select and print it the following, it will wait 5 seconds before printing the result (2)
[
    5 seconds asDelay wait.
    1 + 1
] value

The comment of the Delay class explains what it does.

I am the main way that a process may pause for some amount of time.  The simplest usage is like this:
(Delay forSeconds: 5) wait.
An instance of Delay responds to the message 'wait' by suspending the caller's process for a certain amount of time. The duration of the pause is specified when the Delay is created with the message forMilliseconds: or forSeconds:. A Delay can be used again when the current wait has finished. For example, a clock process might repeatedly wait on a one-second Delay.
A delay in progress when an image snapshot is saved is resumed when the snapshot is re-started. Delays work across millisecond clock roll-overs.
For a more complex example, see  #testDelayOf:for:rect: .

Update: (based on comment)
wait will pause the execution flow, which means that in the example earlier, the 1 + 1 will get executed (execution flow resumed) only after the wait period has ended.
So in your class you can have...
MyBoard>>doStep
    self drawBoard.
    5 seconds asDelay wait.
    self solve.
    5 seconds asDelay wait.
    self destroyBoard.

Comment: how exactly does the wait work? I instantiate my board and draw it, then i want it to wait x seconds, start solve, wait x seconds, then delete the board. Im not sure i understand exactly when the wait happens and when the next/previous command happens
Comment: @Infested I've added the class comment of the Delay class.
Comment: @Infested and another update... if I understand your comment correctly.
Comment: Thanks, yes you did answer my question!
Comment: I do see something strange though, I print solutions in the form of permutation on the transcript (in solve method) and draw it as well as gui. when I do draw wait solve, it draws at the same time it starts to solve. any idea why?
Comment: @Infested maybe the UI loop is being executed in a different process? I don't know without seeing the code (maybe best to ask a separate question with a real code sample).
Comment: I dont really know which part to show, is there any way to send you the code and you look at it and tell me why it acts that way?
Comment: Well stackoverflow has a chat or something like that... but a pastebin link might suffice.
Comment: do you have an answer?

Sleep in Smalltalk Squeak


Is there a tpl.php file generated by Drupal 7 for custom content types

Question: I seem to remember it being mentioned somewhere in the past that when you create a new content type in Drupal 7 that there is a corresponding node--[content-type].tpl.php file created somewhere by Drupal core. I may be wrong. However, if there is such a file created, how do I find it so I can copy it in to my theme?
Maybe it defaults to the node.tpl.php file, but I thought a new file for the custom content was created. Just don't know where to find it if it is created.
TIA
Answer: No; Drupal doesn't ever create template files dynamically.
For new content types the default node.tpl.php, or the one provided by the enabled theme, will be used.
Answer: Yes you can per content type. Use #2 under node at https://www.drupal.org/node/1089656#node-suggestion it should be node--[type].tpl.php.
So for lets say a content type that has the machine name blog, it would be node--blog.tpl.php
As Clive said Drupal doesn't do this automatically.
Comment: Thanks - I thought there was one generated automatically. No idea where that thought came from - perhaps template files in relation to contrib modules...

I just decided to use the base node.tpl.php file and add in my custom field for the content type.


Why does the likelihood function of a binomial distribution not include the combinatorics term?

Question: So the likelihood function for a binomial distribution is:

Why is the likelihood function above not multiplied by a combinatorics term: n! / (x! * (n - x)!)
If the likelihood function is interpreted as the probability of an outcome occurring x times out of n trials as the parameter, θ, varies, shouldn't there be a combinatorics term as that would provide the actual probability?
Thanks!
Answer: We often don't care about the likelihood, just the value for which the likelihood is maximized.
When you use the likelihood function to find a maximum likelihood estimator, you get the same point giving the maximum whether you include constants out front or not. Sure, that maximum value will be different, but that is not our concern.
So let's make it convenient for ourselves and drop constants out in front, especially bulky combinatorics terms!
While we're at it, we usually take the logarithm of the likelihood function since its derivative is easier to calculate, and log doesn't change the point at which the maximum occurs.
Edit
This is in my comment but ought to be in the main post. We typically care about the argmax of a likelihood function, not the max itself.
Comment: Thanks!  I'm guessing there isn't a case where we actually need the likelihood itself?  I know when we do Bayes Analysis the constant would cancel out when dividing the joint by the marginal.
Comment: I don't want to go as far as saying that we'd never care about the likelihood, but we often can get away with dropping coefficients because they cancel or because we care about the argmax instead of the max itself.


Paragraph Entity Query returns too many results

Question: I'm trying to find a paragraph that have a certain taxonomy term value and on a matching parent node. I tried the code below, but it always returns over 30 values, when really only one paragraph entity is possible. Not sure what I'm missing.
<code>$query = \Drupal::entityQuery('paragraph')
    ->condition('status', 1)
    ->condition('type', 'player_assignment')
    ->condition('field_year_season', $term_id)
    ->condition('parent_id', $node_id);

$results = $query->execute();
</code>
Comment: Have you looked with a database client to see what records are returned? I am going to wager a guess they are all 'status 1'.
Answer: If this returns 30 paragraphs then all of them were at some point stored in the parent node, but not necessarily in the current revision. It might be easier to load the node and then check the paragraph field content of the current revision or, in case you don't know the node ID, start your entity query with the node entity:
<code>$query = \Drupal::entityQuery('node')
  ->accessCheck(FALSE)
  ->condition('field_paragraph.entity.field_foo', 'bar');
</code>


Decompiling an RPM?

Question: This is hopefully a simple question. Are there any tools out there to find out an enhanced description (beyond the normal rpm command) of the contents of an rpm, and possibly decompile it? We currently have an rpm from our company's security team which is supposed to be used for centralized authentication on our linux servers. The issue is that they can't supply source, and don't have a documented list of all changes that are made on the server. They did say that decompiling the rpm was ok.
So, any ideas??
Answer: Look at RPM2CPIO and objdump.
Answer: Here's a nice post that goes through various options of getting into packages: http://www.thegeekstuff.com/2010/04/view-and-extract-packages/
Here's the gist of it for an RPM:
$ rpm2cpio package.rpm | cpio  -idmv

Answer: It turns out that 7zip could extract the rpm to a cpio package, which again 7zip could extract to expose the files that are placed in the system.

Decompiling an RPM?


Changing the indexing order of BitArray in Python

Question: I am using a BitArray in my python script, and I was wondering if there is a way to change the indexes order of the BitArray that I create. Right now the indexes are from 0 to N-1 where N is the number of bits.  Is there away to change the indexes to go from N-1 to O?
dataBits = BitArray('0b10100000')
print(dataBits[0])

This above two lines return the first bit True because the order of indexes is from 0 to N-1. Can I change the order of indexes for this to return the last bit False?
Comment: It may be effective to subclass the BitArray class and add a custom method that allows you to achieve that
Comment: Is it acceptable to reverse the bits before you create your `BitArray`? IE: `dataBits = BitArray('10100000'[::-1])`? Otherwise, you should subclass and implement your own `__getitem__` and `__iter__` methods. The first is preferable since there might be other methods in `BitArray` that depend on the order and might lead to "unexpected" behavior. Also, where is the documentation for the `BitArray` library you're using?
Comment: What is returning anything `True` or `False`?
Answer: Yes. What you're looking for is the module variable lsb0:
bitstring.lsb0 = True
dataBits = bitstring.BitArray('0b10100000')
print(dataBits[0])

Prints out False.


How do you hot-deploy java applications in production?

Question: Assuming you have a productive java application and don't want to have (even small) downtimes for software updates (including updated .class files) to take effect.
What infrastructure / server / tools do you use to achieve this?
Any experiences are much appreciated! Could be anything like two servers where one is updated while the other does the "old" job, features of e.g. a Tomcat server or tools enabling this.
Answer: It's not entirely clear from your description, but I'm guessing you're talking about Java EE and not Java SE applications?  Java SE, we just use JNLP for deployment.  Java EE, where we use Glassfish as the container and it has an option to install a new version without interrupting current sessions.  We're not super heavy users, so I'm not absolutely positive that it has prevented an issue, but we've never had an issue.  Our Tomcat EE users just get rudely bumped periodically when we do updates and are used to it at this point.  :-(
Comment: To make it simple: J2SE = Client softwares, J2EE = Server software that runs on an application server
Comment: Thanks for the insight! Actually I wasn't so much aware about the difference between Java SE and Java EE; I'm just using grails which I think is based on Java SE(?).


Can't setImage

Question: Noob Alert,
I am trying to change an image in a UIImageView.
popCard is the IBOutlet pointed to the UIImageView - which is blank in IB.
there are 5 possible images (Graphic0, Graphic1, etc.)
For some reason it keeps displaying Graphic1.
I got a feeling I'm missing something simple. Can you help please?
This what i am using:
getCard=0;
 NSLog(@"begin showCard = %i",getCard);
 FlowCoverAppDelegate *mainDelegate = (FlowCoverAppDelegate *)[[UIApplication sharedApplication]delegate];
 getCard = mainDelegate.showCard;
 NSLog(@"showCard = %i",getCard);

 if (getCard = 0) {
     [popCard setImage:[UIImage imageNamed:@"Graphic0.jpg"]];
     popCard.contentMode = UIViewContentModeScaleAspectFit;
     return;
 }

Cheers
Paul
Answer: The issue with your code is the following:
You are assigning getCard to 0 in your if expression, change it to ==.
Also, if getCard is not a property of your object, you need to declare it as int getCard = 0;
What you should do:
Instead of writing 5 if statements, just write this one line:
[popCard setImage:[UIImage imageNamed: [ NSString stringWithFormat: @"Graphic%d.jpg", getCard ] ] ];

Comment: that's why some prefer to write if (0 == getCard)
Comment: Thank you! That's the second time == caught me out.

Vladmir - I really like that format. It'll help me remember.

Can't setImage


JPA Crud repository query method not working

Question: I want to get a list of users by username, with enabled status and has phone number. I managed to get it working till I add the phone number parameter.
here is my code:
<code>//crud repo
List<Users> findAllByUserNameContainsAndEnabledIsAndMobileNotNull(String userName, String  enabled);
</code>
<code>// controller

public Set<User> searchByName(@PathVariable String username) throws Exception {
        Set<User> result = new HashSet<>();
        result.addAll(userRepository.findAllByUserNameContainsAndEnabledIsAndMobileNotNull(username, "Y"));

        return result;

    }

// user class

public class User{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(precision = 18, scale = 0)
    private BigDecimal id;

    @Column(name = "Enabled", columnDefinition = "char(1) default 'Y'")
    private String enabled;

    private String username;

    private String mobile;

// getters setters..
</code>
Comment: please post your `User` class
Comment: added my user class
Comment: is it typo? `List` - should be `User`
Comment: I have reproduced your case in new project and everything works using custom method that returns `List`.
Comment: have you solved the issue?
Answer: What is your phone number parameter called? You said it was working until that. The names have to match.
Here is all supported keywords in the method names:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
Comment: Please use comments when clarifying additional points. This is not the answer.
Answer: I have started new project and everything works as expected, so the problem is not in method name. Here is code I've tested:
Entity
<code>@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(precision = 18, scale = 0)
    private BigDecimal id;

    @Column(name = "Enabled", columnDefinition = "char(1) default 'Y'")
    private String enabled;

    private String userName;

    private String mobile;

    public User(String enabled, String userName, String mobile) {
        this.enabled = enabled;
        this.userName = userName;
        this.mobile = mobile;
    }
}
</code>
Repositiory
<code>public interface UserRepository extends CrudRepository<User, BigDecimal> {
    List<User> findAllByUserNameContainsAndEnabledIsAndMobileNotNull(String userName, String  enabled);
}
</code>
Test
<code>@SpringBootTest
@ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;
    @Test
    void test_findAllByUserNameContainsAndEnabledIsAndMobileNotNull() {

        User user1 = new User("Y", "user1", "mobile");
        User user2 = new User("Y", "user2", null);
        userRepository.save(user1);
        userRepository.save(user2);

        List<User> all = userRepository.findAllByUserNameContainsAndEnabledIsAndMobileNotNull("user", "Y");
        System.out.println("all = " + all);
    }
}
</code>
And only one record in the output:

all = [User(id=1, enabled=Y, userName=user1, mobile=mobile)]


If the sum of squares of three prime numbers is a prime number, prove that atleast one of those three numbers is 3.

Question: If the sum of squares of three prime numbers $a, b, c$ where $a, b, c \in \mathbb{N}$, is a prime number, prove that at least one of $a, b, c$ is equal to 3.
I've received a hint to assume that $\forall a, b, c \neq 3$ but sadly don't know how to use this fact, so I ask for help.
Answer: If none of them are $3$, then they are all of the form $3m+1$ or $3m+2$ (they don't all have to be the same form). Their squares are all of the form $3n+1$, so the sum of those squares is divisible by $3$. This is impossible.
Comment: +1 - I was just a few seconds away from providing a very similar answer.
Answer: The sum of squares of three numbers none of which are divisible by $3$ is divisible by $3$. This is because the square of any number not divisible by $3$ is congruent to $1$ mod $3$. It follows that one of the primes must be divisible by, hence equal to, $3$.


Comparing Multivariable-Regression Models Derived from Different Sample Sizes

Question: I have a small dataset (n=39) with one dependent variable (y) and several independent variables (x1, x2, …, xn). For most of my independent variables I have 39 measurements. However, I am missing some measurements for some independent variables. For example, independent variable x1 is composed of 39 measurements but independent variable x2 and x3 are composed of 30 and 32 measurements, respectively.
I have built several simple- and multivariable-linear regression models to predict the dependent variable and I am having difficulty selecting the best model. Since some independent variables did not have 39 measurements, models were built different sample sizes. Most models had a sample size of 30. I had originally planned to use the corrected Akaike information criterion (AICc) for model selection (Wikipedia) but I recently learned that the AICc is only supposed to be used to compare models with the same sample size (Stack Exchange Link).
What model selecting criteria can I use to in this situation? I am using python for my analysis.
Answer: I would suggest you fix the number of data points before creating any model. You either remove all the data points which contain missing values or replace the missing values with the mean/median of that variable. You can also look for advanced methods like EM-algorithm to fill the missing values.
Once you are done with that, you can proceed with creating model. Apart from multiple regression, you can use best subset regression, ridge regression, lasso, etc. and compare them according to their AIC.
Hope this helped.
Answer: Multiple imputation of the missing data is one accepted way to approach this problem. There are nearly 400 questions on this site tagged as multiple-imputation. That's valid provided that the data are missing at random in a specific way, often a reasonable assumption.
Instead of simply replacing missing values individually with means or medians or modes you create multiple copies of the data set, with each copy containing probabilistic estimates of the missing values. You then do your regression analyses on each of the imputed data sets and pool the results in a way that takes into account the uncertainty in the imputation. Then the problem of different sample sizes for the different models disappears.


What is the integrand of a path integral?

Question: I have been reading the Deligne et. al notes "Quantum Fields and Strings: A Course For Mathematicians" and I am trying to reconcile what I learned with what physicists are doing. I am confused about what physicists mean by expressions of the form $$\langle 0|\phi(x_1)...\phi(x_n)|0\rangle= \int \mathcal{D}\phi \; \phi(x_1)...\phi(x_n)e^{iS[\phi]}$$
I am not asking about the measure $\mathcal{D}\phi$. This integral is supposed to be the "$n$-point correlation function of the field $\phi$" and should return a scalar, but the $\phi(x_i)$ are all supposed to be operators on a Hilbert space, so it is not clear to me how this happens.
This notation also suggests to me that this correlation function is independent of the field $\phi$ (since $\phi$ is also used for the variable of integration), but this seems unreasonable. Would it be correct to say $$\langle 0|\psi(x_1)...\psi(x_n)|0\rangle= \int \mathcal{D}\phi \; \psi(x_1)...\psi(x_n)e^{iS[\phi]}$$ instead?
Answer: The integrand is the functional $F[\phi]:= \phi(x_1)\cdots\phi(x_n)\exp(iS[\phi])$. Your confusion probably stems from the fact that physicists like to jump around between the Hamiltonian picture where your field is some kind of operator-valued distribution, and the Feynman picture where you're working with path integrals and $\phi$ is just a function (or distribution). The link between them is precisely that the vacuum expectation value of the operator $\phi(x_1)\cdots\phi(x_n)$, i.e.
$$
\langle 0|\phi(x_1)\cdots\phi(x_n)|0\rangle,
$$ can be calculated as the path integral of the integrand I wrote above.
Comment: Neither am I, lol. Ok, usually if your field classically is of type X (be that a section of a vector bundle, a differential form, or a connection on a principal bundle), you think of your operators as being some "operator version" of X, no idea what that means concretely :D
To your specific question: when you work with a gauge theory, you can only expect to get a nonzero expectation value if your expression is gauge-invariant, and I don't think products of the connection form are usually gauge-invariant.
Comment: Thank you for your answer. How does this work when the classical fields are not scalar fields? The example on my mind right now is $U(1)$ Yang-Mills theory; I am not aware of a natural way to multiply connections.
Answer: The field $\phi$ has slightly different meanings inside the path integral and outside of it, as the Feynman path integral is relating two different interpretations.
Inside the path integral, imagine that we're summing an action of classical fields over a measure of all possible values for those classical fields. As a variable of integration, $\phi$ is thus a classical field and each value $\phi(x_i)$ is a scalar value.
Outside the path integral is where $\phi$ is a Hilbert space operator.
Comment: The action term S is always a scalar, and so the fields always have to be combined to form scalars. It's been a while since grad school, but memory serves that a U(1) Yang-Mills theory is just a complex scalar field $\psi$, and so the action involves terms like $\psi \psi^*$. For a non-abelian Yang-Mills theory, the representations of the fields always are combined to form scalars; e.g. using the metric if they are vector representations.
Comment: Coupling terms between different fields also have to combine to form scalars. For instance, the connection couples a vector representation of a gauge field with spinor representations of charged particle fields in Lagrangian like $\psi^\dagger \gamma^{\mu} D_{\mu} \psi$ which are scalar
Comment: I deleted my last comment because it was wrong (or at least misleading). An expectation like $\langle 0 \left| A\mu(x_1) A_\nu(x_2) \right| 0 \rangle$ is valid, where $A$ is the gauge field itself, a vector-valued operator on Hilbert space, and not the connection. Since the product of the vectors transforms like a tensor, this expectation transforms like a tensor valued. Now, the connection (which you've represented with $\mathcal{A}$) is formed from the gauge field(s) and the derivative operator, and this doesn't have a product operator that you could stick in a vacuum estimate.
Comment: You don't need to define an abstract product of connections. Just express things in coordinates and pick values for the indices attached to the connections then just take the product of the corresponding components or coordinates.
Comment: Thank you for your answer. How does this work when the classical fields are not scalar fields? The example on my mind right now is $U(1)$ Yang-Mills theory; I am not aware of a natural way to multiply connections.
Comment: sorry, I am not very familiar with the physics language for these things. My understanding is that a $U(1)$ gauge field is a connection $\mathcal{A}$ on the trivial $U(1)$-principal bundle $P$ over spacetime. I know the action is always scalar valued, but I am confused about the meaning of an expression like $\mathcal{A}(x_1)\mathcal{A}(x_2)e^{iS[\mathcal{A}]}$, where $x_1,x_2$ are points on spacetime.
Comment: @AbdelmalekAbdesselam, am I right that in expectation values, correlation functions, etc. one only ever takes the gauge field part of the connection, and not the operator that  includes the term $i \gamma^2 \partial_\mu$? I guess the operator $\partial_\mu$ can be applied to the vacuum, as in Fourier space it would just be giving the momentum of the vacuum, and so maybe there's no reason in principle that the "full" connection couldn't appear as an Hamiltonian-picture operator. But since there's just one such connection even when there are multiple gauge fields, this didn't strike me as normal


Bad line breaking in Eclipse javadoc comments

Question: There's a minor but annoying bug, I think, in the Eclipse built-in Java formatter. I have a Javadoc comment that looks like this:
<code>/**
 * - - - stuff - - - {@code mTasksBelow}.
 */
</code>
where period at the end is in column 81. The formatter is set to wrap Javadoc comments at line 80. Unfortunately, when I format the code, it does this:
<code>/**
 * - - - stuff - - - {@code mTasksBelow}
 * .
 */
</code>
This puts white space between the text and the period in the generated output, so a browser rendering the Javadoc in HTML, for instance, will also think it's okay to break there.
This doesn't seem to happen unless the period follows a Javadoc tag. (For instance, if the line ended with a closing parenthesis and a period in column 81, it would correctly break before the last word.)
I could move the wrap column, but that would just move the problem. I don't want to turn
off line breaks, because I like my Javadoc source to be as readable as the generated output. Is there some setting I'm missing or is this actually a bug?
Answer: Well there is a less than fun work around for this.  To work around it try enabling Off/On Tags in the Eclipse formatter.
Window -> Preferences -> Java -> Formatter -> Edit -> Off/On Tags -> Enable Off/On tags
Then you need to surround your comment with these tags so the formatter does not touch it (Note that the tags need to be in separate comment blocks else Eclipse will ignore them).  In example:
<code>//@formatter:off
/**
 * Oddly formatted comment.              MUHAHAHAHAH :)
 **/
//@formatter:on
</code>
Presto... formatter won't touch it.  Tested on Juno on Fedora 17.  Hope that helps.
Answer: Well, it is now a new Eclipse bug. It will evidently still be present in the initial Indigo release.
Comment: And Juno. And Kepler. And Luna... :-(


I am getting an exception when execute solr - Exception in building suggester index for: suggest

Question: <code>org.apache.solr.handler.component.SuggestComponent  – Building suggester index for: suggest
org.apache.solr.spelling.suggest.SolrSuggester  – build()
ERROR org.apache.solr.core.SolrCore  – Exception in building suggester index for: suggest
java.lang.IllegalArgumentException: need at least one suggestion
at org.apache.lucene.search.suggest.analyzing.FreeTextSuggester.build(FreeTextSuggester.java:338)
at org.apache.lucene.search.suggest.analyzing.FreeTextSuggester.build(FreeTextSuggester.java:278)
at org.apache.lucene.search.suggest.Lookup.build(Lookup.java:165)
at org.apache.solr.spelling.suggest.SolrSuggester.build(SolrSuggester.java:142)
at org.apache.solr.handler.component.SuggestComponent$SuggesterListener.buildSuggesterIndex(SuggestComponent.java:488)
at org.apache.solr.handler.component.SuggestComponent$SuggesterListener.newSearcher(SuggestComponent.java:472)
at org.apache.solr.core.SolrCore$6.call(SolrCore.java:1716)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>
I am trying to import data using SOLR component with solrconfig.xml, schema.xml and db-data-config.xml files and datasource configuration also perfect i think. While i am executing solr, showing above error.
Could you please help on this to resolve issue and let us know what was the issue....
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: This can happen if you have empty values in your suggest field.


Como exibir validações e erros de domínio numa partial view modal bootstrap?

Question: Estou utilizando DDD e tenho algumas validações no meu domínio que precisam ser feitas, porém quando eu utilizo o ModelState.AddModelError e retorno o meu modelo e a minha PartialView, o formulário da minha Partial não permanece no modal aberto. Ao invés disso, exibe uma página html sem estilos css. Sei que tenho que fazer com Javascript/Ajax/jQuery e retornar um Json no Controller. Mas ainda não acertei fazer funcionar. Alguma maneira eficaz de fazer?
Coloquei os códigos para facilitar a visualização de algo que esteja errado. Basicamente o que quero é retornar os erros que acontecerem no controller para serem exibidos dentro da PartialView carregada no modal bootstrap.
Código do Controller
public ActionResult Create()
        {
            ViewBag.Title = "Adicionar Ação de Formulário";
            return PartialView("~/Views/Acao/_AcaoFormulario.cshtml", _acaoAppService.Iniciar());
        }

        [HttpPost]
        public JsonResult Create(AcaoViewModel acaoViewModel)
        {
            JsonResult result;

            var errorResult = new List<ValidationError>();

            if (ModelState.IsValid)
            {
                var acaoReturn = _acaoAppService.Salvar(acaoViewModel, acaoViewModel.AcaoId);

                if (!acaoReturn.ValidationResult.IsValid)
                {

                    foreach (var error in acaoReturn.ValidationResult.Erros)
                    {
                        errorResult.Add(new ValidationError(error.Message));
                    }

                    return result = Json(new ActionResponse(false, errorResult), JsonRequestBehavior.AllowGet);
                }

                return result = Json(new ActionResponse(true, null), JsonRequestBehavior.AllowGet);
            }

            errorResult.Add(new ValidationError("Ação Inválida"));

            return result = Json(new ActionResponse(false, errorResult));
        }

PartialView com Formulário do Carregado no Modal
@model PAD.Application.ViewModels.AcaoViewModel

@{
    Layout = null;
}

        @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "acaoFrm", onsubmit = "acaoSubmit()" }))
        {

                <button class="close" type="button" data-dismiss="modal">
                    Close
                    x
                </button>

@ViewBag.Title

                    @Html.AntiForgeryToken()
                    @Html.HiddenFor(model => model.AcaoId)

                                @Html.LabelFor(model => model.Nome)
                                @Html.TextBoxFor(model => model.Nome, htmlAttributes: new { @class = "form-control" })

                                @Html.LabelFor(model => model.Tipo, htmlAttributes: new { @for = "tipo" })
                                @*@Html.TextBoxFor(model => model.Tipo, htmlAttributes: new { @class = "form-control" })*@
                                <select class="form-control" id="tipo" name="tipo">
                                    <option>-- Selecionar --</option>
                                    <option value="A">Ação BD</option>
                                    <option value="C">Consulta BD</option>
                                </select>

                                @Html.LabelFor(model => model.FonteDadosId)
                                @Html.DropDownListFor(model => model.FonteDadosId, Model.ComboFonteDados, "-- Selecionar --", new { @class = "form-control" })

                                @Html.LabelFor(model => model.Take)
                                @Html.TextBoxFor(model => model.Take, htmlAttributes: new { @class = "form-control" })

                                @Html.LabelFor(model => model.Execucao, htmlAttributes: new { @for = "execucao" })
                                @*@Html.TextBoxFor(model => model.Execucao, htmlAttributes: new { @class = "form-control" })*@
                                <select class="form-control" id="execucao" name="execucao">
                                    <option>-- Selecionar --</option>
                                    <option value="E">Excluir</option>
                                    <option value="X">Executar</option>
                                    <option value="S">Salvar</option>
                                </select>

                                @Html.LabelFor(model => model.RotinaId)
                                @Html.DropDownListFor(model => model.RotinaId, Model.ComboRotinas, "-- Selecionar -- ", new { @class = "form-control" })

                                @Html.LabelFor(model => model.Descricao)
                                @Html.TextBoxFor(model => model.Descricao, htmlAttributes: new { @class = "form-control" })

                                @Html.LabelFor(model => model.PopUpContainer)
                                @Html.TextBoxFor(model => model.PopUpContainer, htmlAttributes: new { @class = "form-control" })

                                @Html.LabelFor(model => model.Where)
                                @Html.TextAreaFor(model => model.Where, htmlAttributes: new { @class = "form-control", @rows = "10" })

                                @Html.LabelFor(model => model.OrderBy)
                                @Html.TextAreaFor(model => model.OrderBy, htmlAttributes: new { @class = "form-control", @rows = "10" })

                <button class="btn btn-danger shadow" type="button" data-dismiss="modal">
                     Fechar
                </button>
                <button type="submit" class="btn btn-success shadow pull-right" onclick="document.getElementById('acaoFrm').submit();">
                     Salvar
                </button>

        }

Javascript que chama o modal
$("#novaAcao").click(function () {
        $("#modal").load("/acao/create", function () {
            $("#modal").modal("show");
        });
    });

Comment: Edite a pergunta e coloque o código que você já fez.
Answer: Bom, vamos por partes:

Se sua action é HttpPost, não é necessário o trecho "JsonRequestBehavior.AllowGet" (apesar de não ocorrer erro);
Seu form já tem o evento "onsubmit" associado. Logo, ao clicar no submit button este evento será disparado automaticamente, sem necessidade deste trecho: onclick="document.getElementById('acaoFrm').submit();
Na sua função "acaoSubmit()" chame sua action HttpPost via Ajax. No evento "done()" da chamada Ajax, faça algo do tipo:

.done(function(result){
  if(result.data != null && !result.data.sucesso){ //sucesso: primeiro parâmetro de ActionResponse
    var erros = result.data.errorList; //errorList: segundo parâmetro de ActionResponse
    $.each(erros, function(key, value ) {
      $("#divErros").append("
" + value + "
"); //crie uma divErros em sua modal.
    });
  }
});

Seu código fica ainda melhor e mais legível definindo o Response.StatusCode em sua action HttpPost em caso de erro (ex.: 400, 500) ou sucesso (ex.: 200). Neste caso teria que mudar também seu tratamento do retorno da chamada Ajax.
Aqui vai um exemplo:
https://stackoverflow.com/questions/12112361/how-to-set-http-status-code-from-asp-net-mvc-3
Comment: Valeu mesmo! Era exatamente isso que eu estava procurando. E muito obrigado pelas dicas.


Can't decrypt imaps traffic in Wireshark

Question: I have currently problems to decrypt IMAPS Traffic in Wireshark.
I set up the SSL Key with the correct IP Address, Port 993 and Protocol imap. The Key is the correct one.
That is what I see in the SSL log:
dissect_ssl enter frame #136 (already visited)
  conversation = 0x7fdb633e83f8, ssl_session = (nil)
  record: offset = 0, reported_length_remaining = 229
dissect_ssl3_record: content_type 23
association_find: TCP port 59182 found (nil)
association_find: TCP port 993 found 0x7fdb77125e80

Also, Wireshark shows me in the TLSv1 Packages, that there should now be IMAP data, but I can't see anything when I do the "Follow SSL Stream".
The SSL Package looks like this:
0000  00 00 ff ff 00 00 00 00  00 00 00 00 00 00 08 00   ........ ........
0010  45 00 00 89 40 41 40 00  40 06 91 04 0a 2a 2a 6f   E...@A@. @....**o
0020  0a 2a 2a 67 e7 2e 03 e1  21 f5 32 a6 c9 f9 82 f5   .**g.... !.2.....
0030  80 18 00 b6 a7 fb 00 00  01 01 08 0a c2 d2 70 e0   ........ ......p.
0040  c2 d2 70 e0 17 03 01 00  50 76 ee bc d7 bb 0d ec   ..p..... Pv......
0050  f0 0d 92 1f 1a 26 77 c9  bd f6 8e 63 1f f7 57 43   .....&w. ...c..WC
0060  a7 96 80 df 48 0e 57 a5  7b e0 6b 6b 2a bd 56 0d   ....H.W. {.kk*.V.
0070  84 dd 45 df 33 1b 36 e5  85 fa 75 d6 5c f7 1d f3   ..E.3.6. ..u.\...
0080  dc 70 ec e1 17 53 a9 40  d9 7f 61 56 8a 86 df 13   .p...S.@ ..aV....
0090  a1 51 24 db bc 8b 39 2b  96                        .Q$...9+ .

So it's TLS 1.0 and 80 Bytes of data, but I can't read it decrypted. Whats wrong? I successfully viewed HTTPS Traffic with Wireshark...
Comment: Which cipher suite is used?
Comment: @Bruno Cipher Suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA (0x0039)
Comment: @Bruno ohhh i see: http://www.wireshark.org/lists/wireshark-users/200802/msg00182.html This is DH and i dont have the exchanged keys... so no decryption of this...
Comment: ah, I see you've found the issue, that's why I asked about the cipher suite.
Answer: You can't decrypt Ephemeral Diffie-Hellman (DHE) with only the private key. See these links:

https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=3977
http://www.unleashnetworks.com/blog/?p=28
https://stackoverflow.com/questions/4767125/ssl-key-exchange-encryption-techniques
Comment: @reox. If it's just for testing purposes, you might be able to turn off the DHE cipher suites in your client. For example, in Thunderbird: Preferences -> Advanced -> General -> Config Editor, then filter using `security.ssl3.*` (this should apply to SSLv3 as well as TLSv1), you can toggle them on/off. In real use, it's actually a good thing to have perfect forward secrecy, so I'd leave them enabled.
Answer: After some research i found out that TLS_DHE_RSA_WITH_AES_256_CBC_SHA is used as Cypher. According to this: http://www.wireshark.org/lists/wireshark-users/200802/msg00182.html its obviously impossible to decrypt DF...


How to map complex json in React

Question: I have an API that i am connecting to as part of an application that i am developing and i am having a hard time with trimming down everything to get to the objects and rendering out the data.
I have inserted some of the json snippet that is coming back from the API.
Please help.
[
  {
    "ssn": [],
    "name": [
      {
        "pidlist": [],
        "meta": {
          "sources": [],
          "firstSources": [],
          "middleSources": [],
          "lastSources": [],
          "firstInitialSources": [],
          "middleInitialSources": [],
          "firstSeen": 19931001,
          "lastSeen": 20220226,
          "count": 133,
          "rank": 0
        },
        "data": "JOHN R ARCHER",
        "first": "JOHN",
        "last": "ARCHER",
        "middle": "R"
      },
      {
        "pidlist": [],
        "meta": {
          "sources": [],
          "firstSources": [],
          "middleSources": [],
          "lastSources": [],
          "firstInitialSources": [],
          "middleInitialSources": [],
          "firstSeen": 19931001,
          "lastSeen": 20220222,
          "count": 79,
          "rank": 1
        },
        "data": "JOHN ROBERT ARCHER",
        "first": "JOHN",
        "last": "ARCHER",
        "middle": "ROBERT"
      },
      {
        "pidlist": [],
        "meta": {
          "sources": [],
          "firstSources": [],
          "middleSources": [],
          "lastSources": [],
          "firstInitialSources": [],
          "middleInitialSources": [],
          "firstSeen": 19870601,
          "lastSeen": 20211214,
          "count": 107,
          "rank": 2
        },
        "data": "JOHN ARCHER",
        "first": "JOHN",
        "last": "ARCHER"
      }
    ],
    "dob": [
      {
        "meta": {
          "sources": [],
          "dSources": [],
          "mSources": [],
          "ySources": [],
          "firstSeen": 19900301,
          "lastSeen": 20220222,
          "rank": 0
        },
        "date": {
          "data": "XX/XX/XXXX",
          "sortable": 0
        },
        "age": "51"
      },
      {
        "meta": {
          "sources": [],
          "dSources": [],
          "mSources": [],
          "ySources": [],
          "firstSeen": 19900301,
          "lastSeen": 20220222,
          "rank": 2
        },
        "age": "71"
      },
      {
        "meta": {
          "sources": [],
          "dSources": [],
          "mSources": [],
          "ySources": [],
          "firstSeen": 20070501,
          "lastSeen": 20070501,
          "rank": 3
        },
        "age": "??"
      }
    ],
    "address": [
      {
        "meta": {
          "sources": [],
          "firstSeen": 20151204,
          "lastSeen": 20220316,
          "count": 87,
          "rank": 0
        },
        "data": "1775 EDWIN DR, WAYLAND, MI 49348-9315",
        "streetNumber": "1775",
        "street": "EDWIN",
        "streetSuffix": "DR",
        "city": "WAYLAND",
        "state": "MI",
        "zip": "49348",
        "zip4": "9315",
        "dateRange": "12/04/2015-03/16/2022",
        "complete": "1775 EDWIN DR",
        "isCass": "Y",
        "county": "BARRY",
        "rank": 0,
        "latitude": 42.62675,
        "longitude": -85.534946,
        "ownership": "C",
        "topPoBox": 0,
        "highFrequency": false
      },
      {
        "meta": {
          "sources": [],
          "firstSeen": 20180816,
          "lastSeen": 20210629,
          "count": 3,
          "rank": 1
        },
        "data": "1803 S PATTERSON RD, WAYLAND, MI 49348-8817",
        "streetNumber": "1803",
        "street": "PATTERSON",
        "streetSuffix": "RD",
        "city": "WAYLAND",
        "state": "MI",
        "zip": "49348",
        "zip4": "8817",
        "predir": "S",
        "dateRange": "08/16/2018-06/29/2021",
        "complete": "1803 S PATTERSON RD",
        "isCass": "Y",
        "county": "BARRY",
        "rank": 1,
        "ownership": "C",
        "topPoBox": 0,
        "highFrequency": false
      },

This is what i have tried as a first step and cannot find anything helpful in searching:
  { Object.keys(data[0]).map((item, i) => (

    ))}

I have referenced these two posts and tried them but i am still not getting the results that i am looking for:

How to Map JSON in React?
How to map a nested JSON response in React
Comment: Are you trying to show the data as JSON?  or are you trying to show particular pieces of the data?
Comment: Could you show a sample of the desired output?
Comment: I am trying to show the data in a combination of things like in a table or scattered in p tags through the page, here is an example of how i want the data right now for testing but the json is nested and i cant figure it out:
Data
Name: JOHN R ARCHER

Is Dead Flag: false

Address1: 1775 EDWIN DR, WAYLAND, MI 49348-9315

Address2: 1803 S PATTERSON RD, WAYLAND, MI 49348-8817
Answer: I would be inclined to make a wrapper class to hold your data (since it's kind of complex).  And then add helper methods to grab the bits and pieces you want to get out of it.
Then you can use those to display things in a component.
Something like:

// Wrapper class to hold the data and build small getters to pluck
// out the things you want.  `Entry` is a bad name.  You should chose
// something that makes sense in your domain like UserData or ?
class Entry {
  constructor(data) {
    this.data = data;
  }

  get address() {
    return this.data.address[0].data;
  }

  get name() {
    return this.data.name[0].data;
  }

  get dob() {
    return this.data.dob[0].date.data;
  }

  get age() {
    return this.data.dob[0].age
  }
}

Then a component that can, given one Entry render it...
const EntryDisplay = ({ item }) => {
  return (
    <>

Address

          {item.address}

Name

          {item.name}

DOB

          {item.dob} ({item.age} years old)

    </>
  );
};

This could instead render a table row (tr) or list item or paragraphs or whatever.  I chose the description list for simplicity.
And finally, run through your list of data and render the components like:

const EntriesList = () => {
  return (

Entries

      {data.map((entry, idx) => (

Entry {idx}

          <EntryDisplay item={new Entry(entry)} />

      ))}

  );
};

The beauty of the wrapper class (Entry) is that whatever complex thing you need to do to get data out of the deep data hash is compartmentalized in that "model", so then your component can be simpler.
To make this work in your case, you'll likely have to add more helper methods for the particular bits of data you want for each subsection.  Hopefully this is a reasonable starting point.
If you need more, you could add even more helper classes/models to unpack Address as a thing or DOB, since each one of those seems to allow multiple entries.

How to map complex json in React


Help implementing Supersized.js in Drupal 7

Question: I am trying to add Supersized.js into my Drupal 7 site. I have updated Drupal to use the latest version of jQuery, I added scripts[] = js/supersized.3.1.3.min.js to my .info file, and in my html.tpl.php file i added:

I am stuck here. I am not very experienced with Drupal, Javascript, or jQuery.
Edited to include Bob's change to the wrapper.
Comment: I just released a module (still in sandbox, but it works for me) that adds Supersized to Views using the Views_JQFX module. Here is a [link](http://drupal.org/sandbox/thechanceg/1358600) to my sandbox. Please try it out and let me know how it goes. Please keep any bugs/feature requests in the issue queue on the sandbox.
Comment: Well, I guess @kiamlaluno thought my answer wasn't worthy. I'm not sure why since it clearly implements supersized.js like the question asked for. I would love it if you test out my module though. I want to release it as a full project and could use help testing it out.
Answer: There are a few issues here.

It's not in Drupal best practices to add a script to html.tpl.php
That being said, there are two ways to do it. (a) You can add it to your theme's .info file and call a .js file script from there (i.e. "scripts.js") in your theme folder, ideally in a "js" or "scripts" sub-folder if you need this site-wide (b)  If you don't need it site-wide or you can call it with drupal_add_js in your theme's template.php file to target only specific pages / paths
The way Javascript gets called has changed in Drupal 7

The main new thing is to include something like:
(function ($) {
//needed for drupal 7
Drupal.behaviors.myTheme = {
attach: function(context, settings) {
// end drupal 7 syntax

... at the top of your script.
so a clean version should work like so:
(function ($) {

//needed for drupal 7
Drupal.behaviors.myTheme = {
attach: function(context, settings) {
// end dtupal 7 syntax

            $.supersized({

                //Functionality
                slideshow               :   1,      //Slideshow on/off
                autoplay                :   1,      //Slideshow starts playing automatically
                start_slide             :   1,      //Start slide (0 is random)
                random                  :   0,      //Randomize slide order (Ignores start slide)
                slide_interval          :   3000,   //Length between transitions
                transition              :   1,      //0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
                transition_speed        :   500,    //Speed of transition
                new_window              :   1,      //Image links open in new window/tab
                pause_hover             :   0,      //Pause slideshow on hover
                keyboard_nav            :   1,      //Keyboard navigation on/off
                performance             :   1,      //0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
                image_protect           :   1,      //Disables image dragging and right click with Javascript
                image_path              :   'img/', //Default image path

                //Size & Position
                min_width               :   0,      //Min width allowed (in pixels)
                min_height              :   0,      //Min height allowed (in pixels)
                vertical_center         :   1,      //Vertically center background
                horizontal_center       :   1,      //Horizontally center background
                fit_portrait            :   1,      //Portrait images will not exceed browser height
                fit_landscape           :   0,      //Landscape images will not exceed browser width

                //Components
                navigation              :   1,      //Slideshow controls on/off
                thumbnail_navigation    :   1,      //Thumbnail navigation
                slide_counter           :   1,      //Display slide numbers
                slide_captions          :   1,      //Slide caption (Pull from "title" in slides array)
                slides                  :   [       //Slideshow Images
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/quietchaos-kitty.jpg', title : 'Quiet Chaos by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/wanderers-kitty.jpg', title : 'Wanderers by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/apple-kitty.jpg', title : 'Applewood by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'}
                                            ]

            });

//ending drupal 7 specific calls / syntax
}};
}) (jQuery);

Answer: Have you verified through viewing the page source in your browser that the script is being loaded correctly? If it isn't you can investigate into where the file is located on your server versus where your info file is pointing to.
If it IS loading correctly I imagine it's something client side. If it's just going on your front page, or a particular page you could use something like front--page.tpl.php/node--.tpl.php/etc and put your code there.
If it's client side it might also make good sense to create/find a working copy that uses just HTML, and transfer your code piece by piece from there, that way you can at least have a working copy to verify against.
This would require some troubleshooting, and a general working knowledge of JavaScript, but I will say I had similar issues getting a jQuery image gallery up on my own site, and worked it out after some trial and error.
edit
I just noticed in your code the wrapper is:
(function($){
    //code
}(jQuery));

You should change that to:
(function($){
  // code
})(jQuery);

Sorry I didn't notice before, but this is probably why the alerts aren't working.
Comment: The code is showing when I view source.
Comment: If it's loading correctly then it's either something client side or something with your images not loading; I can't really offer much more advice without additional info on what's happening and what's not though.
Comment: Sorry about that, I accidentally submitted just the first line of my reply. The code is showing when I view source. I tried uploading the sample page that came with the source code and it works. the code used above came directly from their sample with the only change being to the beginning of the function. The original code was jQuery(function($){ which I changed to (function ($) {  because of the documentation I found for using jQuery with Drupal.
Comment: You can try adding an alert(''); inside the jQuery container to make sure the code is executing. I would put in a working $.supersize(...) example, and then once you verify that works modify it to work with your images/etc
Comment: I put alert('test'); in the script in a couple of places and it never triggered.
Comment: See my edits above I think that is the issue you're having
Comment: I changed the wrapper as you suggested but it still isn't working, I have updated the question with the new code. Thank you for all your help on this.
Comment: Try removing the second alert, you can't execute code like that in the middle of an object declaration: {}. As a side note, some of these issues should be causing errors, your browser will give you clues as to what's wrong.
Answer: Have you included all the CSS and JavaScript files that come with supersized.js?
Looking at the code, it seems you have an alert('test2'); inside the supersized call. That should be removed; also, in the supersized call you have a option called "image_path" that doesn't seem to be an available option for the supersized plugin. Try removing that.
I would also update the plugin to the current release, which is 3.2.6.
Comment: Correct, `alert('test2');` throws a syntax error.


Is it possible to scan an xml element using single Xpath expression when the element is case insensitive

Question: I have below XML which I need to parse.I need to take name value.But the name element might be case insensitive.How to write a generic Xpath epression to read element with name or Name?
<Employees>
    <Employee id="1">
        <age>29</age>
        <name>Pankaj</name>
        <gender>Male</gender>
        <role>Java Developer</role>
    </Employee>
    <Employee id="2">
        <age>35</age>
        <Name>Lisa</Name>
        <gender>Female</gender>
        <role>CEO</role>
    </Employee>
</Employees>

Below expression will good for name element when we give id as dynamic value.
XPathExpression:
exprs = xpath.compile("/Employees/Employee/@id" + id+ "']/name/text()");

Answer: Try below XPath to match both name and Name elements
/Employees/Employee/*[matches(name(), "name", "i")]/text()

/*[matches(name(), "name", "i")] should match any element (*) which name (name()) is equal to "name" ignoring ("i") case
Answer: You can try the XPath translate() function :
translate(string1,string2,string3)
Converts string1 by replacing the characters in string2 with the characters in string3
In your case, the following:
//Employee/*[translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='name']";
will:

For each Employee
Check each children
Convert all letter in the name of the child ( local-name() ) that are Uppercase to lowercase
Compare it to "name"

With this, you don't have to check manually for each possibility and can be re-use for anything else too ; you just have to replace "name" by tho word you want to check.
For futher reading:
translate()  --> https://developer.mozilla.org/fr/docs/XPath/Fonctions/translate
local-name() --> https://developer.mozilla.org/fr/docs/XPath/Fonctions/local-name


weird result after filtering with Gaussian Recursive Filter

Question: I implemented Gaussian recursive filter(by R. Deriche) using OpenCV and c++. However, the result I'm getting is weird. I also tried normalizing the resulting image between 0 and 255 but even that doesn't help.
any help would be great
Comment: Please provide a sample of code; we have no idea what you're doing wrong if we have no idea what you're doing.
Comment: @AbhishekThakur did you compare the gaussian you obtained with your implementation against the standard simple way to obtain gaussians ? If they are much different, then your implementation of the method is wrong. If they are nearly equal, then how you are convolving is wrong.
Comment: Comments for negative vote would be appreciated.
Comment: thanks, ill be editing the main post with chunks of what ive done.
Comment: Better yet, explain the algorithm step-by-step, with intermediate results and code. E.g. this are the filter parameters I get, this is the 1d impulse response, this is the 2d impulse response, etc. Unless the error in your code is totally obvious, that's what anyone trying to help you would have to do, too.
Comment: It is too much trouble explaining in details gaussian recursive filter by Deriche, not a good fit for a single question.
Comment: I have added code. I tried again but no good results....thanks in advance
Comment: I cant find the error in your code, but when I have gotten images like the one in your question, it has been because I ran over the range of the variables that I was using.  You cannot cast a float to an unsigned char without handling the under / overflow.  For example your line  output.at(i,j) = (unsigned char)((float)fabs(sumvec[j]) + 0.5f) assumes that sumvec[j] + .5 is within 0 to 255.
Comment: the sum of the two vectors will cause the range to exceed 255. how can I handle the under/overflow?
Answer: the Image has to be taken as float in the input. The processing has to be done on this float image and then normalize the result using
<code>normalize(output, output,0,255,NORM_MINMAX,CV_8UC1);
</code>
Thanks for helping guys.