问:
No Autowiring in SpringBoot Vaadin Application when Deployed
I have a SpringBoot application with Vaadin which works fine when started with mvn clean install spring-boot:run out of the IDE.

If it is deployed to a Tomcat server @Autowire (for the ViewProvider) doesn’t work.

I get the following Warning:

```<code>o.s.c.a. ConfigurationClassPostProcessor  :
Cannot enhance @Configuration bean definition 'com.vaadin.spring.VaadinConfiguration'
since its singleton instance has been created too early.
The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor
return type: Consider declaring such methods as 'static'.
</code>```

And this exception:

```<code>java.lang.IllegalArgumentException: Cannot add a null view provider at com.vaadin.navigator.Navigator.addProvider(Navigator.java:887) ~[vaadin-server-7.7.7.jar.7.7.7]
at com.example.gui.MainUI.init(ManinUI.java:39)....
</code>```

My Applicaton Class:

```<code>@SpringBootApplication(scanBasePackages = { "com.example" })
@EnableJpaRepositories(basePackages={"com.example.db"})
@EntityScan(basePackages={"com.example.db.entities"})
@PropertySources(value = {@PropertySource("classpath:db.properties"),
        @PropertySource("classpath:gui.properties")}
)
@EnableVaadin
public class PersonApplication extends SpringBootServletInitializer {

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(PersonApplication.class);
    }

}
</code>```

My UI class:

```<code>@Theme("valo")
@SpringUI(path="/swme")
public class MainUI extends UI {

    private Navigator navigator;
    private SpringViewProvider viewProvider;

    @Autowired
    public void setViewProvider(SpringViewProvider viewProvider) {
        this.viewProvider = viewProvider;
    }

    @Autowired
    private PersonService myService;

    @Override
    protected void init(VaadinRequest request) {

        navigator = new Navigator(this, this);
        navigator.addProvider(viewProvider);

        final VerticalLayout layout = new VerticalLayout();
        layout.setMargin(true);
        setContent(layout);
        layout.addComponent(new MyView(myService));
    }
}
</code>```

The parent pom:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>DOTS4</artifactId>
    <version>5.0</version>
    <packaging>pom</packaging>

    <modules>
        <module>database</module>
        <module>service</module>
        <module>gui</module>
    </modules>

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

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>4.12</junit.version>
    </properties>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <goals>
                                <goal>repackage</goal>
                            </goals>
                            <configuration>
                                <classifier>exec</classifier>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

</project>
</code>```

The pom of the gui modul:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>gui</artifactId>
    <packaging>war</packaging>

    <parent>
        <groupId>com.example</groupId>
        <artifactId>DOTS4</artifactId>
        <version>1.0</version>
    </parent>

    <properties>
        <war.name>myapp</war.name>

        <maven-war-plugin.version>3.1.0</maven-war-plugin.version>
        <vaadin.version>7.7.7</vaadin.version>
        <vaadin-spring.version>1.2.0</vaadin-spring.version><!-- v2 requires vaadin.version >=8.0-->
    </properties>

    <build>
        <finalName>${war.name}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>${maven-war-plugin.version}</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-maven-plugin</artifactId>
                <version>${vaadin.version}</version>
                <configuration>
                    <extraJvmArgs>-Xmx512M -Xss8M</extraJvmArgs>
                    <webappDirectory>target/classes/VAADIN/widgetsets</webappDirectory>
                    <draftCompile>false</draftCompile>
                    <compileReport>false</compileReport>
                    <style>OBF</style>
                    <strict>true</strict>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>clean</goal>
                            <goal>resources</goal>
                            <goal>update-widgetset</goal>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>database</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>service</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-spring-boot-starter</artifactId>
            <version>${vaadin-spring.version}</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-bom</artifactId>
                <version>${vaadin.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>
</code>```

I am using Vaadin v7.7.7 with VaadinSpring v1.2 and
Tomcat-8.5.15

答: Found the reason I was changing an existing project and there was a vaadin servlet defined in web.xml, which created the singleton before spring boot could do its work. </p>

Body:
I have a SpringBoot application with Vaadin which works fine when started with mvn clean install spring-boot:run out of the IDE.

If it is deployed to a Tomcat server @Autowire (for the ViewProvider) doesn’t work.

I get the following Warning:

o.s.c.a. ConfigurationClassPostProcessor  :
Cannot enhance @Configuration bean definition 'com.vaadin.spring.VaadinConfiguration'
since its singleton instance has been created too early.
The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor
return type: Consider declaring such methods as 'static'.

And this exception:

java.lang.IllegalArgumentException: Cannot add a null view provider at com.vaadin.navigator.Navigator.addProvider(Navigator.java:887) ~[vaadin-server-7.7.7.jar.7.7.7]
at com.example.gui.MainUI.init(ManinUI.java:39)....

My Applicaton Class:

@SpringBootApplication(scanBasePackages = { "com.example" })
@EnableJpaRepositories(basePackages={"com.example.db"})
@EntityScan(basePackages={"com.example.db.entities"})
@PropertySources(value = {@PropertySource("classpath:db.properties"),
        @PropertySource("classpath:gui.properties")}
)
@EnableVaadin
public class PersonApplication extends SpringBootServletInitializer {

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(PersonApplication.class);
    }

}

My UI class:

@Theme("valo")
@SpringUI(path="/swme")
public class MainUI extends UI {

    private Navigator navigator;
    private SpringViewProvider viewProvider;

    @Autowired
    public void setViewProvider(SpringViewProvider viewProvider) {
        this.viewProvider = viewProvider;
    }

    @Autowired
    private PersonService myService;

    @Override
    protected void init(VaadinRequest request) {

        navigator = new Navigator(this, this);
        navigator.addProvider(viewProvider);

        final VerticalLayout layout = new VerticalLayout();
        layout.setMargin(true);
        setContent(layout);
        layout.addComponent(new MyView(myService));
    }
}

The parent pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>DOTS4</artifactId>
    <version>5.0</version>
    <packaging>pom</packaging>

    <modules>
        <module>database</module>
        <module>service</module>
        <module>gui</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>4.12</junit.version>
    </properties>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <goals>
                                <goal>repackage</goal>
                            </goals>
                            <configuration>
                                <classifier>exec</classifier>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

</project>

