text:
Q: How to deal with "If P, then Q" in the description of a set? Here is the original question:
Given sets $A,B,C$ express the set in terms of A,B,C, using the symbols $\cup$,$\cap$, and $-$. $$F=\{x | x\in A\text{ and } (x\in  B) \rightarrow (x\in C)\}$$
I have found some solution like $A-(B-C),\,A\cap(B \cap C),\,(B \cap C)\cap A$. I do these all by trying, I wonder if there is a regular way to find or to judge whether I have found all the solution. Someone else give a more answer (−)∪(∩) for the same question. Welcome edit if there is something unclear, thanks!
New add: Maybe an explanation for my second and third answers is necessary. Take the second one. If $x\in ∩(∩)$, it is trivially true that $x\in A$ and the both side of → is true because $x\in B, x\in C$. Above is my understanding, or I am wrong? Please point out. And if my second and third answers is right, my question will be different from which is suggested below.

A: $\phi \to \psi$ is logically equivalent to $\lnot \phi \lor \psi$.
So $$\{x\mid (x \in B) \to (x \in C\}$$ is then just the same as (with $\phi=(x \in B)$, $\psi=(x \in C)$ $$\{x\mid x \notin B \lor x \in C\}$$
which is $$B^\complement \cup C$$
The first clause of the definition of $F$ says $x \in A$ so we must intersect that set with $A$ and we get
$$A \cap (B^\complement \cup C) = (A \cap B^\complement) \cup (A \cap C)$$
(Using distributivity of $\cap$ over $\cup$)
But the question asks to use $-$ (for which I prefer $\setminus$ as a notation BTW) and then a little thought tells us that $A \cap B^\complement = A-B$ and so we get as answer $$(A-B) \cup (A \cap C)$$
This doesn't correspond directly to any of your suggested answers though.


text:
Q: PostgreSQL failure in Spring Boot I have a new Spring Boot app that I'm trying to plug into my local PostgreSQL instance, but I'm having driver failures. I've got a basic driver class set up like so:
package com.rainydaymatt.lfgenie.lfgenieapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LfgenieApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(LfgenieApiApplication.class, args);
    }
}

I decided to forego .yml configuration for the moment in favor of the default application.properties file, and used what little PSQL content for Spring Boot I could find to cobble this together:
spring.datasource.url=jdbc:postgresql://localhost:15432/harpm
spring.datasource.username=admin
spring.datasource.driver-class-name=org.postgresql.Driver

And then added a dependency for a persistent PostgreSQL instance to the Initializr-constructed pom like so:
<groupId>com.rainydaymatt.lfgenie</groupId>
<artifactId>lfgenie-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>lfgenie-api</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.1-901.jdbc4</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

And I'm getting this failure trace(s), which appears to hinge on a missing or unreachable driver:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: org.postgresql.Driver
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at com.rainydaymatt.lfgenie.lfgenieapi.LfgenieApiApplication.main(LfgenieApiApplication.java:10) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: org.postgresql.Driver
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
... 33 common frames omitted

A: Issue solved with following configuration and versions:
SpringBoot: 2.4.0
Postgres: 9
<dependency>
 <groupId>org.postgresql</groupId>
 <artifactId>postgresql</artifactId>
</dependency>

application.properties
spring.cloud.gcp.sql.enabled=false
spring.datasource.url=jdbc:postgresql://localhost:5433/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.properties.hibernate.default_schema=public

spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5

A: Below configuration works for me
#==== connect to postgreSQL ======#
spring.jpa.hibernate.ddl-auto=create-drop
spring.datasource.url=jdbc:postgresql://localhost:5432/rs_ecommerce
spring.datasource.username=postgres
spring.datasource.password=password
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

# Disable feature detection by this undocumented parameter. Check the org.hibernate.engine.jdbc.internal.JdbcServiceImpl.configure method for more details.
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false

# Because detection is disabled you have to set correct dialect by hand.
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect

# seems like we don't need to put the below driver properties in application.properties file for latest version of postgreSQL.

spring.datasource.driver-class-name=org.postgresql.Driver

Details:
https://jdbc.postgresql.org/documentation/head/load.html

A: Update the following things:-
pom.xml
 <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>

Application.properties
 spring.datasource.url=jdbc:postgresql://localhost:5432/db_name
 spring.datasource.username=username
 spring.datasource.password=password
 spring.jpa.hibernate.ddl-auto=update
 spring.datasource.driverClassName=org.postgresql.Driver
  spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

A: It's problem with you postgres driver. Try another one or check the local maven repo. Or you can use this one:
<dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4.1208</version>
    </dependency>

A: Drop the driver-class name. Spring will derive it from the datasource-url. You should have maven dependency for postgresql.

A: If you are using a dependency for PostgreSQL in pom.xml
<dependency>
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.1-901.jdbc4</version>
</dependency>

You don't need to add a Driver in aplication.properties so, remove
spring.datasource.driver-class-name=org.postgresql.Driver

and it should work. Also, don't forget to add password property.
spring.datasource.password=your-db-password

A:        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

#==== connect to postgreSQL ======#
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:postgresql://localhost:5432/schooldb
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

# Disable feature detection by this undocumented parameter. Check the org.hibernate.engine.jdbc.internal.JdbcServiceImpl.configure method for more details.
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false

# Because detection is disabled you have to set correct dialect by hand.
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect

A: If you are using gradle add the following line in the build.gradle file
implementation 'org.postgresql:postgresql:42.5.0'

A: Remove the following from application.properties in Spring Boot App.

#spring.datasource.driver-class-name=org.postgresql.Driver

This should help in resolving the issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP get values by given keys I have array like this:
$user = [
'id' => 1,
'fname' => 'name1',
'lname' => 'lname',
'age' => 20
];

I want to get values by given keys. Is there function already.
$userData = array....($user, ['fname', 'lname']); // get only fname and lname from user

I dont want to to for loops or similar.
Thanks

A: You can use array_intersect_key, after flipping the second array to an associative array.
$userData = array_intersect_key($user, array_flip(['fname', 'lname']));


text:
Q: Can the "true" prior lead to better posterior estimation? Suppose we know $X_1,\dots, X_n \sim N(\mu,1)$, and $\mu\sim N(1,1)$, so the true prior is $N(1,1)$. Now if we want to compare the true prior with $N(2,1)$, can we say the true prior is better than the wrong one in any sense if we want to estimate $\mu$ using the MLE of the posterior?
My guess is that we can take the expectation of the square error:
$$\mathbb E_{\mu \sim N(1,1)} \|\hat \mu - \mu\|$$
where $\hat \mu$ is the MLE of the posterior. If we use the $N(1,1)$ as our prior, will it be better?


text:
Q: Using wp_query to modify the loop in index.php for a CPT I was given a basic umbrella theme to work with and modify for individual needs. I have added a few custom post types. I am having trouble modifying the index.php page to work with my new CPTs.
For example, one CPT is called is a page called beach_clean. It's on a page called beachclean.php and made it a template page like so:
<?php
/*
  Template Name: Beach Clean Page
*/
get_header();  ?>

Normally I would set up a wp_query like this to retrieve the specific CPT info:
<?php
$args = array(
  'post_type' => 'beach_clean'
);
$the_query = new WP_Query( $args );
?>

and then modify the loop like so:
<?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

however I am unsure how to do it based on how the original code is written.
Can anyone help me see how to insert a query for my CPT into the way the code is written?
Please and thank you!
Here is the index.php page:
<?php
    // Start the Loop.
    $index = 1;
    $total_results = $wp_query->post_count;
    while ( have_posts() ) : the_post();
     if ($index == 1):
        get_template_part('template-parts/post', 'hero');
        if ($total_results > 1):
        ?>

        <?php endif; ?>
     <?php else: ?>

          <?php if (has_post_thumbnail()) {
              get_template_part('template-parts/content', 'media_block_top');
          } else { get_template_part('template-parts/content', 'media_block_no_img');
            } ?>

     <?php endif; ?>
     <?php
     $index++;
     endwhile;

         if ($total_results > 1): ?>

                <?php
                // Previous/next page navigation.
                the_posts_pagination( array(
                    'screen_reader_text' => " ",
                    'prev_text'          => __( 'Previous page', 'twentysixteen' ),
                    'next_text'          => __( 'Next page', 'twentysixteen' ),
                    'before_page_number' => '' . __( '', 'twentysixteen' ) . ' ',
                ) );
                 ?>

<?php endif; ?>