The pom of the gui modul:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>gui</artifactId>
    <packaging>war</packaging>

    <parent>
        <groupId>com.example</groupId>
        <artifactId>DOTS4</artifactId>
        <version>1.0</version>
    </parent>

    <properties>
        <war.name>myapp</war.name>

        <maven-war-plugin.version>3.1.0</maven-war-plugin.version>
        <vaadin.version>7.7.7</vaadin.version>
        <vaadin-spring.version>1.2.0</vaadin-spring.version>
    </properties>

    <build>
        <finalName>${war.name}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>${maven-war-plugin.version}</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-maven-plugin</artifactId>
                <version>${vaadin.version}</version>
                <configuration>
                    <extraJvmArgs>-Xmx512M -Xss8M</extraJvmArgs>
                    <webappDirectory>target/classes/VAADIN/widgetsets</webappDirectory>
                    <draftCompile>false</draftCompile>
                    <compileReport>false</compileReport>

                    <strict>true</strict>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>clean</goal>
                            <goal>resources</goal>
                            <goal>update-widgetset</goal>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>database</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>service</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-spring-boot-starter</artifactId>
            <version>${vaadin-spring.version}</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-bom</artifactId>
                <version>${vaadin.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

I am using Vaadin v7.7.7 with VaadinSpring v1.2 and
Tomcat-8.5.15


来源: stackexchange

问:
Add up all the values in a queryset in Django
I am writing a django app that has two classes: A review, and a reply to the said review. The reply is stored in a ManyToMany Field in the review.

This is my Class for the review:

```<code>class Review(models.Model):
    title = models.CharField(max_length = 30)
    replies = models.ManyToManyField(Reply)

    def __str__(self):
        return self.title
</code>```

And here is my reply class:

```<code>class Reply(models.Model):
    rating = models.DecimalField(decimal_places=1,
                                 max_digits = 2,
                                 validators = [MaxValueValidator(5), MinValueValidator(0)],
                                 default = 0
                                )
    text_reply = models.TextField(max_length = 200)
</code>```

One of the things I wish to do, is to take all the ratings for a certain Review, and calculate the average of these numbers. I have tried to do this by doing this:

```<code>def calculate_average():
    objects = Review.objects.all()
    average = 0
    length = 0
    for reply in objects:
        average += reply.replies.rating
        length += 1
    return average/length
</code>```

Traceback

```<code>C:\Users\Will Treston\gd\LesRev\lesssonreview>python manage.py runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03363540>
Traceback (most recent call last):
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate
    app_config.ready()
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
    self.module.autodiscover()
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:\Users\Will Treston\gd\LesRev\lesssonreview\review\admin.py", line 5, in <module>
    class ReviewAdmin(admin.ModelAdmin):
  File "C:\Users\Will Treston\gd\LesRev\lesssonreview\review\admin.py", line 8, in ReviewAdmin
    list_display = ["title", Review.calculate_average()]
  File "C:\Users\Will Treston\gd\LesRev\lesssonreview\review\models.py", line 46, in calculate_average
    average += reply.replies.rating
AttributeError: 'ManyRelatedManager' object has no attribute 'rating'
</code>```

答:
For calculating rating for a particular review,

```<code>result = {}
objects = Review.objects.all()
for review in objects:
    average = 0
    length = 0
    for reply in review.replies.all():
        average += reply.rating
        length += 1
    average /= length
    result.update({review.title, average})
</code>```

If you are looking for a model attribute to calculate the same of a single Model, then

```<code>class Review(models.Model):

    def calculate_rating(self):
        average = 0
        length = 0
        for reply in self.replies.all():
            average += reply.rating
            length += 1
        if average:
            average /= length
        return average
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing a django app that has two classes: A review, and a reply to the said review. The reply is stored in a ManyToMany Field in the review.

This is my Class for the review:

class Review(models.Model):
    title = models.CharField(max_length = 30)
    replies = models.ManyToManyField(Reply)

    def __str__(self):
        return self.title

And here is my reply class:

class Reply(models.Model):
    rating = models.DecimalField(decimal_places=1,
                                 max_digits = 2,
                                 validators = [MaxValueValidator(5), MinValueValidator(0)],
                                 default = 0
                                )
    text_reply = models.TextField(max_length = 200)

One of the things I wish to do, is to take all the ratings for a certain Review, and calculate the average of these numbers. I have tried to do this by doing this:

def calculate_average():
    objects = Review.objects.all()
    average = 0
    length = 0
    for reply in objects:
        average += reply.replies.rating
        length += 1
    return average/length

Traceback

C:\Users\Will Treston\gd\LesRev\lesssonreview>python manage.py runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03363540>
Traceback (most recent call last):
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate
    app_config.ready()
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
    self.module.autodiscover()
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:\Users\Will Treston\gd\LesRev\lesssonreview\review\admin.py", line 5, in <module>
    class ReviewAdmin(admin.ModelAdmin):
  File "C:\Users\Will Treston\gd\LesRev\lesssonreview\review\admin.py", line 8, in ReviewAdmin
    list_display = ["title", Review.calculate_average()]
  File "C:\Users\Will Treston\gd\LesRev\lesssonreview\review\models.py", line 46, in calculate_average
    average += reply.replies.rating
AttributeError: 'ManyRelatedManager' object has no attribute 'rating'

Body:
For calculating rating for a particular review,

result = {}
objects = Review.objects.all()
for review in objects:
    average = 0
    length = 0
    for reply in review.replies.all():
        average += reply.rating
        length += 1
    average /= length
    result.update({review.title, average})

If you are looking for a model attribute to calculate the same of a single Model, then

class Review(models.Model):

    def calculate_rating(self):
        average = 0
        length = 0
        for reply in self.replies.all():
            average += reply.rating
            length += 1
        if average:
            average /= length
        return average


问:
Connect my application (node, express, mongo) with my local database and query it
I build a small application with node.js, express.js, passport.js and mongodb. I'm new to this technology so I'm trying to test it locally before uploading the code on a server and connect it with mongolab. Now my problem is that I'm not able to see or query all my user locally with my mongo shell, so, everytime I add a user, I'm not able to see if I really add it or not. So far my code is the following:

app.js

```<code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var port = process.env.PORT || 3000;

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var mongoose = require('mongoose');
var flash = require('connect-flash');
var session = require('express-session');

var routes = require('./routes/index');
var users = require('./routes/users');

var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
</code>```

database.js (config/database.js)

```<code>module.exports = {
  url: 'mongodb://localhost/expressauth',
};
</code>```

user.js (models/user.js)

```<code>var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');

var userSchema = mongoose.Schema({
  local: {
    name: String,
    email: String,
    password: String,
  },
});

userSchema.methods.generateHash = function(password) {
  return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

userSchema.methods.validPassword = function(password) {
  return bcrypt.compareSync(password, this.local.password);
};

module.exports = mongoose.model('User', userSchema);
</code>```

The code is working fine so far, and every time I add a new user I'm able to obtain a user id (something like that 59397add4905d20f0329125c) and a password.

Now I'm trying to see all my users through the mongo shell so I type MONGO in my terminal and then I type SHOW DBS, so I can see all my database.

I can find the database that I create through my database.js (url: 'mongodb://localhost/expressauth') called expressauth, so I switch to it (USE expressauth) and at the very end I try to make a query (something like SELECT * in mysql) with this method that I found in the documentation => db.expressauth.find().

But I don't receive any data. So I'm not able to test my application (which is actually an web app that I found on github: https://github.com/danielgynn/express-authentication/.

Any suggestion why my mongoshell is not working?

答: If you're in the mongoshell and already called use expressauth, then you should be able to do show collections to see what collections are in that database.  The user or users collection should be there depending on your configuration.  Then you can call db.users.find() to get all the users in the collection.

Body:
I build a small application with node.js, express.js, passport.js and mongodb. I'm new to this technology so I'm trying to test it locally before uploading the code on a server and connect it with mongolab. Now my problem is that I'm not able to see or query all my user locally with my mongo shell, so, everytime I add a user, I'm not able to see if I really add it or not. So far my code is the following:

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var port = process.env.PORT || 3000;

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var mongoose = require('mongoose');
var flash = require('connect-flash');
var session = require('express-session');

var routes = require('./routes/index');
var users = require('./routes/users');

var configDB = require('./config/database.js');
mongoose.connect(configDB.url);

database.js (config/database.js)

module.exports = {
  url: 'mongodb://localhost/expressauth',
};

user.js (models/user.js)

var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');

var userSchema = mongoose.Schema({
  local: {
    name: String,
    email: String,
    password: String,
  },
});

userSchema.methods.generateHash = function(password) {
  return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

userSchema.methods.validPassword = function(password) {
  return bcrypt.compareSync(password, this.local.password);
};

module.exports = mongoose.model('User', userSchema);

The code is working fine so far, and every time I add a new user I'm able to obtain a user id (something like that 59397add4905d20f0329125c) and a password.

Now I'm trying to see all my users through the mongo shell so I type MONGO in my terminal and then I type SHOW DBS, so I can see all my database.

I can find the database that I create through my database.js (url: 'mongodb://localhost/expressauth') called expressauth, so I switch to it (USE expressauth) and at the very end I try to make a query (something like SELECT * in mysql) with this method that I found in the documentation => db.expressauth.find().

But I don't receive any data. So I'm not able to test my application (which is actually an web app that I found on github: https://github.com/danielgynn/express-authentication/.

Any suggestion why my mongoshell is not working?


问:
Starting Tomcat with local user causes JVM_Bind exception
I have a tomcat service that starts fine with the local system account but when I switch it over to log on as a local user I am getting a JVM_Bind exception. The service starts and then shuts down. </p>

<p>It looks like the shutdown port is already being used by another service. I can change the tomcat service to use a different shutdown port, but I want to understand why it starts fine with the system account and complains about the shutdown port with the user account. </p>

```<code>06-Jun-2017 15:46:13.801 SEVERE [main] org.apache.catalina.core.StandardServer.await StandardServer.await: create[localhost:10006]:
 java.net.BindException: Address already in use: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
    at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
    at java.net.ServerSocket.bind(ServerSocket.java:375)
    at java.net.ServerSocket.<init>(ServerSocket.java:237)
    at org.apache.catalina.core.StandardServer.await(StandardServer.java:420)
    at org.apache.catalina.startup.Catalina.await(Catalina.java:713)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:659)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)