A: I would suggest first adding a new file called
archive-beach_clean.php
to your themes root directory.
Then copy and paste all the code from that index file into it.
After, if you haven't done so already, add this argument, 'has_archive' => true,  to the arguments array used in the register_post_type function and in the same array make sure rewrite isn't set to false.
Then go to the wordpress admin area Settings->Permanlinks and make sure Post name is selected and click Save (this will flush your permalinks in case the post type wasn't registered already, now it will be).
Finally, you will be able to access your new page here http://your_domain.com/beach_clean
If you want to change the slug to something other than beach_clean, add the rewrite argument in as noted above, and make the value of it is array('slug' => 'your-custom-slug')


text:
Q: Help making userscript work in chrome I've written a userscript for Gmail : Pimp.my.Gmail & i'd like it to be compatible with Google Chrome too.
Now i have tried a couple of things,  to the best of my Javascript knowledge (which is very weak) & have been successful up-to a certain extent, though im not sure if it's the right way.
Here's what i tried, to make it work in Chrome:
The very first thing i found is that contentWindow.document doesn't work in chrome, so i tried contentDocument, which works.
BUT i noticed one thing, checking the console messages in Firefox and Chrome, i saw that the script gets executed multiple times in Firefox whereas in Chrome it just executes once!
So i had to abandon the window.addEventListener('load', init, false); line and replace it with window.setTimeout(init, 5000); and i'm not sure if this is a good idea.
The other thing i tried is keeping the window.addEventListener('load', init, false); line and using window.setTimeout(init, 1000); inside init() in case the canvasframe is not found.
So please do lemme know what would be the best way to make this script cross-browser compatible.
Oh and im all ears for making this script better/efficient code wise (which im sure is possible)
edit: no help...? :'(
edit 28-Apr:
i re-wrote the code a little and now it looks something like this.:

if(document.location != top.location) return;

(function() {
var interval = window.setInterval(waitforiframe, 3000);
var canvas;
function waitforiframe() {
    console.log("Finding canvas frame");
    canvas = document.getElementById("canvas_frame");
    if (canvas && canvas.contentDocument) {
        console.log("Found canvas frame");
        pimpmygmail();
    }
}
function pimpmygmail() {
    gmail = canvas.contentDocument;
    if(!gmail) return;
    window.clearInterval(interval);
    console.log("Lets PIMP.MY.GMAIL!!!");
    ......rest of the code......
})();
This works perfectly fine in Firefox, but in Chrome, it gives me a top is undefined error.
Another thing i noticed is that if i remove the first line if(document.location != top.location) return; , the waitforiframe() method keeps getting called over and over again. (ie i see the "Finding canvas frame" error in the console)
can someone tell me what does the first line do? i mean what does it achieve & why does the waitforiframe() method run forever if i remove that line??

A: A BIG THANK YOU TO ALL WHO HELPED! -_- meh
btw, this was all i needed at the beginning of the script:
try { if(top.location.href != window.location.href) { return; } }
catch(e) { return; }


text:
Q: detect when use allow the application to use universal access I am developing an utility for OSX which need to use Universal Access (accessibility and event tap).
I am using AXIsProcessTrustedWithOptions to check if the application is allowed. I am checking this state every second (pooling) in order to detect when user is allowing it.
Unfortunately, AXIsProcessTrustedWithOptions is always returning false, even when the application has been allowed.
I know it is possible because others applications like popclip  are doing it but I cannot figure out what I am doing wrong.
Added: code
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:(id)kCFBooleanTrue, kAXTrustedCheckOptionPrompt, nil];
if (!AXIsProcessTrustedWithOptions((CFDictionaryRef)options) ) {
    while (!AXIsProcessTrustedWithOptions(NULL)) {
        NSLog(@"Still not allowed");
        [NSThread sleepForTimeInterval:1.0f];
    }
    NSLog(@"user just allowed the application");
}
else
{
    NSLog(@"App is already allowed");
}


text:
Q: Biblatex parencite command with dot right before the closing parenthesis My university likes to have some interesting cite rules and to comply to them I would need citing commands to produce
<author> (<year>), (<author> <year>) and (<author> <year>.) To do this I looked into natbib and found \citet and \cite that closely resembled what I needed. With a little fiddling I managed to get them closer to what I needed. The problem came with the dot and the comma in the middle
Here is what I currently have.
\documentclass[12pt,twoside,english]{article}
\usepackage[backend=biber,style=authoryear-comp,natbib,citetracker=true,%
maxcitenames=1,uniquename=false,uniquelist=false]{biblatex}
\addbibresource{cite/citedb.bib}
\usepackage{xpatch}

\renewcommand*{\finalnamedelim}{%
  \addspace\&\space}
\AtEveryCitekey{\ifciteseen{}{\clearfield{namehash}}}

\xpatchbibmacro{cite}
  {\printnames{labelname}}
  {\ifciteseen
    {\printnames{labelname}}
    {\printnames[][1-99]{labelname}}}
  {}
  {}

\xpatchbibmacro{textcite}
  {\printnames{labelname}}
  {\ifciteseen
    {\printnames{labelname}}
    {\printnames[][1-99]{labelname}}}
  {}
  {}

\begin{document}

\citet{foo}

\citet{foo}

\citep{foo}

\cited{foo}

\printbibliography

\end{document}

What this currently produces me is
Foo, Bar & Baz (xyz)
Foo et al., (xyz)
(Foo et al., xyz)
So how can I get that comma go away in \citep before the year and also create the needed command ?\cited? with the dot at the end like this?
(Foo et al. xyz.)

A: You can make the comma go away with
\renewcommand*{\nameyeardelim}{\addspace}

Indeed it is the natbib compatibility mode (see blx-natbib.def) that makes this change necessary, the default is to use a space only.

The period in \cited you can get with
\newrobustcmd{\mkbibparensperiod}[1]{\mkbibparens{#1\addperiod}}
\DeclareCiteCommand{\darencite}[\mkbibparensperiod]
  {\usebibmacro{cite:init}%
   \usebibmacro{prenote}}
  {\usebibmacro{citeindex}%
   \usebibmacro{cite}}
  {}
  {\usebibmacro{postnote}}

\newrobustcmd*{\cited}{\darencite}


text:
Q: tidyr extract regular expression I have a data frame that contains some statistics for a number of variables and scenarios.  The data looks like:
df <- data.frame(
  Scenario = c('base','stress','extreme'),
  x_min = c(-3,-2, -2.5),
  x_mean = c(0,0.25, 1),
  x_max = c(2, 1, 3),
  y_min = c(-1.5, -2, -3),
  y_mean = c(1, 2, 3),
  y_max = c(5, 3, 3.5),
  z_min = c(0, 1, 3),
  z_mean = c(0.25, 2, 5),
  z_max = c(2, 4, 7)
)

   Scenario x_min x_mean x_max y_min y_mean y_max z_min z_mean z_max
1     base  -3.0   0.00     2  -1.5      1   5.0     0   0.25     2
2   stress  -2.0   0.25     1  -2.0      2   3.0     1   2.00     4
3  extreme  -2.5   1.00     3  -3.0      3   3.5     3   5.00     7

I would like to use tidyr's gather and extract functions (in a similar manner to Hadley's answer to this question) to get the data in a format like:
new_df
    Scenario variable  min  mean   max
1     base        x   -3.0  0.00   2.0
2   stress        x   -2.0  0.25   1.0
3  extreme        x   -2.5  1.00   3.0
4     base        y   -1.5  1.00   5.0
5   stress        y   -2.0  2.00   3.0
6  extreme        y   -3.0  3.00   3.5
7     base        z    0.0  0.25   2.0
8   stress        z    1.0  2.00   4.0
9  extreme        z    3.0  5.00   7.0

The command I have so far looks like:
new_df <- df %>%
            gather(key, value, -Scenario) %>%
            extract(key, c("min", "mean", "max"), "regex")

It's the regex I'm struggling with.  Following the answer in the question referenced above I've tried:
"_min|_mean|_max" --> idea being to capture the 3 different groups

The error I get looks like:
 Error in names(l) <- into :
     'names' attribute [3] must be the same length as the vector [0]

What I think this error is saying is the the regular expression isn't "finding" 3 groups to sort into the c("min","mean","max") I passed it.
What regular expression would get this working? Or is there another better method?

A: All you need is
df %>% gather(var, val, -Scenario) %>%
    separate(var, into = c('var', 'stat'), sep = '_') %>%
    spread(stat, val)
#   Scenario var max mean  min
# 1     base   x 2.0 0.00 -3.0
# 2     base   y 5.0 1.00 -1.5
# 3     base   z 2.0 0.25  0.0
# 4  extreme   x 3.0 1.00 -2.5
# 5  extreme   y 3.5 3.00 -3.0
# 6  extreme   z 7.0 5.00  3.0
# 7   stress   x 1.0 0.25 -2.0
# 8   stress   y 3.0 2.00 -2.0
# 9   stress   z 4.0 2.00  1.0

Since your initial column names are nicely formatted with underscores separating the variable and the statistic, separate is all you need to split them into two columns. spread will rearrange from long to wide.

A: This can be done easily with melt from data.table as it can take multiple patterns in the measure
library(data.table)
nm1 <- unique(substr(names(df)[-1], 1, 1))
melt(setDT(df), measure = patterns("min$", "mean$", "max$"),
       value.name= c("min", "mean", "max"))[, variable := nm1[variable]][]
#   Scenario variable  min mean max
#1:     base        x -3.0 0.00 2.0
#2:   stress        x -2.0 0.25 1.0
#3:  extreme        x -2.5 1.00 3.0
#4:     base        y -1.5 1.00 5.0
#5:   stress        y -2.0 2.00 3.0
#6:  extreme        y -3.0 3.00 3.5
#7:     base        z  0.0 0.25 2.0
#8:   stress        z  1.0 2.00 4.0
#9:  extreme        z  3.0 5.00 7.0


text:
Q: Vue.js convert svg $ref element to dataURL In vue.js I am trying to convert an svg element to a dataURL using the npm package svg-to-dataurl
I am using $refs to get the element,
<svg ref="referenceSVG" version="1.1" xmlns="http://www.w3.org/2000/svg">
                        <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
                </svg>

I click a button which calls a method which gets the referenced element.
refSVG(){
        this.svgStr = this.$refs.referenceSVG
        ......
    }

Next I log this variable, which is of type string,
console.log(this.svgStr);//is an object

If I pass this.svgStr to the function svgToDataUrl(this.svgStr) the dataURL is not created correctly and gives,

If on the other hand, I directly pass in the element as a string like this,
this.dataUrl = svgToDataURL('<svg ref="referenceSVG" version="1.1" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>')

This gives a dataURL which can be used,
data:image/svg+xml,%3Csvg%20ref%3D%22referenceSVG%22%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2240%22%20stroke%3D%22black%22%20stroke-width%3D%223%22%20fill%3D%22red%22%20%2F%3E%3C%2Fsvg%3E

So it seems that the origin svgStr needs to be converted to a string. To do this I used,
this.toString = this.svgStr.toString()

and logged it, which gives,
[object SVGSVGElement]

Which is not the full element I'd expect and so no use in the svgToDataUrl().
How can I get the element into the svgToDataUrl() function for conversion to a dataURL?
Also I am not sure if I should be talking about a dataUri or dataUrl?
Any help would be greatly appreciated.
Thanks,

A: Your variable is not of type string but of type Object. Therefore if you call toString() on it it'll return the string representation of that object not the SVG content you're looking for.
You can access the HTML representation of a ref node though simply through its outerHTML property:
this.svgStr = this.$refs.referenceSVG.outerHTML


text:
Q: What are the triggers for Goku to become a Super Saiyan in the Parallel Quest 'Legendary Super Saiyan' In PQ 15 'Legendary Super Saiyan', I cannot get Goku to transform in Super Saiyan, even though I beat Krilin.
What are the conditions for this to happen ?

A: Provided that all other conditions are met (i.e. you defeated Krillin before Goku), there is a random chance (I don't know the exact figure but experience suggests it's somewhere around 25%) that Goku will transform. Even if you do get lucky and he transforms, Stage 1 Frieza is an absolute Super Kamehameha magnet and will get thoroughly owned if you don't keep SSJ Goku busy.
Add to that the random factor of the item drops, and you could be grinding for a fair while for the Super Saiyan skill (it might be faster to finish the Android Saga so you can just buy it from the skill shop).

A: I tried a killion times then I started defeating them in order, piccollo,  vegeta, then gohan and of course krillin before goku and he transformed 3X in a row.


text:
Q: How to write loop over complex expressions I am trying to make a script that loops over
grep "^\s*w" /proc/net/wireless | awk '{ print int($3 * 100 / 70) "%" }'
and checks each output case in order to print a proper wifi signal icon like this
for x in grep "^\s*w" /proc/net/wireless | awk '{ print int($3 * 100 / 70) "%" }';
        do
        case "$(cat $x)" in
                100|9[0-9])     echo "" ;;
                8[0-9]|7[0-9])  echo "" ;;
                6[0-9]|5[0-9])  echo "" ;;
                4[0-9]|3[0-9])  echo "" ;;
                *)              echo "" ;;
        esac
        done

but bash returns an error near '|' expression


text:
Q: Why does Lua use a garbage collector instead of reference counting? I've heard and experienced it myself: Lua's garbage collector can cause serious FPS drops in games as their scripted part grows.
This is as I found out related to the garbage collector, where for example every Vector() userdata object created temporarily lies around until getting garbage collected.
I know that Python uses reference counting, and that is why it doesn't need any huge, performance eating steps like Luas GC has to do.

*

*Why doesn't Lua use reference counting to get rid of garbage?

A: Reference Counting alone is not enough for a garbage collector to work correctly because it does not detect cycles. Even Python does not use reference counting alone.
Imagine that objects A and B each hold a reference to each other. Even once you, the programmer no longer hold a reference to either object, reference counting will still say that objects A and B have references pointing to them.
There are many different garbage collecting schemes out there and some will work better in some circumstances and some will work better in other circumstances. It is up to the language designers to try and choose a garbage collector that they think will work best for their language.

A: What version of Lua is being used in the games you are basing this claim on? When World of Warcraft switched from Lua 5.0 to 5.1, all the performance issues caused by garbage collection were severely diminished.
With Lua 5.0's garbage collection, the amount of time spent collecting garbage (and blocking anything else from happening at the same time) was proportional to the amount of memory currently in use, leading to lots of effort to minimize the memory usage of WoW addons.
With Lua 5.1's garbage collection, the collector changed to being incremental so it doesn't lock up the game while collecting garbage like it previously did. Now garbage collection has a very minimal impact on performance compared to the larger issue of horribly inefficient code in the majority of user created addons.

A: In general, reference counting isn't an exact substitute for garbage collection because of the potential of circular references. You might want to read this page on why garbage collection is preferred to reference counting.

A: You might also be interested in the Lua Gem about optimization which also has a part that handles garbage collection.

A: Take a look at some of the CPython sources. A good portion of the C code is Py_DECREF and Py_INCREF. That nasty, tedious and error-prone book keeping just goes away in Lua.
If required, there's nothing to stop you writing Lua modules in C that manage any heavy, private allocations manually.

A: Because reference counting garbage collectors can easily leak objects.
Trivial example: a doubly-linked list. Each node has a pointer to the next node - and is itself pointed to by the next one. If you just un-reference the list itself and expect it to be collected, you just leaked the entire list - none of the nodes have a reference count of zero, and hence they'll all keep each other alive. With a reference counting garbage collector, any time you have a cyclic object, you basically need to treat that as an unmanaged object and explicitly dispose of it yourself when you're finished.
Note that Python uses a proper garbage collector in addition to reference counting.

A: While others have explained why you need a garbage collector, keep in mind that you can configure the garbage collection cycles in Lua to either be smaller, less frequent, or on demand.  If you have a lot of memory allocated and are busy drawing frames, then make the thresholds very large to avoid a collection cycle until there is a break in the game.
Lua 5.1 Manual on garbage collection

A: It's a tradeoff.  People have explained some reasons some languages (this really has nothing to do with Lua) use collectors, but haven't touched on the drawbacks.
Some languages, notably ObjC, use reference counting exclusively.  The huge advantage of this is that deallocation is deterministic--as soon as you let go of the last reference, it's guaranteed that the object will be freed immediately.  This is critical when you have memory constraints.  With Lua's allocator, if memory constraints require predictable deallocation, you have to add methods to force the underlying storage to be freed immediately, which defeats the point of having garbage collection.
"WuHoUnited" is wrong in saying you can't do this--it works extremely well with ObjC on iOS, and with shared_ptr in C++.  You just have to understand the environment you're in, to avoid cycles or break them when necessary.


text:
Q: jquery masterpage custom function Jquery custom function on masterpage not working
I have a custom function like as follows :
(function ($) {
    $.fn.scrollingCarousel = function (options, i) {
         ...something something
    };

    jQuery.fn.scrollingCarousel.defaults = {
        autoScroll: false,
        autoScrollDirection: 'left',
        autoScrollSpeed: 10000,
        looped: false,
        scrollerAlignment: 'horizontal',
        scrollerOffset: 0,
        scrollSpeed: 'fast',
        beforeCreateFunction: null,
        afterCreateFunction: null
    };
})(jQuery);

i am using it in a page which has a masterpage.
i am using it in a page as follows.
<script type="text/javascript">
    $(document).ready(function () {
        $(this).('#carousel-demo1').scrollingCarousel();
    });
</script>

i get an error as scrollingCarousel is not recognized.
If i dont use the masterpage the code works fine.

A: As mentioned , the way you are calling your function is not correct
example usage:
$(document).ready(function(){
var a  =   $("#carousel-demo1").scrollingCarousel();
});

(function ($) {
    $.fn.scrollingCarousel = function (options, i) {
         alert('something')
    };

    jQuery.fn.scrollingCarousel.defaults = {
        autoScroll: false,
        autoScrollDirection: 'left',
        autoScrollSpeed: 10000,
        looped: false,
        scrollerAlignment: 'horizontal',
        scrollerOffset: 0,
        scrollSpeed: 'fast',
        beforeCreateFunction: null,
        afterCreateFunction: null
    };
})(jQuery);


text:
Q: How to load an external properties file from a maven java project I have a maven java project, with a properties file in the src/main/resources directory. I've packaged the jar without the properties file in the jar, so it can be deployed to different environments with different settings, but the unit tests are failing
The project structure is
Properties Application Project
|-- pom.xml
`-- src
    |-- main
        |-- java
        |   `-- java classes
        |-- resources
        |   `-- myProps.properties
`-- target
    |--properties-app.jar
       myProps.properties

The values are loaded in this file
public class MyProperties {

    private Properties myProperties;