</code>```

答:
Generic Solution for Tomcat JVM_BIND exceptions

Windows

1) Might be some other services listening to the same port 8080, In such cases go to %TOMCAT_HOME%/conf/server.xml and change the port to your desired integer like 8081,9080 etc.

2) Go to Windows task manager and check for some other java process running behind, if running end the process.

3) You can do netstat command on Windows to check for active connections and check for 8080 or (whatever your configured)  ports which is listening and kill those services.

Linux

1) ps - ef ¦ grep java use this command to identify the process running behind, if many processes running which is not relevant. You can kill the process by kill - 9 processid

2) You can do the netstat command on linux and check for the 8080 or (whatever your configured) ports which is listening and kill those services.

3) Also you can change your $TOMCAT_HOME/conf/server.xml port number to your desired integers.

Mac

Kill processId terminal kill <pid>

To find ProcessId use this below command.

  lsof -i:

Also you can change your $TOMCAT_HOME/conf/server.xml port number to your desired integers.

Body:
I have a tomcat service that starts fine with the local system account but when I switch it over to log on as a local user I am getting a JVM_Bind exception. The service starts and then shuts down.

It looks like the shutdown port is already being used by another service. I can change the tomcat service to use a different shutdown port, but I want to understand why it starts fine with the system account and complains about the shutdown port with the user account.

06-Jun-2017 15:46:13.801 SEVERE [main] org.apache.catalina.core.StandardServer.await StandardServer.await: create[localhost:10006]:
 java.net.BindException: Address already in use: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
    at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
    at java.net.ServerSocket.bind(ServerSocket.java:375)
    at java.net.ServerSocket.<init>(ServerSocket.java:237)
    at org.apache.catalina.core.StandardServer.await(StandardServer.java:420)
    at org.apache.catalina.startup.Catalina.await(Catalina.java:713)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:659)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)


问:
How to send messages in grpc bidirectional rpc without buffering from grpc node client
RouteChat example which is a bi-directional rpc, seems to be buffering messages on write. Is there a way to force writes to the outgoing stream immediately without buffering?</p>

答:
The reason you're seeing this buffering behavior is because writes are actually completed asynchronously, so the server code needs to regularly allow other asynchronous operations to happen between writes to ensure that they are sent as soon as they are computed. You can take advantage of the optional callback argument to write to send each message immediately after the last one is sent. The code in that example can instead be written using async.each:

```<code>async.each(notes, function(note, next) {
  console.log('Sending message "' + note.message + '" at ' +
      note.location.latitude + ', ' + note.location.longitude);
  var noteMsg = new messages.RouteNote();
  noteMsg.setMessage(note.message);
  var location = new messages.Point();
  location.setLatitude(note.location.latitude);
  location.setLongitude(note.location.longitude);
  noteMsg.setLocation(location);
  // Note the use of the next callback here
  call.write(noteMsg, next);
}, function() {
  // End the stream after all messages have been sent
  call.end();
});
</code>```

Body:
The reason you're seeing this buffering behavior is because writes are actually completed asynchronously, so the server code needs to regularly allow other asynchronous operations to happen between writes to ensure that they are sent as soon as they are computed. You can take advantage of the optional callback argument to write to send each message immediately after the last one is sent. The code in that example can instead be written using async.each:

async.each(notes, function(note, next) {
  console.log('Sending message "' + note.message + '" at ' +
      note.location.latitude + ', ' + note.location.longitude);
  var noteMsg = new messages.RouteNote();
  noteMsg.setMessage(note.message);
  var location = new messages.Point();
  location.setLatitude(note.location.latitude);
  location.setLongitude(note.location.longitude);
  noteMsg.setLocation(location);
  // Note the use of the next callback here
  call.write(noteMsg, next);
}, function() {
  // End the stream after all messages have been sent
  call.end();
});


问:
How to make a qmake target to create QtIFW installer
I would like to automate the generation of an installer in my build process, with some control over when it gets built. How do I set up a make target to generate an installer using qmake?

I have a subdirs project with multiple components. The installer configuration is in a subdirectory (“installer-qt”). Files need to be copied to the installer packages’ data directories, then run the installer generator automatically. In addition to the built binaries I’d like to install documentation, headers, and other resources.

答:
This is what I've come up with.

Step 1: Copy files to the installer packages

Using make install:
Add this to the subprojects:

```<code>package_build {
    INSTALLER_PACKAGE=$$PWD/installer-qt/packages
    INSTALL_PREFIX=$$INSTALLER_PACKAGE/com.example.component1/data
} else {
    isEmpty(INSTALL_PREFIX): INSTALL_PREFIX="/opt/ExampleCorp"
}
message("Install to $$INSTALL_PREFIX")
unix {
    target.path = "$$INSTALL_PREFIX/bin"
    documentation.path = "$$INSTALL_PREFIX/doc"
    includes.path = "$$INSTALL_PREFIX/include"
    testcase|staticlib {
        INSTALLS -= target
    } else {
        INSTALLS += target
        INSTALLS += documentation
        INSTALLS += includes
    }
}
documentation.files += readme.txt
includes.files += header.h
</code>```

Now you can use the default /opt install when you run qmake, specify the prefix when you run qmake using qmake INSTALL_PREFIX=/my/prefix, or specify copying to the installer package when you run qmake using qmake CONFIG+=package_build

(Open question: How best to copy everything to the installer data without overriding the normal ‘make install’?)

Step 2: Build installer package

Add a qmake .pro project in installer-qt:

```<code>TEMPLATE = subdirs # Empty project

CONFIG(release, debug|release) {
    unix: INSTALLER_OFFLINE = $$PWD/MYPROJECT-linux-x64.run
    win32: INSTALLER_OFFLINE = $$PWD/MYPROJECT-win32-x64.exe
}
CONFIG(debug, debug|release) {
    unix: INSTALLER_OFFLINE = $$PWD/MYPROJECT-linux-x64-debug.run
    win32: INSTALLER_OFFLINE = $$PWD/MYPROJECT-win32-x64-debug.exe
}
OTHER_FILES += $$PWD/config/config.xml \
    $$PWD/packages/com.example.component1/meta/package.xml
# Create the target assembly Offline Installer
QTIFWDIR = $$(HOME)/Qt/QtIFW2.0.5
offlineInstaller.target = $$INSTALLER_OFFLINE
offlineInstaller.commands = $$QTIFWDIR/bin/binarycreator --offline-only \
    -c $$PWD/config/config.xml -p $$PWD/packages $$offlineInstaller.target
offlineInstaller.depends = install
offlineInstallerTarget.target = package # This is the real name of the target
offlineInstallerTarget.depends = offlineInstaller
QMAKE_EXTRA_TARGETS += offlineInstaller offlineInstallerTarget
</code>```

This is enough to run ‘make package’ in the subdirectory, but we want to run it from the top level build directory. To do that, add this to the top level subdirs project:

```<code>SUBDIRS += installer-qt
offlineInstaller.target = package
offlineInstaller.depends = installer-qt mysubproject install
offlineInstaller.CONFIG = recursive
offlineInstaller.recurse = installer-qt
offlineInstaller.recurse_target = package
QMAKE_EXTRA_TARGETS += offlineInstaller
</code>```

Now you can run ‘qmake CONFIG+= package_build /path/to/project.pro && make package’ from the build directory to build the installer.
Add this to the QtCreator deploy configuration by going to Add Deploy Step > Make and putting in “package” for the “Make arguments.”

Resources:

https://evileg.com/en/post/164/

http://doc.qt.io/qt-5/qmake-advanced-usage.html#adding-custom-targets

Body:
This is what I've come up with.

Step 1: Copy files to the installer packages

Using make install:
Add this to the subprojects:

package_build {
    INSTALLER_PACKAGE=$$PWD/installer-qt/packages
    INSTALL_PREFIX=$$INSTALLER_PACKAGE/com.example.component1/data
} else {
    isEmpty(INSTALL_PREFIX): INSTALL_PREFIX="/opt/ExampleCorp"
}
message("Install to $$INSTALL_PREFIX")
unix {
    target.path = "$$INSTALL_PREFIX/bin"
    documentation.path = "$$INSTALL_PREFIX/doc"
    includes.path = "$$INSTALL_PREFIX/include"
    testcase|staticlib {
        INSTALLS -= target
    } else {
        INSTALLS += target
        INSTALLS += documentation
        INSTALLS += includes
    }
}
documentation.files += readme.txt
includes.files += header.h

Now you can use the default /opt install when you run qmake, specify the prefix when you run qmake using qmake INSTALL_PREFIX=/my/prefix, or specify copying to the installer package when you run qmake using qmake CONFIG+=package_build

(Open question: How best to copy everything to the installer data without overriding the normal ‘make install’?)

Step 2: Build installer package

Add a qmake .pro project in installer-qt:

TEMPLATE = subdirs # Empty project

CONFIG(release, debug|release) {
    unix: INSTALLER_OFFLINE = $$PWD/MYPROJECT-linux-x64.run
    win32: INSTALLER_OFFLINE = $$PWD/MYPROJECT-win32-x64.exe
}
CONFIG(debug, debug|release) {
    unix: INSTALLER_OFFLINE = $$PWD/MYPROJECT-linux-x64-debug.run
    win32: INSTALLER_OFFLINE = $$PWD/MYPROJECT-win32-x64-debug.exe
}
OTHER_FILES += $$PWD/config/config.xml \
    $$PWD/packages/com.example.component1/meta/package.xml
# Create the target assembly Offline Installer
QTIFWDIR = $$(HOME)/Qt/QtIFW2.0.5
offlineInstaller.target = $$INSTALLER_OFFLINE
offlineInstaller.commands = $$QTIFWDIR/bin/binarycreator --offline-only \
    -c $$PWD/config/config.xml -p $$PWD/packages $$offlineInstaller.target
offlineInstaller.depends = install
offlineInstallerTarget.target = package # This is the real name of the target
offlineInstallerTarget.depends = offlineInstaller
QMAKE_EXTRA_TARGETS += offlineInstaller offlineInstallerTarget

This is enough to run ‘make package’ in the subdirectory, but we want to run it from the top level build directory. To do that, add this to the top level subdirs project:

SUBDIRS += installer-qt
offlineInstaller.target = package
offlineInstaller.depends = installer-qt mysubproject install
offlineInstaller.CONFIG = recursive
offlineInstaller.recurse = installer-qt
offlineInstaller.recurse_target = package
QMAKE_EXTRA_TARGETS += offlineInstaller

Now you can run ‘qmake CONFIG+= package_build /path/to/project.pro && make package’ from the build directory to build the installer.
Add this to the QtCreator deploy configuration by going to Add Deploy Step > Make and putting in “package” for the “Make arguments.”

Resources:

https://evileg.com/en/post/164/

http://doc.qt.io/qt-5/qmake-advanced-usage.html#adding-custom-targets


问:
AngularJs Directive Link function can't access attr attribute
I have the following return of an directive in angularJS

```<code>return {
            restrict: _restrict,
            link: function (scope, element, attrs) {
                $timeout(LinkPre, 0);  //Calling a scoped method
            },
            templateUrl: ConstrutorapiTemplatesChart,
            scope: "@",
            controller: Controller
        }