    public MyProperties() {

        File file = new File("./myProps.properties");
        try {

            myProperties = new Properties();
            FileInputStream myPropertiesInputStream = new FileInputStream(file);
            myProperties.load(myPropertiesInputStream);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    public Properties getPropertyValue() {
        return myProperties.getProperty("value");
    }

}

The unit test is as follows
import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

public class MyPropertiesTest {

    private MyProperties myProperties;

    @Before
    public void setup() {

        myProperties = new MyProperties();

    }

    @Test
    public void testMyProperties() {

        assertNotNull(myProperties.getPropertyValue());

    }

}

What should I use to load the properties file from the target directory so I can build it successfully from the command line?

A: I hope you are using maven jar plugin. If so use this configuration inside jar-plugin
    <configuration>
      <archive>
        <manifestEntries>
          <Class-Path>.</Class-Path>
        </manifestEntries>
      </archive>
    </configuration>

Then the jar will take the properties file from root directory of jar file.

A: Solved it with both suggestions, plus a few changes to the pom.
Thank you both.
In the pom, the properties file from the resource directory is copied to the target directory, and is excluded from the jar file created by the pom
<?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test</groupId>
    <artifactId>properties</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>properties</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
                <configuration>
                    <reuseForks>false</reuseForks>
                    <forkCount>1</forkCount>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.7</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>install</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/target</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/resources</directory>
                                    <includes>
                                        <include>**/*.properties</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <excludes>
                        <exclude>**/*.properties</exclude>
                    </excludes>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>com.properties.MyProperties</mainClass>
                        </manifest>
                        <manifestEntries>
                            <Class-Path>.</Class-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

In MyProperties, the file is loaded using the getClass().getResourceAsStream() method
myProperties.load(getClass().getResourceAsStream("/myProps.properties"));

All tests pass now, and the jar file runs from the command line and loads the properties file.
I've uploaded the resulting project to github here: https://github.com/tetsujin1979/ExternalProperties


text:
Q: Failed to fetch ... Hash Sum mismatch. tried rm apt/list but didn't work as you saw on the title, I got the "Failed to fetch... Hash Sum mismatch" Error. I have tried this method:
sudo rm -rf /var/lib/apt/lists/*
sudo apt-get update

But it didn't work. I still got the same error.
Err http ://vn.archive.ubuntu.com trusty-updates/universe amd64 Packages
Get:99 http ://vn.archive.ubuntu.com trusty-updates/universe amd64 Packages [1,789 B]
Get:100 http ://vn.archive.ubuntu.com trusty-updates/main i386 Packages [1,789 B]
Fetched 28.3 MB in 5min 15s (89.8 kB/s)
W: Failed to fetch http://vn.archive.ubuntu.com/ubuntu/dists/trusty/main/source/Sources  Hash Sum mismatch
W: Failed to fetch http://vn.archive.ubuntu.com/ubuntu/dists/trusty-updates/universe/source/Sources  Hash Sum mismatch
W: Failed to fetch http://vn.archive.ubuntu.com/ubuntu/dists/trusty-updates/universe/binary-amd64/Packages  Hash Sum mismatch
W: Failed to fetch http://vn.archive.ubuntu.com/ubuntu/dists/trusty-updates/main/binary-i386/Packages  Hash Sum mismatch
W: Failed to fetch http://vn.archive.ubuntu.com/ubuntu/dists/trusty-updates/universe/binary-i386/Packages  Hash Sum mismatch
W: Failed to fetch http://vn.archive.ubuntu.com/ubuntu/dists/trusty-updates/main/i18n/Translation-en  Hash Sum mismatch
W: Failed to fetch http://vn.archive.ubuntu.com/ubuntu/dists/trusty-updates/universe/i18n/Translation-en  Hash Sum mismatch
E: Some index files failed to download. They have been ignored, or old ones used instead.

Please help! Thank you a lot!

A: If deleting /var/lib/apt/lists/* does not work...
(esp. if you're behind a proxy), fix "Hash Sum Mismatch" like this:
Create file
/etc/apt/apt.conf.d/99fixbadproxy
with this content
Acquire::http::Pipeline-Depth 0;
Acquire::http::No-Cache true;
Acquire::BrokenProxy    true;

See also here

A: I used to get the same issue with jp.archive.ubuntu.com, usually it disappeared after a couple hours, so my guess is that it has something to do with your mirror's synchronisation with the master mirrors (i.e., you are fetching the package list while it is being synchronised). Switching to another mirror made such occurrences much less frequent for me (although they still do happen every now and then), so you may want to try that. (Here is the list of archive mirrors.)


text:
Q: htaccess rule to make index.php be served instead of index.html when go to http://localhost Could someone provide an .htaccess rule such that my index.php overrides my index.html?
Meaning that index.php, and not index.html, is served when I go to http://localhost.

A: That will do the job:
DirectoryIndex index.php index.html

In case there is no index.php the index.html file will be served instead.

A: This may work instead...
RewriteEngine On
RewriteBase /
RewriteRule ^index.html$ index.php [R=301,L]

A: In the apache configuration file (or .htaccess), set DirectoryIndex to index.php, instead of index.html
Here is an example:
http://www.javascriptkit.com/howto/htaccess6.shtml


text:
Q: Error while counting number of character,lines and words in java i have written the following code to count the number of character excluding white spaces,count number of words,count number of lines.But my code is not showing proper output.
import java.io.*;

 class FileCount
{

public static void main(String args[]) throws Exception
{
    FileInputStream file=new FileInputStream("sample.txt");
    BufferedReader br=new BufferedReader(new InputStreamReader(file));
    int i;
    int countw=0,countl=0,countc=0;
    do
    {
        i=br.read();
        if((char)i==(' '))
            countw++;
        else if((char)i==('\n'))
            countl++;
        else
            countc++;

    }while(i!=-1);
    System.out.println("Number of words:"+countw);
    System.out.println("Number of lines:"+countl);
    System.out.println("Number of characters:"+countc);
}
}

my file sample.txt has
hi my name is john
hey whts up

and my out put is
Number of words:6
Number of lines:2
Number of characters:26

A: You need to discard other whitespace characters as well including repeats, if any. A split around \\s+ gives you words separated by not only all whitespace characters but also any appearance of those characters in succession.
Having got a list of all words in the line it gets easier to update the count of words and characters using length methods of array and String.
Something like this will give you the result:
String line = null;
String[] words = null;
while ((line = br.readLine()) != null) {
    countl++;
    words = line.split("\\s+");
    countw += words.length;
    for (String word : words) {
        countc += word.length();
    }
}

A: A new line means also that the words ends.
=> There is not always a ' ' after each word.
  do
  {
  i=br.read();
    if((char)i==(' '))
        countw++;
    else if((char)i==('\n')){
        countl++;
        countw++;  // new line means also end of word
    }
    else
        countc++;
}while(i!=-1);

End of file should also increase the number of words (if no ' ' of '\n' was the last character.
Also handling of more than one space between words is still not handled correctly.
=> You should think about more changes in your approach to handle this.

A: import java.io.*;

class FileCount {

    public static void main(String args[]) throws Exception {
        FileInputStream file = new FileInputStream("sample.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(file));
        int i;
        int countw = 0, countl = 0, countc = 0;
        do {
            i = br.read();
            if ((char) i == (' ')) { // You should also check for other delimiters, such as tabs, etc.
                countw++;
            }
            if ((char) i == ('\n')) { // This is for linux Windows should be different
                countw++; // Newlines also delimit words
                countl++;
            }  // Removed else. Newlines and spaces are also characters
            if (i != -1) {
                countc++; // Don't count EOF as character
            }

        } while (i != -1);

        System.out.println("Number of words " + countw);
        System.out.println("Number of lines " + countl); // Print lines instead of words
        System.out.println("Number of characters " + countc);
    }
}

Ouput:
Number of words 8
Number of lines 2
Number of characters 31

Validation
$ wc sample.txt
2  8 31 sample.txt

A: Try this:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileCount {
    /**
     *
     * @param filename
     * @return three-dimensional int array. Index 0 is number of lines
     * index 1 is number of words, index 2 is number of characters
     * (excluding newlines)
     */
    public static int[] getStats(String filename) throws IOException {
        FileInputStream file = new FileInputStream(filename);
        BufferedReader br = new BufferedReader(new InputStreamReader(file));

        int[] stats = new int[3];
        String line;
        while ((line = br.readLine()) != null) {
            stats[0]++;
            stats[1] += line.split(" ").length;
            stats[2] += line.length();
        }

        return stats;
    }

    public static void main(String[] args) {
        int[] stats = new int[3];
        try {
            stats = getStats("sample.txt");
        } catch (IOException e) {
            System.err.println(e.toString());
        }
        System.out.println("Number of words:" + stats[1]);
        System.out.println("Number of lines:" + stats[0]);
        System.out.println("Number of characters:" + stats[2]);
    }

}


text:
Q: Updating some fields that occurs in multiple table at once in Laravel I have two tables employee and wage:
The employee table consists columns: idEmployeeGlobal, email, position, idEmployeeWorkingLocation.
The table wage consists columns: idWage, wage, idEmployeeGlobal, idEmployeeWorkingLocation.
In this situation, I can't change the database. It always error occurred when updating those two tables. The error is
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Here is my code to update:
// Employee Section
$employee = Employee::find($id);
$employee->idEmployeeWorkingLocation = $request->idEmployeeWorkingLocation;
$employee->email = $request->email;
$employee->position = $request->position;
$employee->save();

// Wage Section
$wage = Wage::where('idEmployeeGlobal', $id)->first();
$wage->idEmployeeLocation = $request->idEmployeeLocation;
$wage->save();

No matter whether the position of Wage Section or the Employee section in code above, I always ended up in error.
I also can't get the full error because my working place prohibits telling any company resources outside.
Case Example:
This is John Doe, He works in New York (15) then he gets moved to London (51). There is changes in the field idEmployeeWorkingLocation, position, and wage that is needed to be inputted by admin.
Before update
// Employee Table
idEmployeeGlobal |        email        | position | idEmployeeWorkingLocation
-----------------------------------------------------------------------------
         1       | johndoe@example.com | Manager  | 15

// Wage Table
idWage |  wage  | idEmployeeGlobal (FK) | idEmployeeWorkingLocation (FK)
------------------------------------------------------------------------
   1   |  $50   | 1                     | 15

Desired result after change:
Before update
// Employee Table
idEmployeeGlobal |        email        | position   | idEmployeeWorkingLocation
-----------------------------------------------------------------------------
         1       | johndoe@example.com | Head of HR | 51

// Wage Table
idWage |  wage  | idEmployeeGlobal (FK) | idEmployeeWorkingLocation (FK)
------------------------------------------------------------------------
   1   |  $55   | 1                     | 51

A: Can you share your table structure for employee and wage tables? The main issue is there is some primary key in one table which references the foreign key in the child table. Most probably that is idEmployeeLocation. But need table structure to verify that.

A: I think you do not have record for this idEmployeeGlobal in your wages table. Make sure the record is created.
Also share your migration files for the wages and employees table.

Use cases to debug
To check if you are getting wage
$wage = Wage::where('idEmployeeGlobal', $id)->first();
dd($wage)

To check if you are getting input from form
dd($request->idEmployeeLocation);


text:
Q: Why IntelliJ doesn't run my script if it has main in it I am observing an interesting behavior. I have an existing project in which I created a folder and created a Scala script in that folder. To run it I did

*

*Write a Scala script, e.g. MyScript.scala

*In the menu select: Run ->    Edit Configurations... Press the "+" (⌘N also works on the Mac in    this dialog) Select "Scala Script" Then select your Script file in    this dialog

Interestingly, if the script is the following then I get error Scala script not found
object HelloWorld{

  def main(args:Array[String]): Unit ={
    println("hello world");
  }
}

but if the script is
def greetings(): Unit ={
  println("hello")
}

greetings();

then it works!
Why IntelliJ cannot run the 1st version of the script?

A: You could do the following:
Run it as a script.
You have to use the following code:
class HelloWorld {
  def main(args:Array[String]): Unit ={
    println("hello world");
  }
}
object Foo extends HelloWorld
Foo.main(args)

Hint: I removed the 'build' action from 'Before launch' to show the warnings further down.
Run it as an Application.
You can keep your code. Just select 'Application' when creating the configuration.
object HelloWorld{

  def main(args:Array[String]): Unit ={
    println("hello world");
  }
}

Why?
You have to provide an entry point for the script. So you could use the following code:
object HelloWorld {
  def main(args:Array[String]): Unit ={
    println("hello world");
  }
}
HelloWorld.main(args) //without this line, Script is not found!

But this gives an error (expected class or object definition):

An If you try to extend from App trait, you get 2 warnings:
object HelloWorld extends App {
  override def main(args:Array[String]): Unit ={
    println("hello world");
  }
}
HelloWorld.main(args)

So I guess its best to use one of two Solutions above.


text:
Q: How does require 'digest/md5' works? require 'digest/md5'       # => true
Digest::Md5.hexdigest('')  # => "d41d8cd98f00b204e9800998ecf8427e"

Which file does this require use? Is an actual file being required? Or is it required programmatically?

A: This is (sorta) explained in the documentation for Kernel#require:

require(name) → true or false
Loads the given name, returning true if successful and false if
  the feature is already loaded.
If the filename does not resolve to an absolute path, it will be
  searched for in the directories listed in $LOAD_PATH ($:).
If the filename has the extension ".rb", it is loaded as a source file; if
  the extension is ".so", ".o", or ".dll", or the default shared library
  extension on the current platform, Ruby loads the shared library as a Ruby
  extension.  Otherwise, Ruby tries adding ".rb", ".so", and so on to the
  name until found.  If the file named cannot be found, a LoadError will be raised.

By default $LOAD_PATH will include the directories where Ruby's standard library lives. Directories, plural, because native (compiled binary) modules in the standard library live in a different directory than pure-Ruby modules.
Digest is actually a great example because some of its files are native and others are Ruby.
On my Mac $LOAD_PATH includes (among others) these two directories (truncated for readability):

*

*.../usr/lib/ruby/2.0.0

*.../usr/lib/ruby/2.0.0/universal-darwin15
The former is where pure-Ruby modules live and the latter is where native modules live.
So when I do require 'digest/md5' Ruby first looks in .../usr/lib/ruby/2.0.0/ for a directory named digest/, and upon finding it, for a file in it named md5.rb. It doesn't find it, so it looks for md5.bundle. Why .bundle and not .so or .o? Because that's the "default shared library extension" that Ruby was configured with when it was compiled for OS X. Go figure.
Ruby doesn't find it there, so next it looks in .../usr/lib/ruby/2.0.0/universal-darwin15/digest/. There's no md5.rb there, but there is an md5.bundle, so Ruby loads it.

A: It loads a C-extension that can be found in Ruby's source dir - ruby/ext/digest/md5/

A: It's one of Ruby's standard libraries (stdlib), which means that it's available in pretty much every implementation of Ruby. It does, in fact, load a file. But it's a file that was copied to your computer when you installed Ruby and is pretty much always going to be available to you. Another good example of a standard library is DateTime.
One thing that confused me a lot when I started learning Ruby and Rails was that Rails requires a fair number of Ruby's standard libraries for you. So it's good to be aware of what's actually going on under the hood.


text:
Q: HTML5 validation I wonder if HTML5 have any formvalidation for dual entry (write 2 identical password) and can you write own exceptions?
Thanx in advance!

A: If you want something a bit nicer and HTML5-utilising, try this:
http://www.html5rocks.com/en/tutorials/forms/html5forms/
Password:
<input type="password" id="password" name="password">
Confirm Password:
<input type="password" id="passwordconf" name="passwordconf" oninput="check(this)">

Make it fancy by adding this to your CSS (below).  It puts a red border around the offending input fields when they fail HTML5 validation.
:invalid {
     border: 2px solid #ff0000;
}

All done.  You should still use an alert() or server-side validation to ensure that the user inputs both passwords correctly.  Don't rely on client-side anything.

A: I had a similar problem, and to solve it using the HTML5 api I did this: setted a pattern for the password to contain at least eight letters and a number. Then to make them matching I did:
    var password = document.querySelector('#password'),
        passwordConfirm = document.querySelector('#password_confirm');

    [].forEach.call([password, passwordConfirm], function(el) {
        el.addEventListener('input', function() {
            if (!el.validity.patternMismatch) {
                if ( password.value === passwordConfirm.value ) {
                    try{password.setCustomValidity('')}catch(e){}
                } else {
                    password.setCustomValidity("Password and password confirm doesn\'t match")
                }
            }
        }, false)
    });

where with el.validity.patternMismatch check for the pattern validity first and then check for the validity of the two.
Here is my password input with the pattern.
<input type="password" pattern="^((?=.*(\d|\W))(?=.*[a-zA-Z]).{8,})$" id="password" />

A: I'm quite sure that's not possible. Also, it can be easily covered by javascript so why not use that instead?
This works perfectly well:

<form action="filename.ext" name="pwForm" method="GET/POST">
    <input type="password" name="pw1" value="">

    <input type="password" name="pw2" value="">

    <input type="Submit" name="CheckPassword" value="Check Passwords" onClick="return checkPassword();">
</form>

A: Thanks Kicker, that was really useful.
I extended it a little to make the password and password confirm inputs to be invalid as soon as typing in the input started.
var password = document.querySelector(' input[name=usr_password]');
var passwordConfirm = document.querySelector(' input[name=usr_password_confirm]');
if (password && passwordConfirm)
{
    [].forEach.call([password, passwordConfirm], function(el) {
        el.addEventListener('input', function() {
            if ( el.validity.patternMismatch === false) {
                if ( password.value === passwordConfirm.value ) {
                    try{
                        password.setCustomValidity('');
                        passwordConfirm.setCustomValidity('');

                    }
                    catch(e){}
                }
                else {
                    password.setCustomValidity("The two passwords do not match");
                }
            }
            if ((password.checkValidity() && passwordConfirm.checkValidity()) === false)
            {
                password.setCustomValidity("The two passwords do not match, and they don't comply with the password rules.");
                passwordConfirm.setCustomValidity("The two passwords do not match, and they don't comply with the password rules.");
            }
            else
            {
                password.setCustomValidity('');
                passwordConfirm.setCustomValidity('');

            }
        }, false)
    });
}

A: I think this is what you are looking for.

Password: <input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" name="pwd1" onchange="
  this.setCustomValidity(this.validity.patternMismatch ? 'Password must contain at least 6 characters, including UPPER/lowercase and numbers' : '');
  if(this.checkValidity()) form.pwd2.pattern = this.value;
">

Confirm Password: <input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" name="pwd2" onchange="
  this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');
">

This will do the password and retype password fields validation.

A: Another option is to use http://jqueryvalidation.org/validate/, if you don't mind using Jquery to do your dirty work.
Check out http://jqueryvalidation.org/equalTo-method
<form id="myform">
  Password
  <input id="password" name="password" />

  Again
  <input class="left" id="password_again" name="password_again" />

  <input type="submit" value="Validate!">
</form>

You can also write more complicated methods if required: http://jqueryvalidation.org/category/plugin/


text:
Q: How do i unit test the same route multiple times using Apache Camel I am using CamelTestSupport and currently have 2 unit test for 1 routes.
Both unit test is to test if exception is thrown, I used AdviceWith to replace and throw Exception.
The issue arises as written in the documentation it is recommended to only Advice the route once as it will cause the 2nd unit test to not match the route.
What can i do to reset the route after each unit test?


text:
Q: Xamarin iOS - Issue referencing a UIView from a custom UITableViewCell class I would like to create a simple animation when a view is tapped within a cell.When this view is tapped, I would like to change it's color to blue, and slide it to the right of screen.
I have two challenges:

*

*How do I reference the exact view that was tapped?

Currently, more than one view is changed to blue, not even the one that was tapped, when I expect just the tapped view to change.

*The view does not slide/hide.This is an information overlay. I'd like to hide it by sliding it to the right if it's drawn out(in order to hide the information) and then slide it back to the left to display the info when the user taps on it again. Basically an open/close animation.

Any help would be greatly appreciated.
  public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
    {
        cell = tableView.DequeueReusableCell (CustomCell.Key) as CustomCell;

        if (cell == null) {

            cell = new CustomCell ();

        }

        try
        {
            cell.cellImageView.Image = TableItems[indexPath.Row];

            tapOnOverlay = new UITapGestureRecognizer(HideTheOverlay);
            cell.overlay.UserInteractionEnabled = true;
            cell.overlay.AddGestureRecognizer(tapOnOverlay);

    }
        catch (Exception imageException)
        {
            Console.Write(imageException.Message);
        }

        return cell;
    }