</code>```

My LinkPre function is the function below

```<code>var LinkPre = function (scope, elem, attrs) {
            attrs.$observe(_attrUrl, function (relatorio) {
                if (relatorio != "") AoMudarUrl(scope, elem, relatorio);
            });
        }
</code>```

I got an error on the LinkPre function, that the attrs is undefined

Cannot read property '$observe' of undefined

Anyone has any ideia why?

Obs: I need that the Link function be executed after the directive is rendered

答:
thats because your LinkPre function doesnt recive any aguments when called by timeout, and thats why attrs and all of the parameters will be undefined, you could try the following:

```<code>$timeout(function() {
    LinkPre(scope, elem, attrs);
});
</code>```

no need for the end zero either

Body:
I have the following return of an directive in angularJS

return {
            restrict: _restrict,
            link: function (scope, element, attrs) {
                $timeout(LinkPre, 0);  //Calling a scoped method
            },
            templateUrl: ConstrutorapiTemplatesChart,
            scope: "@",
            controller: Controller
        }

My LinkPre function is the function below

var LinkPre = function (scope, elem, attrs) {
            attrs.$observe(_attrUrl, function (relatorio) {
                if (relatorio != "") AoMudarUrl(scope, elem, relatorio);
            });
        }

I got an error on the LinkPre function, that the attrs is undefined

Cannot read property '$observe' of undefined

Anyone has any ideia why?

Obs: I need that the Link function be executed after the directive is rendered

Body:
thats because your LinkPre function doesnt recive any aguments when called by timeout, and thats why attrs and all of the parameters will be undefined, you could try the following:

$timeout(function() {
    LinkPre(scope, elem, attrs);
});

no need for the end zero either


问:
ClickHouse Distributed Table Slow
I have created a distributed table in ClickHouse with two shards and one replica of the data in total.

```<code>SELECT *
FROM system.clusters

┌─cluster──────────────┬─shard_num─┬─shard_weight─┬─replica_num─┬─host_name────┬─host_address─┬─port─┬─is_local─┬─user────┬─default_database─┐
│ twoshardsonereplicas │         1 │            1 │           1 │ 192.168.8.70 │ 192.168.8.70 │ 9000 │        0 │ default │                  │
│ twoshardsonereplicas │         2 │            1 │           1 │ 192.168.8.71 │ 192.168.8.71 │ 9000 │        1 │ default │                  │
└──────────────────────┴───────────┴──────────────┴─────────────┴──────────────┴──────────────┴──────┴──────────┴─────────┴──────────────────┘
</code>```

I have the tables exit and exit_all which is the distributed table. I insert into the table exit_all and it distributes the data evenly across my two servers. When I query from the local exit table on half the records it takes 0.15, seconds but when doing on exit_all it takes 0.45 seconds. I would expect it to take around the same amount of time since the processing is split.

I can see when I count my query that the data is split perfectly for this query or within 100 records on 100k so it's not like all the data is sitting on one server.

Edit: Also getting large variances in query time every 2-3 queries where for some, it will go from 1.3 seconds down to 750ms for the same query.

答:
To answer the first question:

Distributed tables can add some amount of overhead to processing. Since you are doing two queries, passing the result via https and merging them, the last two parts can well add 0.3 seconds of processing, simply passing the data from one machine to another (in a local network) via http can take well over 0.1 seconds.

Tl;dr You're distributed query is still taking ~0.15 seconds, transferring and merging the result takes more time however

To answer the second question:
Clickhouse has internal query caching, so repeating a query might or might not trigger data withdrawal from the cache making it faster. Hence why you are noticing inconsistencies with query time.

Title: ClickHouse Distributed Table Slow

Body:
I have created a distributed table in ClickHouse with two shards and one replica of the data in total.

SELECT *
FROM system.clusters

┌─cluster──────────────┬─shard_num─┬─shard_weight─┬─replica_num─┬─host_name────┬─host_address─┬─port─┬─is_local─┬─user────┬─default_database─┐
│ twoshardsonereplicas │         1 │            1 │           1 │ 192.168.8.70 │ 192.168.8.70 │ 9000 │        0 │ default │                  │
│ twoshardsonereplicas │         2 │            1 │           1 │ 192.168.8.71 │ 192.168.8.71 │ 9000 │        1 │ default │                  │
└──────────────────────┴───────────┴──────────────┴─────────────┴──────────────┴──────────────┴──────┴──────────┴─────────┴──────────────────┘

I have the tables exit and exit_all which is the distributed table. I insert into the table exit_all and it distributes the data evenly across my two servers. When I query from the local exit table on half the records it takes 0.15, seconds but when doing on exit_all it takes 0.45 seconds. I would expect it to take around the same amount of time since the processing is split.

I can see when I count my query that the data is split perfectly for this query or within 100 records on 100k so it's not like all the data is sitting on one server.

Edit: Also getting large variances in query time every 2-3 queries where for some, it will go from 1.3 seconds down to 750ms for the same query.


问:
How to autocomplete a bash commandline with file paths?

Context

I am creating a shell program which is a command line tool. I want to create my own auto-completion for this tool.

I want to do two different things (maybe should I post two questions):

for the options --install and -i, I want to auto-complete on file paths, like the ls command do.

for the options --unit-test and -t, I want to auto-complete on file paths from a particular directory which I can get running my_app --directory.

my_app_autocomplete file

```<code>__my_app_autocomplete()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="--help -h --install -i --run -r --rebuild -rb --show-running-containers -ps --stop -s --remove -rm --logs -l --bash -b --sass -css --unit-tests -t"
    containers="nginx php mysql mongo node"
    sass="watch"

    # By default, autocomplete with options
    if [[ ${prev} == my_app ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
    # By default, autocomplete with options
    if [[ ${cur} == -* ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
    # For --install and -i options, autocomplete with folder
    if [ ${prev} == --install ] || [ ${prev} == -i ] ; then
        COMPREPLY=( $(compgen -d -- ${cur}) )
        return 0
    fi
    # For --stop --remove --logs and --bash, autocomplete with containers
    if [ ${prev} == --stop ] || [ ${prev} == -s ] || [ ${prev} == --remove ] || [ ${prev} == -rm ] || [ ${prev} == --logs ] || [ ${prev} == -l ] || [ ${prev} == --bash ] || [ ${prev} == -b ] ; then
        COMPREPLY=( $(compgen -W "${containers}" -- ${cur}) )
        return 0
    fi
    # For --sass and -css, complete with sass options
    if [ ${prev} == --sass ] || [ ${prev} == -css ] ; then
        COMPREPLY=( $(compgen -W "${sass}" -- ${cur}) )
        return 0
    fi
    # For --unit-tests and -t, complete with relative to my_app folder paths
    if [ ${prev} == --unit-tests ] || [ ${prev} == -t ] ; then
        COMPREPLY=( $(compgen -d -- ${cur}) )
        return 0
    fi
}
complete -F __my_app_autocomplete my_app
</code>```

Problem

I struggle on a particular point: auto-complete file paths.

I don't understand compgen options and how to do things with it. Maybe I could try to run a subcommand but I don't know the syntax and I can't find any useful information except man of bash - Programmable completion builtins which does not give much information about compgen.

In this case, when I do:

```<code>user@computer:~$ my_app --install D[TAB][TAB]
</code>```

I would like:

```<code>user@computer:~$ my_app --install Documents/
</code>```

I obtain:

```<code>user@computer:~$ myapp --install Documents
</code>```

with a blank space at the end of the line, which is a problem because I have to erase it and add a / to be able to redo [TAB][TAB] to auto-complete for sub-directories.

Investigations

-o nospace

With the option -o nospace applied on complete as:

```<code>complete -o nospace -F __my_app_autocomplete my_app
</code>```

the behavior is:

```<code>user@computer:~$ myapp --i[TAB][TAB]
user@computer:~$ myapp --install
</code>```

without space.

```<code>user@computer:~$ myapp --install D[TAB][TAB]
user@computer:~$ myapp --install Documents
</code>```

without space.

Problems:

It removes spaces for all options, forcing me to manually add a space after those that aren't file paths (like --install)

I have to add / to navigate into sub directories

-o filenames

With the option -o filenames applied on complete as:

```<code>complete -o filenames -F __my_app_autocomplete my_app
</code>```

the behavior is:

```<code>user@computer:~$ myapp --i[TAB][TAB]
user@computer:~$ myapp --install
</code>```

with a space

```<code>user@computer:~$ myapp --install D[TAB][TAB]
user@computer:~$ myapp --install Documents/
</code>```

with a / and without space if it's a directory

```<code>user@computer:~$ my_app --install D[TAB][TAB]
</code>```0

with a space if it's a file

It seems to set paths only for completion not defined in an list of words, so it does not affect other completions, I think it's the first part of what I need.

From a particular directory

I will open another question to avoid mixing things: How to autocomplete a bash commandline with file paths from a specific directory without displaying this directory?

答:
To auto complete file paths

Substitute

```<code>complete -F __my_app_autocomplete my_app
</code>```

with

```<code>complete -o filenames -F __my_app_autocomplete my_app
</code>```

Here you can find all the compgen options explained:

https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html

Body:
Context

I am creating a shell program which is a command line tool. I want to create my own auto-completion for this tool.

I want to do two different things (maybe should I post two questions):

for the options --install and -i, I want to auto-complete on file paths, like the ls command do.

for the options --unit-test and -t, I want to auto-complete on file paths from a particular directory which I can get running my_app --directory.

my_app_autocomplete file

__my_app_autocomplete()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="--help -h --install -i --run -r --rebuild -rb --show-running-containers -ps --stop -s --remove -rm --logs -l --bash -b --sass -css --unit-tests -t"
    containers="nginx php mysql mongo node"
    sass="watch"

    # By default, autocomplete with options
    if [[ ${prev} == my_app ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
    # By default, autocomplete with options
    if [[ ${cur} == -* ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
    # For --install and -i options, autocomplete with folder
    if [ ${prev} == --install ] || [ ${prev} == -i ] ; then
        COMPREPLY=( $(compgen -d -- ${cur}) )
        return 0
    fi
    # For --stop --remove --logs and --bash, autocomplete with containers
    if [ ${prev} == --stop ] || [ ${prev} == -s ] || [ ${prev} == --remove ] || [ ${prev} == -rm ] || [ ${prev} == --logs ] || [ ${prev} == -l ] || [ ${prev} == --bash ] || [ ${prev} == -b ] ; then
        COMPREPLY=( $(compgen -W "${containers}" -- ${cur}) )
        return 0
    fi
    # For --sass and -css, complete with sass options
    if [ ${prev} == --sass ] || [ ${prev} == -css ] ; then
        COMPREPLY=( $(compgen -W "${sass}" -- ${cur}) )
        return 0
    fi
    # For --unit-tests and -t, complete with relative to my_app folder paths
    if [ ${prev} == --unit-tests ] || [ ${prev} == -t ] ; then
        COMPREPLY=( $(compgen -d -- ${cur}) )
        return 0
    fi
}
complete -F __my_app_autocomplete my_app

Problem

I struggle on a particular point: auto-complete file paths.

I don't understand compgen options and how to do things with it. Maybe I could try to run a subcommand but I don't know the syntax and I can't find any useful information except man of bash - Programmable completion builtins which does not give much information about compgen.

In this case, when I do:

user@computer:~$ my_app --install D[TAB][TAB]

I would like:

user@computer:~$ my_app --install Documents/

I obtain:

user@computer:~$ myapp --install Documents

with a blank space at the end of the line, which is a problem because I have to erase it and add a / to be able to redo [TAB][TAB] to auto-complete for sub-directories.

Investigations

-o nospace

With the option -o nospace applied on complete as:

complete -o nospace -F __my_app_autocomplete my_app

the behavior is:

user@computer:~$ myapp --i[TAB][TAB]
user@computer:~$ myapp --install

without space.

user@computer:~$ myapp --install D[TAB][TAB]
user@computer:~$ myapp --install Documents

without space.

Problems:

It removes spaces for all options, forcing me to manually add a space after those that aren't file paths (like --install)

I have to add / to navigate into sub directories

-o filenames

With the option -o filenames applied on complete as:

complete -o filenames -F __my_app_autocomplete my_app

the behavior is:

user@computer:~$ myapp --i[TAB][TAB]
user@computer:~$ myapp --install

with a space

user@computer:~$ myapp --install D[TAB][TAB]
user@computer:~$ myapp --install Documents/

with a / and without space if it's a directory

user@computer:~$ myapp --install f[TAB][TAB]
user@computer:~$ myapp --install file

with a space if it's a file

It seems to set paths only for completion not defined in an list of words, so it does not affect other completions, I think it's the first part of what I need.

From a particular directory

I will open another question to avoid mixing things: How to autocomplete a bash commandline with file paths from a specific directory without displaying this directory?

Body:
To auto complete file paths

Substitute

complete -F __my_app_autocomplete my_app

with

complete -o filenames -F __my_app_autocomplete my_app

Here you can find all the compgen options explained:

https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html


问:
How do I read (i.e. understand) this Java array?
```<code>String[][][] arr  =
{{ { "a", "b" , "c"}, { "d", "e", null } },{ {"x"}, null },{{"y"}},{ { "z","p"}, {} }};
</code>```

I've reason to believe that something like this is going to come up on an exam eventually but in +10 years of coding, I've never seen such a horror. I sure could use some tips for mentally parsing this, so that I can figure out what it really means in my head. Sure, I could run it through IntelliJ but I won't have it available.

For the record, this makes perfect sense to me:

```<code>int[][] twoD = { { 1, 2, 3} , { 4, 5, 6, 7}, { 8, 9, 10 } };
</code>```

Body:
String[][][] arr  =
{{ { "a", "b" , "c"}, { "d", "e", null } },{ {"x"}, null },{{"y"}},{ { "z","p"}, {} }};

I've reason to believe that something like this is going to come up on an exam eventually but in +10 years of coding, I've never seen such a horror. I sure could use some tips for mentally parsing this, so that I can figure out what it really means in my head. Sure, I could run it through IntelliJ but I won't have it available.

For the record, this makes perfect sense to me:

int[][] twoD = { { 1, 2, 3} , { 4, 5, 6, 7}, { 8, 9, 10 } };

Body:
Maybe you will understand more from this, i can see your array like this :

String[] arr0 = {"a", "b", "c"};
String[] arr1 = {"d", "e", null};
String[] arr2 = {"x"};
String[] arr3 = null;
String[] arr4 = {"y"};
String[] arr5 = {"z", "p"};
String[] arr6 = {};

String[][] arr0_1 = {arr0, arr1};//-->>  {{"a", "b", "c"}, {"d", "e", null}}
String[][] arr2_3 = {arr2, arr3};//-->>  {{"x"}, null}
String[][] arr4_4 = {arr4};      //-->>  {{"y"}}
String[][] arr5_6 = {arr5, arr6};//-->>  {{"z", "p"}, {}}

String[][][] arr = {arr0_1, arr2_3, arr4_4, arr5_6};

which is equivalent to

String[][][] arr
        = {
            {//----------------------------
                {"a", "b", "c"},//arr0    |
                                        //|---->arr0_1
                {"d", "e", null}//arr1    |
            },//---------------------------

            {//----------------------------
                {"x"},//arr2              |
                                        //|---->arr2_3
                null  //arr3              |
            },//---------------------------

            {//----------------------------
                {"y"}//arr4               |---->arr4_4
            },//---------------------------

            {//----------------------------
                {"z", "p"},//arr5         |
                                        //|---->arr5_6
                {}//arr6                  |
            }//---------------------------
        };


问:
Getting Unsupported major.minor version 52.0 error for SonarQube with jdk 1.7
I am using SonarQube version 5.5. My SonarQube server is running successfully on http://localhost:9000 on windows 64 bit.

I have one Maven project which is running on jdk 1.7 and its POM with Sonar server configuration is as shown below.

```<code><properties>
 <java-version>1.7</java-version>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<wsdl4j.version>1.4</wsdl4j.version>
<commons-logging.version>1.1.1</commons-logging.version>
<commons-io.version>2.5</commons-io.version>
<sonar.host.url> http://localhost:9000/</sonar.host.url> </properties>
</code>```

When I run mvn sonar:sonar  command, it gives me below error.

```<code>Caused by: java.lang.UnsupportedClassVersionError: org/sonarsource/scanner/maven/SonarQubeMojo : Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClassFromSelf(ClassRealm.java:386)
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:42)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:244)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:230)
    at org.sonatype.guice.bean.reflect.URLClassSpace.loadClass(URLClassSpace.java:101)
</code>```

I understand its java version issue but not able to figure out the solution.

Did any one face such an issue ?

答: The SonarQube Maven plugin being used supports only Java 8+. You should force an older version of org.codehaus.mojo:sonar-maven-plugin in your pom or in the command-line.</p>

Body:
I am using SonarQube version 5.5. My SonarQube server is running successfully on http://localhost:9000 on windows 64 bit.

I have one Maven project which is running on jdk 1.7 and its POM with Sonar server configuration is as shown below.

<properties>
 <java-version>1.7</java-version>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<wsdl4j.version>1.4</wsdl4j.version>
<commons-logging.version>1.1.1</commons-logging.version>
<commons-io.version>2.5</commons-io.version>
<sonar.host.url> http://localhost:9000/</sonar.host.url> </properties>

When I run mvn sonar:sonar  command, it gives me below error.

Caused by: java.lang.UnsupportedClassVersionError: org/sonarsource/scanner/maven/SonarQubeMojo : Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClassFromSelf(ClassRealm.java:386)
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:42)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:244)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:230)
    at org.sonatype.guice.bean.reflect.URLClassSpace.loadClass(URLClassSpace.java:101)

I understand its java version issue but not able to figure out the solution.

Did any one face such an issue ?


问:
Sending an array as a server tag's property
I am wondering if it's possible to send an array of strings to a tag's property

```<code><SampleTag:Form
  runat="server"
  ID="sampleform1"
  Items={item1,item2,item3,item4}