 public void HideTheOverlay()
    {
        try{

            UIView.Animate(2.0,()=> {

// How do I get a reference to the exact view that was tapped on here??

cell.overlay.Layer.BackgroundColor = UIColor.Blue.CGColor;

// This does not move the view. Nothing happens here

cell.overlay.Layer.Frame = new RectangleF(
                        new PointF((float)cell.overlay.Layer.Frame.Location.X + 200,
                            (float)cell.overlay.Layer.Frame.Location.Y),
                        (SizeF)cell.overlay.Frame.Size);

            });

        }catch(Exception ex)
        {
            Console.Write(ex.Message + ex.StackTrace);

        }

A: I found a solution to my problem above.
I passed the UITapGestureRecognizer as a parameter in my HideOverlay function and thus to get the selected/tapped view, I accessed it by calling the View property from the gesture recognizer. From there, I could animate the view according by accessing the view's Layer.
Below is the full implementation of my open/close animation
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
    {
        CustomCell cell = tableView.DequeueReusableCell (CustomCell.Key) as CustomeCell;

        if (cell == null) {

            cell = new CustomCell ();

        }
            tapOnOverlay = new UITapGestureRecognizer(HideTheOverlay);
            cell.overlay.AddGestureRecognizer(tapOnOverlay);
            cell.overlay.UserInteractionEnabled = true;

       catch (Exception imageException)
        {
            Console.Write(imageException.Message);
        }

        return cell;
    }

The HideOverlay function
     public void HideTheOverlay(UITapGestureRecognizer tap)
    {
        try{

            UIView.Animate(1.5,()=> {

                float offsetXClose = (float)UIScreen.MainScreen.Bounds.Width - ((float)tap.View.Layer.Frame.Location.X + 20);

                float offsetXOpen = (float)UIScreen.MainScreen.Bounds.Width - ((float)tap.View.Layer.Frame.Width);

                float currentXPosition = (float)tap.View.Layer.Frame.Location.X;

                float finalXPosition = currentXPosition + offsetXClose;

                if(currentXPosition == finalXPosition) //Means the overlay is already closed. We should open it
                {

                    //Open the overlay by moving it to the left
                    tap.View.Layer.Frame = new RectangleF(
                        new PointF((float)tap.View.Layer.Frame.Location.X - offsetXOpen,
                            (float)tap.View.Layer.Frame.Location.Y),
                        (SizeF)tap.View.Frame.Size);

                }else{

                    //Close the overlay, by moving it to the right
                    tap.View.Layer.Frame = new RectangleF(
                        new PointF((float)tap.View.Layer.Frame.Location.X + offsetXClose,
                            (float)tap.View.Layer.Frame.Location.Y),
                        (SizeF)tap.View.Frame.Size);
                }

            });

        }catch(Exception ex)
        {
            Console.Write(ex.Message + ex.StackTrace);

        }

    }


text:
Q: Set Data table to contain nodes of xml like data member of data grid VB.net I have an XML document that looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CoreNLP-to-HTML.xsl" type="text/xsl"?>
<root>
  <document>
    <sentences>
      <sentence id="1">
        <tokens>
           <token id="7">
            <word>founded</word>
            <lemma>found</lemma>
            <CharacterOffsetBegin>72</CharacterOffsetBegin>
            <CharacterOffsetEnd>79</CharacterOffsetEnd>
            <POS>VBN</POS>
            <NER>O</NER>
          </token>
          <token id="8">
            <word>in</word>
            <lemma>in</lemma>
            <CharacterOffsetBegin>80</CharacterOffsetBegin>
            <CharacterOffsetEnd>82</CharacterOffsetEnd>
            <POS>IN</POS>
            <NER>O</NER>
          </token>
          <token id="9">
            <word>1891</word>
            <lemma>1891</lemma>
            <CharacterOffsetBegin>83</CharacterOffsetBegin>
            <CharacterOffsetEnd>87</CharacterOffsetEnd>
            <POS>CD</POS>
            <NER>DATE</NER>
            <NormalizedNER>1891</NormalizedNER>
            <Timex tid="t1" type="DATE">1891</Timex>
          </token>
          <token id="10">
            <word>.</word>
            <lemma>.</lemma>
            <CharacterOffsetBegin>87</CharacterOffsetBegin>
            <CharacterOffsetEnd>88</CharacterOffsetEnd>
            <POS>.</POS>
            <NER>O</NER>
          </token>
        </tokens>
      </sentence>
    </sentences>
  </document>
</root>

Now I've placed a Datagrid on my Form1 and added the following code:
Dim ds As DataSet = New DataSet()
ds.ReadXml("input.txt.xml")

With Me.DataGridView1

    .DataSource = ds

    .DataMember = "token"

End With

And it looks great.   I can see all the tokens in my XML populated the rows and columns of the Datagrid.
But I don't want the data in the datagrid.  I just want it in the datatable....
 Dim dt As DataTable = New DataTable()

        dt.ReadXml("input.txt.xml")

Then what command like the   .DataMember = "token"   can I issue or do I need to copy it into a new datatable?
Thanks

A: I did it via a dataview:
Dim myDT As DataTable
Dim myDV As DataView

myDV = ds.Tables(4).DefaultView
myDT = myDV.ToTable

If anyone knows how to go directly or replace the (4) with "token" - because it is the 4th table in the dataset then let me know.


text:
Q: getting an error snapshot.data is not a function Tech stack: React, Firebase, Next.js
My website runs like this; when a user registers, a document (in 'User' collection), a 'vote' subcollection containing 2 documents, is created. And right after that user registers, the website should call 2 functions: getUserInfo() and getUserVotes from useEffect(), which basically read all the documents which was created earlier.
Now. The problem is, when a user first registered, and this getUserVotes is called, there was an error saying threadSnap.data is not a function even though threadSnap is supposed to be document snapshot not querySnapshot (which is why this should work properly). But after refreshing a page, this error just disappears.
const getUserVotes = async (user) => {
    const uid = user.uid;
    if (user) {
      Promise.allSettled([
        getDoc(doc(db, "users", uid, "votes", "threads")),
        getDoc(doc(db, "users", uid, "votes", "replies"))
      ]).then(([threadSnap, replySnap]) => {
        setUserVotes({
          threads: threadSnap.data(),
          replies: replySnap.data()
        })
      })
    }
  }

At first, I tried calling getDoc two times like this
threadSnap = await getDoc(doc(db, "users", uid, "votes", "threads")),
replySnap = await getDoc(doc(db, "users", uid, "votes", "replies"))
setUserVotes({
  threads: threadSnap.data(),
  replies: replySnap.data()
})

But it seems like JS calls setUserVotes evenn before two promises complete. Then, I use Promise.all on two getDoc but then the state both becomes undefined (for some reason). Finally, I land on Promise.allSettled which seems to work normally except when the user registers for the first time that the error threadSnap.data is not a function. I expect my program to wait for two getDoc to resolve before setting my state through setUserVotes. Can you guys help?


text:
Q: On Swift: Met error about parentheses type writing sqrt I wrote the following code:
var number3 = sqrt(9)

and the System reports error saying that

Variable number3 inferred to have type "()", which may be unexpected."

How can this error be?
I found another user saying that (9) refers to (int) type instead of int type. But the sqrt function need an parentheses. How do you guys deal with this problem?

A: There error here is incorrect (and fixed in the latest versions of Swift). The correct error is:
  1> import Darwin
  2> var number3 = sqrt(9)
repl.swift:2:15: error: ambiguous use of 'sqrt'
var number3 = sqrt(9)
              ^
Darwin.sqrt:1:6: note: found this candidate
func sqrt(x: Float) -> Float
     ^
Darwin.sqrt:1:6: note: found this candidate
func sqrt(_: Double) -> Double
     ^

The problem is that Swift doesn't know if you want to convert the literal "3" into a Float or a Double. Rather than force it to do that, just use a Double directly:
  2> sqrt(9.0)
$R0: Double = 3


text:
Q: Cannot use pivot_longer in r with multiple cell value Say that I have a df.
And I want to change it into a long data format.
I found that this question (Long pivot for multiple variables using Pivot long) was similar with mine.
But I got an error when ran the below code. I did not know why.
What I expected should like the df_expected.
library(tidyverse)
df = data.frame(
  dis = 'cvd',
  pollution = 'pm2.5',
  lag_day = '2',
  b1.x = 1,
  b1_ci.x = 2,
  PC.x = 3,
  pc_ci.x = 4,
  b1.y =5,
  b1_ci.y = 6,
  PC.y = 7,
  pc_ci.y = 8
)
# df
# dis pollution lag_day b1.x b1_ci.x PC.x pc_ci.x b1.y b1_ci.y PC.y pc_ci.y
# 1 cvd     pm2.5       2    1       2    3       4    5       6    7       8

df %>%
  pivot_longer(
    cols = -c(dis:lag_day),
    names_to = c('.value', 'from'),
    names_sep = '.'
  ) # error code
# Error: Input must be a vector, not NULL.
# Run `rlang::last_error()` to see where the error occurred.
# In addition: Warning message:
# Expected 2 pieces. Additional pieces discarded in 8 rows [1, 2, 3, 4, 5, # 6, 7, 8].

df_expected = data.frame(
  dis = 'cvd',
  pollution = 'pm2.5',
  lag_day = '2',
  from = c('x', 'y'),
  b1 = c(1,5),
  b1_ci = c(2,6),
  PC = c(3, 7),
  pc_ci = c(4, 8)
)

# df_expected
# dis pollution lag_day from b1 b1_ci PC pc_ci
# 1 cvd     pm2.5       2    x  1     2  3     4
# 2 cvd     pm2.5       2    y  5     6  7     8

A: df %>%
pivot_longer(-c(dis, pollution, lag_day),
           names_to = c('.value', 'from'), names_sep='[.]')

# A tibble: 2 x 8
  dis   pollution lag_day from     b1 b1_ci    PC pc_ci
  <chr> <chr>     <chr>   <chr> <dbl> <dbl> <dbl> <dbl>
1 cvd   pm2.5     2       x         1     2     3     4
2 cvd   pm2.5     2       y         5     6     7     8

in base R:
reshape(df, -(1:3),  direction = 'long')

or even:
reshape(df, -(1:3), idvar = 1:3,  direction = 'long')

              dis pollution lag_day time b1 b1_ci PC pc_ci
cvd.pm2.5.2.x cvd     pm2.5       2    x  1     2  3     4
cvd.pm2.5.2.y cvd     pm2.5       2    y  5     6  7     8


text:
Q: I keep getting the Undefined symbols for architecture x86_64 warning when I go to run my program. I am on a mac and I dont know what the issue is Image of the issue
If theres anyone who can help with the issue it would be very helpful.


text:
Q: Wordpress missing break lines I've got a wired problem here... One of my clients tells me that there is no

 or
 tags in her posts, and i've checked my self... wtf is wrong?
Example on how it should be (visual)

This is how the HTML looks like, with no break lines? :S

What is wrong with this?

A: Check your theme's functions.php file, its possible your missing the wordpress wautop function as seen here: http://codex.wordpress.org/How_WordPress_Processes_Post_Content#wpautop.28.29_WordPress_Function
You can also disable this function and use your own content filtering methods... this blog should help for that: http://blog.bigsmoke.us/2010/12/09/wpautop


text:
Q: Creating a list of headings, sub-headings and sub-subheadings in Excel I am looking to make a list of heading type 1, sub-heading type 2 and sub-sub-heading type 3, and each subsequent instance of a heading increments in excel. e.g.
Outcome 1
Output 1.1
Activity 1.1.1
Activity 1.1.2
Output 1.2
Activity 1.2.1
Activity 1.2.2
Activity 1.2.3
Outcome 2
Output 2.1
Activity 2.1.1
etc

Here is my formula - getting to be a complicated nested IF statement:
IF([@Column1]="","",
IF([@Column1]="Outcome", "Outcome " & COUNTIF(tbOOA[[#Headers],[Column1]]:[@Column1], [@Column1]),
IF([@Column1]="Output","Output "& COUNTIF(tbOOA[[#Headers],[Column1]]:[@Column1],"Outcome") ***&"."&*** COUNTIF(tbOOA[[#Headers],[Column1]]:[@Column1],[@Column1]),
"Activity " & "serious help")))

In Column 1, choose from a list of 'Outcome', 'Output', or 'Activity'.
In column 2, calculate the appropriate number, e.g. Output 1.2
If the row is empty, then nothing. - Fine
If it is "Outcome", count from the header until current row for the number of instances of "Outcome". - Fine
Else if it is "Output", count the number of "Outcome"s there are. - Fine
This is where it falls apart. Trying to calculate the number after the "." (bold and italic)

I need to count the # of instances of "Output", but then this has to reset to 1 each time there is a new 'Outcome'.
The logic I'm trying to follow is:
(# of "Outputs" from the table header until the current row) minus
(# of "Outputs" from the table header until the last instance of "Outcome")

I've tried several attempts at calculating row number, but everything has been problematic.
The logic is the same for activities, though will complicate the formula even more and I haven't bothered to start on that until I can get level 2 sorted.
Does anyone know of a similar problem/solution?

A: If you are open to using hidden helper columns, the formulas become much more manageable.  Use Column A to hold your "Outcome", "Output", and "Activity" data.
Then use column B to deal with Outcome numbers, column C to deal with Output numbers, and column D to deal with Activity numbers.  Merge the final results together in Column E.
In B1, C1, and D1, manually write in the first values (1, 0, and 0).
Then, fill down starting from B2 with the following:
=IF(A2="Outcome",B1+1,B1)

This works by incrementing only if you have found your next Outcome.
Fill down from C2 with the following:
=IF(A2="Outcome",0,IF(A2="Output",C1+1,C1))

This works by incrementing only if you have found your next Output.  It resets to 0 if you have a new Outcome.
Then fill down from D2 with
=IF(OR(A3="Outcome",A3="Output"),0,IF(A3="Activity",D2+1,D2))

It's very similar to the prior formula, but resets on an Outcome or an Output.
Finally, in D4, merge it all together with
=B1&IF(C1>0,"."&C1&IF(D1>0,"."&D1,""),"")

& is a string concatenate operation.  By checking if the inner values are 0, we only concatenate . and the next number if the next number is non-zero.

A: I had a similar problem, where I wanted to create the multi-level heading numbers based on the indentation of list of texts. So the numbers must be generated automatically with a user-defined formula (UDF) like below:

For this to work, you must type ="1" in cell A2. The same formula in A3 (below) must be copied down to A4:A14.

=NextLevelNum(A2;IndentLevel(B3))

Function IndentLevel I took from https://professor-excel.com/how-to-return-the-indentation-of-a-cell-in-excel/
Function NextLevelNum I did myself. All code below.
Option Explicit

Public Function IndentLevel(Ref As Range) As Long
  Application.Volatile
  IndentLevel = Ref.IndentLevel
End Function

Public Function NextLevelNum(prevNumRef As Range, level As Integer) As String
  Dim prevNum As String
  Dim nums() As String
  Dim prevLevel As Integer

  prevNum = prevNumRef.Value
  nums = Split(prevNum, ".")
  prevLevel = UBound(nums) + 1

  ' Ensure  1 <= level <= prevLevel +1
  level = WorksheetFunction.Max(level, 1)
  level = WorksheetFunction.Min(level, prevLevel + 1)

  ReDim Preserve nums(0 To level - 1)

  If level = prevLevel + 1 Then
    nums(level - 1) = "1"
  Else
    nums(level - 1) = CStr(CInt(nums(level - 1)) + 1)
  End If

  NextLevelNum = Join(nums, ".")
End Function


text:
Q: Where can I buy an Ubuntu Phone? I need to buy an Ubuntu phone, where can I buy it? It is unavailable everywhere.

A: You cannot buy a new retail phone with Ubuntu from anywhere, now. A few months ago, Canonical announced that it is ending development of Unity, and the phone projects.
You may be able to find a used phone on eBay or similar sites, or you may buy certain models of phone, and flash an image from ubports onto the device. Even if you buy an original Ubuntu phone, you will likely need to flash over to a ubports image, to get updates and use an app store.


text:
Q: How to grant persistable uri permission to a Uri received from Intent.ACTION_GET_CONTENT? On my app I have a function to attach files and contacts and other things.
I use an Intent to pick multiple files from a picker.
When I use Intent.ACTION_GET_CONTENT... I can pick files from many places like Google Photos, or Music Apps, or Contacts. But the permission to the result Uri expires when I live the activity...
When I use Intent.ACTION_OPEN_DOCUMENT... I don´t have any problem with permissions ussing takePersistableUriPermission but I lose to pick files from Google Photos, Music Apps, and Contacts...
So is there a way to grant persistable uri permission to a Uri received from Intent.ACTION_GET_CONTENT or that is exclusive to Intent.ACTION_OPEN_DOCUMENT?


text:
Q: Select dependientes - Angular 9 Estimados necesitó filtrar, selects dependientes en Angular 9, tengo este código me devuelve una descripción (description) y un código (code) nesecito enviar el código al otro select, para obtener la description o nombre de provincia, el tema es que es un solo endpoint.
 No se como pasar el código al otro select,
Me envían un enpoint único que por el code obtengo el otro valor es hacer un select en cascada,
Dejo lo que tengo. espero me puedan ayudar no se si me explique bien pero es lo que tengo.
en el método onSelect() en consola obtengo el código correcto, pero no se como enviárselo al otro select para que obtenga el nombre correspondiente espero este explicando bien.

/* Servicio Inicio*/
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { environment } from 'src/environments/environment.dev';
import { IUbigeo } from '@aafp/commons/interfaces';
import { Department, Province } from '../interfaces/ubigeo.interface';

@Injectable({
  providedIn: 'root'
})
export class Ubigeo {

  public departamentos: Department[] = [];
  public provincias: Province[] = [];
  // ENDPOINTS
  private url = `${environment.url}/retiro4uit/v1/util4uit/util?code=ubigeo`;

  constructor(private http: HttpClient) { }

  getDepartamentos () {
    this.http.get(this.url)
      .subscribe( (resp: Department[]) => {
        console.log(resp, 'departamentos');
        this.departamentos = resp;
      });
  }
}
/* Servicio Fin*/

/* Componente Inicio*/
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { STEPPER_GLOBAL_OPTIONS } from '@angular/cdk/stepper';
import { Ubigeo } from '../../commons/http/ubigeo.http';
import { SELECT_ITEM_HEIGHT_EM } from '@angular/material/select';
import { Department, Province } from '../../commons/interfaces/ubigeo.interface';

@Component({
  selector: 'app-residente-aporte-step',
  templateUrl: './residente-aporte-step.component.html',
  styleUrls: ['./residente-aporte-step.component.scss'],
  providers: [
    {
      provide: STEPPER_GLOBAL_OPTIONS,
      useValue: { displayDefaultIndicatorType: false },
    },
  ],
})
export class ResidenteAporteStepComponent implements OnInit {

  firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  public formSubmitted = false;

  constructor(
    private _formBuilder: FormBuilder,
    public ubigeo: Ubigeo,
    ) {}

  ngOnInit(): void {
    this.ubigeo.getDepartamentos();
  }

  // Cargando Datos del servicio 4uit localstorage
  firstName =  localStorage.getItem('firstName' || '').toLowerCase();
  amountAvailable =  localStorage.getItem('amountAvailable' || '');

  // carga Provincias
  onSelect(code: number): void {
    console.log(code);
  }
}
/* Componente Fin*/
<mat-form-field class="select-width">
    <mat-label>Departamento</mat-label>
    <select matNativeControl required [(ngModel)]="selectedDepartament.code" (change)="onSelect($event.target.value)">
        <option *ngFor="let departments of ubigeo.departamentos" value={{departments.code}}>{{departments.description | titlecase}}</option>
    </select>
</mat-form-field>

<mat-form-field class="select-width">
    <mat-label>Provincia</mat-label>
    <select matNativeControl required>
        <option value="Lima">Lima</option>
        <option value="Lima">Lima</option>
        <option value="Lima">Lima</option>
        <option value="Lima">Lima</option>
    </select>
</mat-form-field>

A: Primero a tu servicio agrega el siguiente método getProvincias(code) para obtener las provincias del departamento (lee los comentarios dentro del código):
export class Ubigeo {

  public departamentos: Department[] = [];
  public provincias: Province[] = [];
  // ENDPOINTS
  // retiramos el ubigeo y lo colocamos en getDepartamentos(), el parámetro code lo usaremos para obtener las provincias.
  private url = `${environment.url}/retiro4uit/v1/util4uit/util?code=`;

  constructor(private http: HttpClient) { }

  // método que realizará la petición para obtener los departamentos
  getDepartamentos() {
    // acá ponemos el parámetro code = ubigeo para que te devuelva los departamentos
    this.http.get(this.url + 'ubigeo')
      .subscribe( (resp: Department[]) => {
        console.log(resp, 'departamentos');
        this.departamentos = resp;
      });
  }

  // método que realizará la petición para obtener las provincias de un departamento
  // code es el parámetro que recibe el método y que enviaremos como parámetro de endpoint en code
  getProvincias(code: any) {
    // limpiamos las provincias
    this.provincias= [];
    // obtenemos las provincias con el parámetro code = code
    this.http.get(this.url + code)
      .subscribe( (resp: Province[]) => {
        console.log(resp, 'provincias');
        this.provincias = resp;
      });
  }
}

Luego en tu componente debes mandar a llamar al servicio para que obtenga las provincias:
export class ResidenteAporteStepComponent implements OnInit {

  firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  public formSubmitted = false;

  constructor(
    private _formBuilder: FormBuilder,
    public ubigeo: Ubigeo,
    ) {}

  ngOnInit(): void {
    this.ubigeo.getDepartamentos();
  }

  // Cargando Datos del servicio 4uit localstorage
  firstName =  localStorage.getItem('firstName' || '').toLowerCase();
  amountAvailable =  localStorage.getItem('amountAvailable' || '');

  // carga Provincias cambio tu parámetro a any, haz puesto tipo number, pero por lo que veo en consola es un string, no un número.
  onSelect(code: any): void {
    console.log(code);
    this.ubigeo.getProvincias(code); // con esto ya hemos obtenido las provincias del departamento seleccionado, ahora solo falta ponerlo en la plantilla html.
  }
}

Entonces en tu plantilla finalmente solo debes recorrer las provincias...
<mat-form-field class="select-width">
    <mat-label>Departamento</mat-label>
    <select matNativeControl required [(ngModel)]="selectedDepartament.code" (change)="onSelect($event.target.value)">
        <option *ngFor="let departments of ubigeo.departamentos" value={{departments.code}}>{{departments.description | titlecase}}</option>
    </select>
</mat-form-field>

<mat-form-field class="select-width">
    <mat-label>Provincia</mat-label>
    <!-- recorremos las provincias con un *ngFor -->
    <select matNativeControl required>
        <option *ngFor="let province of ubigeo.provincias" value="{{province.code}}">{{province.description | titlecase}}</option>
    </select>
</mat-form-field>

Espero esto te sea de utilidad, y espero también solucione tus dudas.


text:
Q: How to avoid in Java simultaneous processing of unique combinations before persisting in database? Maybe the obvious question but I cannot find an elegant solution for it
In a Spring Service initialized from a multithreaded Controller I process a request from a 3rd party that contains a combination of a confirmation code and a terminal number. Once we process  this request we persist this combination into the database and do not allow processing of this combination again.
The pseudo code is as follows:
protected void processAdmission(String confirmationCode, String terminalCode)
throws AdmissionException {

    //Check availability in the database
    boolean isAvailable = checkDatabaseAvailability(confirmationCode, terminalCode);
    if (!isAvailable)
    {
        throw new AdmissionException();
    }
    saveInDatabase(confirmationCode, terminalCode);
}

This unique combination is allowed only once to be processed; next time it should be an error because this combination is already in the database and we check the database .  What if this unique combination comes twice simultaneously?  The database protection will not help because the data are not in the database yet.

A: Assuming that you have the appropriate unique constraints in place and are using transactions:

*

*you do the work

*insert the values into the database

*commit the trasaction.

if the commit succeeds, all good.  if the commit throws a UniqueConstraintViolation, then the codes are already used and should be rejected (and the transaction will be rolled back so that any work you did is undone).

A: Asumming your data is backed by a relational database, you can rely on your database.
If the pair (confirmationCode,terminalCode) is persisted in the same table, then a PRIMARY KEY or UNIQUE constraint on the pair will preserve the uniqueness.

A: I think it is very hard to prevent that on application level. Consider that you have more than one server up and running that receive the same combination of terminal number and confirmation code, you are screwed :-)
If there is just a single instance and a single JVM, you could use create a class with a static HashSet to save the number/code and a synchronized static method that adds and checks if the combination is already present. Although that should work, be aware of the possible disadvantages of the synchronized keyword in your particular environment.
Here an example where the combination is the concatenated string of number and code
public CombinationValidator {
  private static HashSet<String> combinations;

  public static synchronized boolean addAndCheck(String combination) {
      if (combinations.contains(combination)) {
          return false;
      } else {
          combinations.add(combination);
          return true;
      }
   }
}

In the end, it is your database that needs to take care of that. Depending on your DBMS you would need to define unique key constraints. Then wait for the database to tell you if the insert has been successful. If so, continue to process the request. If not, throw the AdmissionException.

A: Finally, I created the new table and used select for update locking


text:
Q: LaTeX Trellis Diagrams for STBCs I recently had to draw multiple trellises for space-time block codes (first introduced in this paper; the open-access version is here). I'd like to share the code with you here, so that the work doesn't have to be done twice.
As you see, I created a new command for plotting a trellis, where you can add the number of states, the PSK order, and the x- and y-distance between points as arguments:

\documentclass[a4paper]{article}

\usepackage{pst-plot,pst-sigsys}
\usepackage[nomessages]{fp}

\newcommand{\trellis}[4]{
  \def \STATES {#1}
  \def \PSK {#2}
  \def \XDISTANCE {#3}
  \def \YDISTANCE {#4}
  \FPupn\NGROUPS{\STATES{} \PSK{} div 0 trunc}
  \multido{\ryA=0+-\YDISTANCE,\nA=1+1}{\STATES}{%
    \dotnode(0,\ryA){dotA\nA}
    \dotnode(\XDISTANCE,\ryA){dotB\nA}
  }
  \multido{\nG=1+1,\nOffset=1+\PSK}{\NGROUPS}{%
    \multido{\nStart=\nG+\NGROUPS}{\PSK}{%
      \multido{\nArrows=\nOffset+1}{\PSK}{%
        \ncline{dotA\nStart}{dotB\nArrows}
      }
    }
  }
}

\begin{document}
  \begin{pspicture}[showgrid=true](0,0)(12,-20)
    \rput(0,0){\trellis{4}{4}{1.}{1}}
    \rput(3,0){\trellis{16}{4}{1.5}{1}}
    \rput(6,0){\trellis{8}{8}{2.25}{2.25}}
  \end{pspicture}
\end{document}

A: You have a lot of trailing spaces which move your image to the right. If you are not sure where to place a % at the line end then do it for every line:
\newcommand{\trellis}[4]{%
  \def \STATES {#1}%
  \def \PSK {#2}%
  \def \XDISTANCE {#3}%
  \def \YDISTANCE {#4}%
  \FPupn\NGROUPS{\STATES{} \PSK{} div 0 trunc}%
  \multido{\ryA=0+-\YDISTANCE,\nA=1+1}{\STATES}{%
    \dotnode(0,\ryA){dotA\nA}
    \dotnode(\XDISTANCE,\ryA){dotB\nA}
  }%
  \multido{\nG=1+1,\nOffset=1+\PSK}{\NGROUPS}{%
    \multido{\nStart=\nG+\NGROUPS}{\PSK}{%
      \multido{\nArrows=\nOffset+1}{\PSK}{%
        \ncline{dotA\nStart}{dotB\nArrows}
      }%
    }%
  }%
}

PSTricks macros itself kill all glue, so the last % three are not needed. But it doesn't hurt ...

and I suppose that you do not need the fppackage. Try \numexpr
\multido{\nG=1+1,\nOffset=1+\PSK}{\numexpr\STATES/\PSK}{%
  \multido{\nStart=\nG+\numexpr\STATES/\PSK}{\PSK}{%


text:
Q: generating random color within an array and storing it in struct Hi i want to be able randomly select a given set of color and store it into an struct of array.
void addrand(struct inv[],int *ptr)

const char *random[6];
            random[0] = "red";
            random[1] = "green";
            random[2] = "yellow";
            random[3] = "blue";
            random[4] = "white";
            random[5] = "black";

inv[*ptr].color = random[rand()%6];

i get something like array type 'char[30]' is not assignable.


text:
Q: entrypoint command in gitlabci image Please explain what this entrypoint command does in gitlabci file
stages:
  - tfsec

    Terraform Security:
      allow_failure: true
      image:
        name: aquasec/tfsec
        entrypoint: ["/bin/sh", "-c"]

If it works in gitlabci, why does docker run fail with /bin/sh?
docker run --rm -it aquasec/tfsec /bin/sh
Error: provided path is not a dir

A: What is you gitlab version?
If it is greater than 17.06 , then use entrypoint: [""]


text:
Q: Java:How to restrict to adding sub classes in the collection? Can anyone please tell me the solution for the below question:
I have a super class named A,and few sub classes named B,C.The both sub classes B and C extends A.
I want to add the super class object in the collection(like arraylist) not sub class objects.
I mean the collection should allow only super class object not sub class object.

A: You cannot do this with static typing.
If you really need to do this, you need to write a collection class that uses
  element.getClass().equals(someClass)

to test that the (candidate) element satisfies your restriction.

A: There's no way to do it with java.util implemented colletions. You need to write your own collection that will check element's class and choose whether to add it or not. And you can still implement List<E> for example.
But it more looks like a design issue of your way of using class inheritance, like maybe those classes B,C shouldn't extend A.

A: You should use the Lower Bounded Wildcards of Generic to limit it.
For example:
List<E super A> aList = new ArrayList<>();

Now, the aList can only accept the super class of A (Of course, including Class A).
See the details:
https://docs.oracle.com/javase/tutorial/java/generics/lowerBounded.html