>
</SampleTag:Form>
</code>```

This doesn't work since it sends "{item1,item2,item3,item4}" as a string to the class.

答:
I know you already accepted an answer, but I wanted to let you know it's possible to do what you are trying to do using a type converter.  I prefer this method as it makes the control more designer friendly and easier for others to use.

Use: (sorry for the VB code...)

```<code><cc1:ServerControl1 ID="ServerControl11" runat="server" Items="Testing,Test2,Test3,Test4,Test5" />
</code>```

Code:

The key is the use of the TypeConverter attribute on the property (see after this class for the definition).

```<code>Public Class ServerControl1
    Inherits WebControl

    <TypeConverter(GetType(StringToArray))> _
    Public Property Items() As String()
        Get
            If ViewState("Items") IsNot Nothing Then
                Return ViewState("Items")
            Else
                Return New String() {}
            End If
        End Get
        Set(ByVal value As String())
            ViewState("Items") = value
        End Set
    End Property

    Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
        MyBase.Render(writer)

        For Each s As String In Items
            writer.Write(String.Format("-{0}<br/>", s))
        Next
    End Sub
End Class

Public Class StringToArray
    Inherits TypeConverter

    Public Overloads Overrides Function CanConvertFrom(ByVal context As ITypeDescriptorContext, ByVal sourceType As Type) As Boolean
        If sourceType Is GetType(String) Then
            Return True
        End If
        Return MyBase.CanConvertFrom(context, sourceType)
    End Function

    Public Overloads Overrides Function ConvertFrom(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object) As Object
        If TypeOf value Is String Then
            Dim v As String() = CStr(value).Split(New Char() {","c})
            Return v
        End If
        Return MyBase.ConvertFrom(context, culture, value)
    End Function
End Class
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am wondering if it's possible to send an array of strings to a tag's property

<SampleTag:Form
  runat="server"
  ID="sampleform1"
  Items={item1,item2,item3,item4}
>
</SampleTag:Form>

This doesn't work since it sends "{item1,item2,item3,item4}" as a string to the class.

Body:
I know you already accepted an answer, but I wanted to let you know it's possible to do what you are trying to do using a type converter.  I prefer this method as it makes the control more designer friendly and easier for others to use.

Use: (sorry for the VB code...)

<cc1:ServerControl1 ID="ServerControl11" runat="server" Items="Testing,Test2,Test3,Test4,Test5" />

Code:

The key is the use of the TypeConverter attribute on the property (see after this class for the definition).

Public Class ServerControl1
    Inherits WebControl

    <TypeConverter(GetType(StringToArray))> _
    Public Property Items() As String()
        Get
            If ViewState("Items") IsNot Nothing Then
                Return ViewState("Items")
            Else
                Return New String() {}
            End If
        End Get
        Set(ByVal value As String())
            ViewState("Items") = value
        End Set
    End Property

    Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
        MyBase.Render(writer)

        For Each s As String In Items
            writer.Write(String.Format("-{0}<br/>", s))
        Next
    End Sub
End Class

Public Class StringToArray
    Inherits TypeConverter

    Public Overloads Overrides Function CanConvertFrom(ByVal context As ITypeDescriptorContext, ByVal sourceType As Type) As Boolean
        If sourceType Is GetType(String) Then
            Return True
        End If
        Return MyBase.CanConvertFrom(context, sourceType)
    End Function

    Public Overloads Overrides Function ConvertFrom(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object) As Object
        If TypeOf value Is String Then
            Dim v As String() = CStr(value).Split(New Char() {","c})
            Return v
        End If
        Return MyBase.ConvertFrom(context, culture, value)
    End Function
End Class


问:
jQuery Show/Hide multiple galleries
I have three galleries on a page and want them to show with simple jQuery show/hide technique.

Gallery works perfect, but maybe there are some more preview galleries to display in the future.

What I have done so far:

```<code>$(document).ready(function(){

$('#gallery1').click(function() {
  $('#gallery').hide();
  $('#previewGallery1').show();
});

$('#showGallery1').click(function() {
  $('#gallery').show();
  $('#previewGallery1').hide();
});

$('#gallery2').click(function() {
  $('#gallery').hide();
  $('#previewGallery2').show();
});

$('#showGallery2').click(function() {
  $('#gallery').show();
  $('#previewGallery2').hide();
});

$('#gallery3').click(function() {
  $('#gallery').hide();
  $('#previewGallery3').show();
});

$('#showGallery3').click(function() {
  $('#gallery').show();
  $('#previewGallery3').hide();
});

});
</code>```

https://jsfiddle.net/stef75/ah3Lxkdy/

Need some help to add more generic code here :)

Thx in advance!

答:
You can do it using html data attributes

$(document).ready(function(){

  $("[data-show-gallery]").click(function() {
    $('[data-gallery-preview]').hide(); // feel free to use a class here insted
    $('[data-gallery='+$(this).attr("data-show-gallery")+']').show();
  });

  $("[data-close-gallery]").click(function() {// feel free to use a class here insted
    $('[data-gallery-preview]').show(); // feel free to use a class here insted
    $('[data-gallery]').hide(); // feel free to use a class here insted
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#gallery {
    background: orange;
    width: 100%;
  }

  .previewImage {
    border: 1px solid red;
    background: green;
    height: 250px;
    width: 30%;
    margin: 1%;
    float: left;
    cursor: pointer;
  }

  .previewGallery {
    margin: 1%;
    background: blue;
  }

  [data-gallery] {
    display: none;
  }

  .previewThumb {
    background: orange;
    float: left;
    width: 150px;
    height: 150px;
    margin: 1%;
  }

a { color: #fff; }</code>```

Above gallery...

Preview-Image Gallery 1

Preview-Image Gallery 2

Preview-Image Gallery 3

Preview-Gallery 1

thumb 1

thumb 2

thumb 3

thumb 4

thumb 5

thumb 6

    << back

Preview-Gallery 2

thumb 1

thumb 2

thumb 3

thumb 4

thumb 5

thumb 6

    << back

Preview-Gallery 3

thumb 1

thumb 2

thumb 3

thumb 4

thumb 5

thumb 6

    << back

Below gallery...
```

Title: jQuery Show/Hide multiple galleries

Body:
I have three galleries on a page and want them to show with simple jQuery show/hide technique.

Gallery works perfect, but maybe there are some more preview galleries to display in the future.

What I have done so far:

$(document).ready(function(){

$('#gallery1').click(function() {
  $('#gallery').hide();
  $('#previewGallery1').show();
});

$('#showGallery1').click(function() {
  $('#gallery').show();
  $('#previewGallery1').hide();
});

$('#gallery2').click(function() {
  $('#gallery').hide();
  $('#previewGallery2').show();
});

$('#showGallery2').click(function() {
  $('#gallery').show();
  $('#previewGallery2').hide();
});

$('#gallery3').click(function() {
  $('#gallery').hide();
  $('#previewGallery3').show();
});

$('#showGallery3').click(function() {
  $('#gallery').show();
  $('#previewGallery3').hide();
});

});

https://jsfiddle.net/stef75/ah3Lxkdy/

Need some help to add more generic code here :)

Thx in advance!

Body:
You can do it using html data attributes

$(document).ready(function(){

  $("[data-show-gallery]").click(function() {
    $('[data-gallery-preview]').hide(); // feel free to use a class here insted
    $('[data-gallery='+$(this).attr("data-show-gallery")+']').show();
  });

  $("[data-close-gallery]").click(function() {// feel free to use a class here insted
    $('[data-gallery-preview]').show(); // feel free to use a class here insted
    $('[data-gallery]').hide(); // feel free to use a class here insted
  });

});

#gallery {
    background: orange;
    width: 100%;
  }

  .previewImage {
    border: 1px solid red;
    background: green;
    height: 250px;
    width: 30%;
    margin: 1%;
    float: left;
    cursor: pointer;
  }

  .previewGallery {
    margin: 1%;
    background: blue;
  }

  [data-gallery] {
    display: none;
  }

  .previewThumb {
    background: orange;
    float: left;
    width: 150px;
    height: 150px;
    margin: 1%;
  }

a { color: #fff; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Above gallery...</div>

<div id="gallery" data-gallery-preview>
  <div class="previewImage" data-show-gallery="1">Preview-Image Gallery 1</div>
  <div class="previewImage" data-show-gallery="2">Preview-Image Gallery 2</div>
  <div class="previewImage" data-show-gallery="3">Preview-Image Gallery 3</div>
</div>

<div style="clear: both;"></div>

<div data-gallery="1">
  <div class="previewGallery">
    <h2>Preview-Gallery 1</h2>
    <div class="previewThumb">thumb 1</div>
    <div class="previewThumb">thumb 2</div>
    <div class="previewThumb">thumb 3</div>
    <div class="previewThumb">thumb 4</div>
    <div class="previewThumb">thumb 5</div>
    <div class="previewThumb">thumb 6</div>

    <div style="clear: both;"></div>
    <a href="#" data-close-gallery>&lt;&lt; back</a>
  </div>
</div>
<div data-gallery="2">
  <div class="previewGallery">
    <h2>Preview-Gallery 2</h2>
    <div class="previewThumb">thumb 1</div>
    <div class="previewThumb">thumb 2</div>
    <div class="previewThumb">thumb 3</div>
    <div class="previewThumb">thumb 4</div>
    <div class="previewThumb">thumb 5</div>
    <div class="previewThumb">thumb 6</div>
    <div style="clear: both;"></div>
    <a href="#" data-close-gallery>&lt;&lt; back</a>
  </div>
</div>
<div data-gallery="3">
  <div class="previewGallery">
    <h2>Preview-Gallery 3</h2>
    <div class="previewThumb">thumb 1</div>
    <div class="previewThumb">thumb 2</div>
    <div class="previewThumb">thumb 3</div>
    <div class="previewThumb">thumb 4</div>
    <div class="previewThumb">thumb 5</div>
    <div class="previewThumb">thumb 6</div>
    <div style="clear: both;"></div>
    <a href="#" data-close-gallery>&lt;&lt; back</a>
  </div>
</div>

<div>Below gallery...</div>


问:
SAVE attribute needed for Fortran variables when only the C_LOC address is returned to a C program?
Normally, the SAVE attribute is used in Fortran type declarations so that the variable retains its value at the end of a subprogram, such as described by the answers to the SO question here. However, I recently gave an example at another question for how a Fortran function can be written that returns only the C address of an allocatable character string constant to a C calling program, with the C_LOC intrinsic and other ISO_C_BINDING features of F2003. Should the SAVE attribute be used on the Fortran allocatable string constant to avoid potential issues?

Although I didn't use SAVE, the function worked as intended: the C program uses a char* to point at the address returned by the Fortran function, which could then be used as normal (e.g., for printing and with strlen()). No warnings/errors were generated. Also, this seems consistent with how I have seen C_F_POINTER used in the compiler docs and the examples at a related SO question (that is, the target values did not have the SAVE attr).

Particularly since the Fortran function was called from C, it's not clear to me whether this process exhibits the expected behavior, or if it could/should have failed, or if this is a vendor-specific implementation detail. The Intel Fortran 17 documentation for SAVE (here) seems to indicate that a string constant (allocatable or not?) is saved by default, but I am not sure if I'm reading this right, or how/if this info holds up in the current context. Am I performing this process in a portable, correct manner?

Although I linked to the code already, here are the important bits:

```<code>! f_string.f90: returns the C address to an allocatable string constant:
function get_string() bind(c, name='get_string')
    use, intrinsic :: iso_c_binding
    implicit none
    type(C_PTR) :: get_string
    character(len=:), allocatable, target :: fortstring  ! <- Include SAVE?

    fortstring = "Hello StackOverflow" // C_NULL_CHAR    ! <- NULL-terminated string constant
    get_string = C_LOC(fortstring)
end function get_string
</code>```

```<code>// c_string.c: uses a char* to point at the address returned by 'get_string'
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *get_string(void);                                  // <- Fortran fcn signature
int main(){
    char *mycharptr;

    mycharptr = get_string();
    printf("String from Fortran: %s\n", mycharptr);
    printf("len = %d\n", strlen(mycharptr));
    return 0;
}
</code>```

Compiled as ifort /c f_string.f90, icl c_string /link f_string.obj.

答:
That is correct. Save is necessary.

All allocatable entities are deallocated when the procedure exits unless they are save.

You can use pointer instead of allocatable and the target will not be automatically deallocated. I find it better than save because of possible multiple calls to the procedure.

Your program probably "worked" because although the memory block was deallocated, it was not overwritten. So the C procedure still found meaningful data, but at address it was not allowed to access. But this access is not always checked by the OS memory protection.

Body:
Normally, the SAVE attribute is used in Fortran type declarations so that the variable retains its value at the end of a subprogram, such as described by the answers to the SO question here. However, I recently gave an example at another question for how a Fortran function can be written that returns only the C address of an allocatable character string constant to a C calling program, with the C_LOC intrinsic and other ISO_C_BINDING features of F2003. Should the SAVE attribute be used on the Fortran allocatable string constant to avoid potential issues?

Although I didn't use SAVE, the function worked as intended: the C program uses a char* to point at the address returned by the Fortran function, which could then be used as normal (e.g., for printing and with strlen()). No warnings/errors were generated. Also, this seems consistent with how I have seen C_F_POINTER used in the compiler docs and the examples at a related SO question (that is, the target values did not have the SAVE attr).

Particularly since the Fortran function was called from C, it's not clear to me whether this process exhibits the expected behavior, or if it could/should have failed, or if this is a vendor-specific implementation detail. The Intel Fortran 17 documentation for SAVE (here) seems to indicate that a string constant (allocatable or not?) is saved by default, but I am not sure if I'm reading this right, or how/if this info holds up in the current context. Am I performing this process in a portable, correct manner?

Although I linked to the code already, here are the important bits:

! f_string.f90: returns the C address to an allocatable string constant:
function get_string() bind(c, name='get_string')
    use, intrinsic :: iso_c_binding
    implicit none
    type(C_PTR) :: get_string
    character(len=:), allocatable, target :: fortstring  ! <- Include SAVE?

    fortstring = "Hello StackOverflow" // C_NULL_CHAR    ! <- NULL-terminated string constant
    get_string = C_LOC(fortstring)
end function get_string

// c_string.c: uses a char* to point at the address returned by 'get_string'
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *get_string(void);                                  // <- Fortran fcn signature
int main(){
    char *mycharptr;

    mycharptr = get_string();
    printf("String from Fortran: %s\n", mycharptr);
    printf("len = %d\n", strlen(mycharptr));
    return 0;
}

Compiled as ifort /c f_string.f90, icl c_string /link f_string.obj.


问:
RxJava combinator for combining maps?
I have a Map of tasks like this:

```<code>Map<Identifier, Observable<Progress>> tasks;
</code>```

I would like to transform this to:

```<code>Observable<Map<Identifier, Progress>>
</code>```

Where each Map<Identifier, Progress> element contains the latest element from each task.

I want the new Observable to complete only when all tasks have completed, and fail when any one of the tasks fails.

Is there a combinator for this?

答:
To transform single Map<Identifier, Observable<Progress>> task to <Identifier, Progress> use:

```<code>Observable.just(Identifier)
    .flatMap(Observable<Progress> progressObservable,
        (Identifier, Progress, Pair<Identifier, Progress>) -> {create pair of elements})
</code>```

To combine those tasks together, use combineLatest operator

```<code>Observable.combineLatest(List<Observable<Pair<Identifier, Progress>>>,
    (List<Pair<Identifier, Progress>>) -> {merge into `Map`})
</code>```

I hope I get your idea well. OF course, written in pseudocode.

An implementation:

```<code>public static <T, S> Observable<Map<T, S>> zipMaps(final Map<T, Observable<S>> tasks) {
    Objects.requireNonNull(tasks, "tasks is null");
    return Observable.combineLatest(
        tasks.entrySet()
            .stream()
            .map(entry -> Observable.combineLatest(
                Observable.just(entry.getKey()),
                entry.getValue(),
                Pair::with))
            .collect(ImmutableList.toImmutableList()),
        xs -> Arrays.stream(xs)
            .map(x -> (Pair<T, S>)x)
            .collect(ImmutableMap.toImmutableMap(Pair::getValue0, Pair::getValue1)));
}
</code>```

Title: RxJava combinator for combining maps?

Body:
I have a Map of tasks like this:

Map<Identifier, Observable<Progress>> tasks;

I would like to transform this to:

Observable<Map<Identifier, Progress>>

Where each Map<Identifier, Progress> element contains the latest element from each task.

I want the new Observable to complete only when all tasks have completed, and fail when any one of the tasks fails.

Is there a combinator for this?

Body:
To transform single Map<Identifier, Observable<Progress>> task to <Identifier, Progress> use:

Observable.just(Identifier)
    .flatMap(Observable<Progress> progressObservable,
        (Identifier, Progress, Pair<Identifier, Progress>) -> {create pair of elements})

To combine those tasks together, use combineLatest operator

Observable.combineLatest(List<Observable<Pair<Identifier, Progress>>>,
    (List<Pair<Identifier, Progress>>) -> {merge into `Map`})

I hope I get your idea well. OF course, written in pseudocode.

An implementation:

public static <T, S> Observable<Map<T, S>> zipMaps(final Map<T, Observable<S>> tasks) {
    Objects.requireNonNull(tasks, "tasks is null");
    return Observable.combineLatest(
        tasks.entrySet()
            .stream()
            .map(entry -> Observable.combineLatest(
                Observable.just(entry.getKey()),
                entry.getValue(),
                Pair::with))
            .collect(ImmutableList.toImmutableList()),
        xs -> Arrays.stream(xs)
            .map(x -> (Pair<T, S>)x)
            .collect(ImmutableMap.toImmutableMap(Pair::getValue0, Pair::getValue1)));
}


问:
disable weekend dates on angular bootstrap datepicker using custom directive
I'm using Angular bootstrap datapicker plugin in my angular app.

I've written a custom directive for the date pickers in my app. And i want to disable the weekends in the date picker at certain places. I've given the functions that disables the weekend dates inside the directive itself.

The function to disable the weekend dates works fine when it is not used inside the directive.

My custom directive:

```<code>app.directive('datePic', function(){
      return {
        restrict: 'E',
        scope: {
          control: "=ngModel",
          min: "=minDate",
          max: "=maxDate",
          disable: "&dateDisabled"
        },
        template: '<div class="col-sm-6"><div class="input-group"><input type="text" class="form-control" datepicker-popup is-open="opened1" ng-model="control" min-date="min" max-date="max" date-disabled="disable" close-text="Close" /><span class="input-group-btn"><button type="button" id="btn2" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button></span></div></div>',
        link: function(scope, elem, attrs){
          scope.open = function($event) {
            $event.preventDefault();
            $event.stopPropagation();
            scope.opened1 = true;
          };

          scope.disabled = function(date, mode) {
            return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));
          };

          scope.toggleMin = function() {
            scope.minDate = scope.minDate ? null : new Date();
          };
           scope.toggleMin();
        }
      }
    })
</code>```

HTML:

```<code><div class="form-group has-feedback">
<label for="inputEmail3" class="col-sm-3 control-label"><span>*</span>From :</label>
<date-pic ng-model="data.leaveFromDate" min-date="minDate" max-date="maxdate" date-disabled="disabled(date, mode)"></date-pic>
</div>

<div class="form-group has-feedback">
<label for="inputEmail3" class="col-sm-3 control-label"><span>*</span>To :</label>
<date-pic ng-model="data.leaveToDate" min-date="data.leaveFromDate" max-date="data.leaveToDate" date-disabled="disabled(date, mode)"></date-pic>
</div>
</code>```

I dont know how to pass date-disabled="disabled(date, mode)" into the directive so that it is possible to disable weekend dates dynamically.

I have assigned date-disabled inside the directive as disable: "&dateDisabled" and used it in the template as date-disabled="disable".

Any suggestions or guidance much appreciated.

Thank you in advance.

答:
```<code><script language="javascript" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"></script>
</code>```

enter code here

```<code> <div ng-app="myApp" ng-controller="myCntrl">
  From Date:
    <input type="text" uib-datepicker-popup="{{dateformat}}" min-date="mindate" ng-model="dt" is-open="showdp"
    date-disabled="disabled(date, mode)" />

    <span>
        <button type="button" class="btn btn-default" ng-click="showcalendar($event)">
            <i class="glyphicon glyphicon-calendar"></i>
        </button>
    </span>
</div>
<script language="javascript">
    angular.module('myApp', ['ngAnimate', 'ui.bootstrap']);
    angular.module('myApp').controller('myCntrl', function ($scope) {
        $scope.today = function () {
            $scope.dt = new Date();
        };
        $scope.mindate = new Date();
        $scope.dateformat="dd/MM/yyyy";
        $scope.today();
        $scope.showcalendar = function ($event) {
            $scope.showdp = true;
        };
        $scope.showdp = false;
        $scope.disabled = function (date, mode) {
return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));
</code>```

};

```<code>    });
</script>
</form>
</code>```

Body:
I'm using Angular bootstrap datapicker plugin in my angular app.

I've written a custom directive for the date pickers in my app. And i want to disable the weekends in the date picker at certain places. I've given the functions that disables the weekend dates inside the directive itself.

The function to disable the weekend dates works fine when it is not used inside the directive.

My custom directive:

app.directive('datePic', function(){
      return {
        restrict: 'E',
        scope: {
          control: "=ngModel",
          min: "=minDate",
          max: "=maxDate",
          disable: "&dateDisabled"
        },
        template: '

<input type="text" class="form-control" datepicker-popup is-open="opened1" ng-model="control" min-date="min" max-date="max" date-disabled="disable" close-text="Close" /><button type="button" id="btn2" class="btn btn-default" ng-click="open($event)"></button>

',
        link: function(scope, elem, attrs){
          scope.open = function($event) {
            $event.preventDefault();
            $event.stopPropagation();
            scope.opened1 = true;
          };

          scope.disabled = function(date, mode) {
            return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));
          };

          scope.toggleMin = function() {
            scope.minDate = scope.minDate ? null : new Date();
          };
           scope.toggleMin();
        }
      }
    })

HTML:

*From :
<date-pic ng-model="data.leaveFromDate" min-date="minDate" max-date="maxdate" date-disabled="disabled(date, mode)"></date-pic>

*To :
<date-pic ng-model="data.leaveToDate" min-date="data.leaveFromDate" max-date="data.leaveToDate" date-disabled="disabled(date, mode)"></date-pic>

I dont know how to pass date-disabled="disabled(date, mode)" into the directive so that it is possible to disable weekend dates dynamically.

I have assigned date-disabled inside the directive as disable: "&dateDisabled" and used it in the template as date-disabled="disable".

Any suggestions or guidance much appreciated.

Thank you in advance.

Body:
<script language="javascript" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"></script>

enter code here

 <div ng-app="myApp" ng-controller="myCntrl">
  From Date:
    <input type="text" uib-datepicker-popup="{{dateformat}}" min-date="mindate" ng-model="dt" is-open="showdp"
    date-disabled="disabled(date, mode)" />

    <span>
        <button type="button" class="btn btn-default" ng-click="showcalendar($event)">
            <i class="glyphicon glyphicon-calendar"></i>
        </button>
    </span>
</div>
<script language="javascript">
    angular.module('myApp', ['ngAnimate', 'ui.bootstrap']);
    angular.module('myApp').controller('myCntrl', function ($scope) {
        $scope.today = function () {
            $scope.dt = new Date();
        };
        $scope.mindate = new Date();
        $scope.dateformat="dd/MM/yyyy";
        $scope.today();
        $scope.showcalendar = function ($event) {
            $scope.showdp = true;
        };
        $scope.showdp = false;
        $scope.disabled = function (date, mode) {
return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));

};

    });
</script>
</form>


问:
Hover over an image in one column to make text appear in a different column
Apologies as I know this question has been asked in various different forms, but I can't find an answer to my exact problem - at least not one that I understand!

I'm very new to programming, and am currently building myself a webpage for my wedding cake business to try and familiarise myself with HTML, CSS and a bit of JavaScript and JQuery. I have a list of thumbnail images in one column, which I added "onmouseover" to so that when hovered over (in addition to a css transition) they display a large version of themselves in a central column. I want to also display information about each cake in a third column to the right hand side of the main image but I have no idea how to go about doing this!

```<code><div class="col-md-3">
<ul class="cake-thumbs">
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img10" src="Resources/img/10.jpg" alt="Pastel Pink Placard and Pearls">
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img11" src="Resources/img/11.jpg" alt="Naked Wedding Cake with fresh fruit">
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img12" src="Resources/img/12.jpg" alt="Gold Damask and Pearls">
        </figure>
    </li>
</ul>
</div>
<div class="col-md-6">
        <img id="preview" src="Resources/img/1.jpg" alt="">
</div>
<div class="col-md-3">
    <p id="info">Price and servings here</p>
</div>
</code>```

答:
The issue is missing document. at getElementById()

Price and servings here

```

Body:
Apologies as I know this question has been asked in various different forms, but I can't find an answer to my exact problem - at least not one that I understand!

I'm very new to programming, and am currently building myself a webpage for my wedding cake business to try and familiarise myself with HTML, CSS and a bit of JavaScript and JQuery. I have a list of thumbnail images in one column, which I added "onmouseover" to so that when hovered over (in addition to a css transition) they display a large version of themselves in a central column. I want to also display information about each cake in a third column to the right hand side of the main image but I have no idea how to go about doing this!

Price and servings here

Body:
The issue is missing document. at getElementById()

<div class="col-md-3">
<ul class="cake-thumbs">
    <li>
        <figure class="cake-img">
            <img onmouseover="document.getElementById('preview').src=this.src" id="img10" src="http://lorempixel.com/50/50/city" alt="Pastel Pink Placard and Pearls">
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img onmouseover="document.getElementById('preview').src=this.src" id="img11" src="http://lorempixel.com/50/50/sports" alt="Naked Wedding Cake with fresh fruit">
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img onmouseover="document.getElementById('preview').src=this.src" id="img12" src="http://lorempixel.com/50/50/cats" alt="Gold Damask and Pearls">
        </figure>
    </li>
</ul>
</div>
<div class="col-md-6">
        <img id="preview" src="http://lorempixel.com/50/50/nature" alt="">
</div>
<div class="col-md-3">
    <p id="info">Price and servings here</p>
</div>