问:
Hibernate Configuration, Exception encountered during context initialization, Errors with HomeController and sessionFactory
First of all, I am recently trying to improve myself in JAVA EE. And there is another topic, actually the same problem as mine. But the solution did not work for me. Here is the link of that topic:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory

Also another topic is:
java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration

Anyways I will provide the errors I am facing with,

Error Message:

Org.springframework.beans.factory.UnsatisfiedDependencyException: Error >creating bean with name 'homeController': Unsatisfied dependency expressed >through field 'productDao;

nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Failed to introspect bean class

Here is HomeController:

```<code>package com.emusicstore.controller;

import com.emusicstore.dao.ProductDao;
import com.emusicstore.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.util.List;

@Controller
public class HomeController {

    @Autowired
    private ProductDao productDao;

    @RequestMapping("/")
    public String home(){
        return "home";
    }

    @RequestMapping("/productList")
    public String getProducts(Model model) {
        List<Product> products = productDao.getAllProducts();
        model.addAttribute("products", products);

        return "productList";
    }

    @RequestMapping("/productList/viewProduct/{productId}")
    public String viewProduct(@PathVariable String productId, Model model) throws IOException {
        Product product = productDao.getProductById(productId);
        model.addAttribute(product);
        return "viewProduct";
    }
}
</code>```

Pom.xml :

```<code><groupId>com.mywebsite</groupId>
<artifactId>emusicstore</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.0.1.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.1.Final</version>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.195</version>
    </dependency>

    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>

</dependencies>
</code>```

ApplicationContext.xml:

```<code>    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:tcp://localhost/~/test" />
    <property name="username" value="sa" />
    <property name="password" value="" />
 </bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
    <property name="dataSource" ref="dataSource"></property>
    <property name="hibernateProperties" >

        <props>
            <prop key="hibernate.dialect"> org.hibernate.dialect.H2Dialect</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.show_sql" >true</prop>
            <prop key="hibernate.format_sql">true</prop>
        </props>
    </property>

    <property name="packagesToScan">
        <list>
            <value>com.emusicstore</value>
        </list>
    </property>

</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" >
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
</code>```

The things that I have tried:

register bean object in applicationContext.xml

bean id="productDao" class="com.emusicstore.dao.impl.ProductDaoImpl" />

Annotating ProductDao class with @Component

Adding Hibernate Core jar file to Project Structure

Here is also the pic of my Project Structure: Project Structure

Full error stack:

```<code>WARNING [RMI TCP Connection(3)-127.0.0.1]
org.springframework.web.context.support.XmlWebApplicationContext.refresh
Exception encountered during context initialization - cancelling refresh
attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'homeController': Unsatisfied dependency
expressed through field 'productDao'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'sessionFactory': Failed to introspect bean class
[org.springframework.orm.hibernate4.LocalSessionFactoryBean] for lookup
method metadata: could not find class that it depends on; nested
exception is java.lang.NoClassDefFoundError: org/hibernate
/cfg/Configuration

SEVERE [RMI TCP Connection(3)-127.0.0.1]
org.springframework.web.context.ContextLoader.initWebApplicationContext
Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'homeController': Unsatisfied dependency
expressed through field 'productDao';
nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'sessionFactory':
Failed to introspect bean class
[org.springframework.orm.hibernate4.LocalSessionFactoryBean] for lookup
method metadata:
could not find class that it depends on; nested exception is
java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration
</code>```

答:
try to add

```<code><dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-tools</artifactId>
    <version>4.0.1.Final</version>
</dependency>
</code>```

to you pom.xml file

Body:
First of all, I am recently trying to improve myself in JAVA EE. And there is another topic, actually the same problem as mine. But the solution did not work for me. Here is the link of that topic:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory

Also another topic is:
java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration

Anyways I will provide the errors I am facing with,

Error Message:

Org.springframework.beans.factory.UnsatisfiedDependencyException: Error >creating bean with name 'homeController': Unsatisfied dependency expressed >through field 'productDao;

nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Failed to introspect bean class

Here is HomeController:

package com.emusicstore.controller;

import com.emusicstore.dao.ProductDao;
import com.emusicstore.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.util.List;

@Controller
public class HomeController {

    @Autowired
    private ProductDao productDao;

    @RequestMapping("/")
    public String home(){
        return "home";
    }

    @RequestMapping("/productList")
    public String getProducts(Model model) {
        List<Product> products = productDao.getAllProducts();
        model.addAttribute("products", products);

        return "productList";
    }

    @RequestMapping("/productList/viewProduct/{productId}")
    public String viewProduct(@PathVariable String productId, Model model) throws IOException {
        Product product = productDao.getProductById(productId);
        model.addAttribute(product);
        return "viewProduct";
    }
}

Pom.xml :

<groupId>com.mywebsite</groupId>
<artifactId>emusicstore</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.0.1.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.1.Final</version>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.195</version>
    </dependency>

    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>

</dependencies>

ApplicationContext.xml:

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:tcp://localhost/~/test" />
    <property name="username" value="sa" />
    <property name="password" value="" />
 </bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
    <property name="dataSource" ref="dataSource"></property>
    <property name="hibernateProperties" >

        <props>
            <prop key="hibernate.dialect"> org.hibernate.dialect.H2Dialect</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.show_sql" >true</prop>
            <prop key="hibernate.format_sql">true</prop>
        </props>
    </property>

    <property name="packagesToScan">
        <list>
            <value>com.emusicstore</value>
        </list>
    </property>

</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" >
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

The things that I have tried:

register bean object in applicationContext.xml

bean id="productDao" class="com.emusicstore.dao.impl.ProductDaoImpl" />

Annotating ProductDao class with @Component

Adding Hibernate Core jar file to Project Structure

Here is also the pic of my Project Structure: Project Structure

Full error stack:

WARNING [RMI TCP Connection(3)-127.0.0.1]
org.springframework.web.context.support.XmlWebApplicationContext.refresh
Exception encountered during context initialization - cancelling refresh
attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'homeController': Unsatisfied dependency
expressed through field 'productDao'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'sessionFactory': Failed to introspect bean class
[org.springframework.orm.hibernate4.LocalSessionFactoryBean] for lookup
method metadata: could not find class that it depends on; nested
exception is java.lang.NoClassDefFoundError: org/hibernate
/cfg/Configuration

SEVERE [RMI TCP Connection(3)-127.0.0.1]
org.springframework.web.context.ContextLoader.initWebApplicationContext
Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'homeController': Unsatisfied dependency
expressed through field 'productDao';
nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'sessionFactory':
Failed to introspect bean class
[org.springframework.orm.hibernate4.LocalSessionFactoryBean] for lookup
method metadata:
could not find class that it depends on; nested exception is
java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration

Body:
try to add

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-tools</artifactId>
    <version>4.0.1.Final</version>
</dependency>

to you pom.xml file


来源: stackexchange

问:
Need help to handle this error: Variable 'x' used before being initialized
I have a problem in Swift whit optional function param. I want to set an value for an SKSpriteNote within a function, but this value dos not exist before the function is called, so i obviously get an error ;/

Can anyone please tell me what to do, to solve this?

THIS IS THE ERROR I GET:
Variable 'bought_ingredient_market_graphic' used before being initialized

THIS IS MY FUNCTION (see

```<code>func show_market_graphic(x: CGFloat, y: CGFloat, level: String, ingredient: String?){

    var market_graphic: SKSpriteNode

    var bought_ingredient_market_graphic: SKSpriteNode

    if(level == "locked"){

        market_graphic = SKSpriteNode(imageNamed: "locked_ingredient")

    } else {

        market_graphic = SKSpriteNode(imageNamed: "bought_ingredient")

        bought_ingredient_market_graphic = SKSpriteNode(imageNamed: ingredient!)
    }

    market_graphic.zPosition = 10

    market_graphic.position = CGPoint(x: x, y: y)

    addChild(market_graphic)

    if(level != "locked"){
        // * ERROR ON LINE BELOW
        bought_ingredient_market_graphic.zPosition = 20
        // * ERROR ON LINE BELOW
        bought_ingredient_market_graphic.position = market_graphic.position
        // * ERROR ON LINE BELOW
        addChild(bought_ingredient_market_graphic)
    }
}
</code>```

答:
Your code should work in principle, the compiler fails to detect the corelation between level == "locked" and level != "locked".

I assume that the compiler sees a risk that the value of level could change betwwen the statelents.  So the best way would be to initialize bought_ingredient_market_graphic in the first if-clause.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem in Swift whit optional function param. I want to set an value for an SKSpriteNote within a function, but this value dos not exist before the function is called, so i obviously get an error ;/

Can anyone please tell me what to do, to solve this?

THIS IS THE ERROR I GET:
Variable 'bought_ingredient_market_graphic' used before being initialized

THIS IS MY FUNCTION (see

func show_market_graphic(x: CGFloat, y: CGFloat, level: String, ingredient: String?){

    var market_graphic: SKSpriteNode

    var bought_ingredient_market_graphic: SKSpriteNode

    if(level == "locked"){

        market_graphic = SKSpriteNode(imageNamed: "locked_ingredient")

    } else {

        market_graphic = SKSpriteNode(imageNamed: "bought_ingredient")

        bought_ingredient_market_graphic = SKSpriteNode(imageNamed: ingredient!)
    }

    market_graphic.zPosition = 10

    market_graphic.position = CGPoint(x: x, y: y)

    addChild(market_graphic)

    if(level != "locked"){
        // * ERROR ON LINE BELOW
        bought_ingredient_market_graphic.zPosition = 20
        // * ERROR ON LINE BELOW
        bought_ingredient_market_graphic.position = market_graphic.position
        // * ERROR ON LINE BELOW
        addChild(bought_ingredient_market_graphic)
    }
}


问:
Correlation matrix in panel data in R
I have a time-series panel dataset which is structured in the following way:

df <- data.frame(
  year = c(2012L, 2013L, 2014L, 2012L, 2013L, 2014L),
  id = c(1L, 1L, 1L, 2L, 2L, 2L),
  c = c(11L, 13L, 13L, 16L, 15L, 15L)
)

#>   year id  c
#> 1 2012  1 11
#> 2 2013  1 13
#> 3 2014  1 13
#> 4 2012  2 16
#> 5 2013  2 15
#> 6 2014  2 15
```

<p>I would like to find the cross-correlation between values in column C given their id number.
Something similar to this: </p>

<pre class="lang-r prettyprint-override"><code>#>     1  2
#> 1   1  0.8
#> 2   0.8  1
</code>```

I have been using dplyr package to find the cross-correlation between two variables in my panel data but for some reason, I can't do the same for cross correlation in one veriable grouped by id.

答:
If you are already using tidyverse tools, you should try widyr.

Its functions reshape to wide, get the correlations, and give you back a tidy data frame again.

(Note I changed the sample data slightly to match akaDrHouse's answer.

df <- data.frame(
  year = c(2012L, 2013L, 2014L, 2012L, 2013L, 2014L),
  id = c(1L, 1L, 1L, 2L, 2L, 2L),
  c = c(11L, 13L, 13L, 16L, 15L, 156L)
)

df
#>   year id   c
#> 1 2012  1  11
#> 2 2013  1  13
#> 3 2014  1  13
#> 4 2012  2  16
#> 5 2013  2  15
#> 6 2014  2 156

widyr::pairwise_cor(df, id, year, c)

#> # A tibble: 2 x 3
#>   item1 item2 correlation
#>   <int> <int>       <dbl>
#> 1     2     1   0.4946525
#> 2     1     2   0.4946525

widyr::pairwise_cor(df, id, year, c, upper = FALSE)

#> # A tibble: 1 x 3
#>   item1 item2 correlation
#>   <int> <int>       <dbl>
#> 1     1     2   0.4946525
```

Title: Correlation matrix in panel data in R

Body:
I have a time-series panel dataset which is structured in the following way:

df <- data.frame(
  year = c(2012L, 2013L, 2014L, 2012L, 2013L, 2014L),
  id = c(1L, 1L, 1L, 2L, 2L, 2L),
  c = c(11L, 13L, 13L, 16L, 15L, 15L)
)

#>   year id  c
#> 1 2012  1 11
#> 2 2013  1 13
#> 3 2014  1 13
#> 4 2012  2 16
#> 5 2013  2 15
#> 6 2014  2 15

I would like to find the cross-correlation between values in column C given their id number.
Something similar to this:

#>     1  2
#> 1   1  0.8
#> 2   0.8  1

I have been using dplyr package to find the cross-correlation between two variables in my panel data but for some reason, I can't do the same for cross correlation in one veriable grouped by id.


问:
Redirect HTTP to HTTPS with Ninja framework on Heroku
How to configure a Ninja web application running on Heroku to force the use of SSL, that is, redirect all requests to HTTPS?</p>

答:
If you look good in the ninja framework documentation it is indicated how to configure it to get what you want

http://www.ninjaframework.org/documentation/configuration_and_modes.html


问:
c++ Generic function to divide any data type?
I'm trying to use a single function to divide the usual data types (int, double, float, long, string, char) and having trouble converting a generic string to numeric type. This is what I have so far:</p>

```<code>template <typename T>
T const& Division(T const& a, T const& b)
{
    if (typeid(a) == typeid(string))
    {
        stringstream ss;
        float first, second;
        ss << a;
        ss >> first;
        ss << b;
        ss >> second;

        stringstream output;
        output << first / second;
        T result;
        output >> result;

        return result;
    }
}
</code>```

答:
Since division would always require nuances specific to your type, a generic template function is not a good approach.

But you could overload the division operator on a case by case basis. For example, for a class Foo, make sure that the prototype for this function is in the translation unit prior to use:

```<code>Foo operator/ (const Foo& numerator, const Foo& denominator){
    // ToDo - your code here, and return a newly constructed Foo.
}
</code>```

That will also be syntactically more palatable at the calling site.

Body:
I'm trying to use a single function to divide the usual data types (int, double, float, long, string, char) and having trouble converting a generic string to numeric type. This is what I have so far:

template <typename T>
T const& Division(T const& a, T const& b)
{
    if (typeid(a) == typeid(string))
    {
        stringstream ss;
        float first, second;
        ss <> first;
        ss <> second;

        stringstream output;
        output << first / second;
        T result;
        output >> result;

        return result;
    }
}

Body:
Since division would always require nuances specific to your type, a generic template function is not a good approach.

But you could overload the division operator on a case by case basis. For example, for a class Foo, make sure that the prototype for this function is in the translation unit prior to use:

Foo operator/ (const Foo& numerator, const Foo& denominator){
    // ToDo - your code here, and return a newly constructed Foo.
}

That will also be syntactically more palatable at the calling site.


问:
Transition doesn't work on hover off
i have problem. I wanted to transform div's background when hovering on, it works fine except when i put mouse off the div, the transition doesn't work then. How can i fix this?

When i put mouse off, it instantly changes to original flag.

```<code>$("#flag").hover(function(){
 $(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/EN.png")',
'background-size':'cover',
'transition':'1 s'
 });
}, function(){
$(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/PL.png")',
'background-size':'cover',
'transition':'1 s'
});
})
</code>```

答:
Your code is almost Ok, just change transition part 1 s to 1s . It is a syntax problem:

$("#flag").hover(function(){
 $(this).css({
     'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/EN.png")',
     'background-size':'cover',
     'transition':'3s'
 })}, function(){
 $(this).css({
     'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/PL.png")',
     'background-size':'cover',
     'transition':'3s'
 })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
    width: 100px;
    height: 100px;
    background: grey;
}</code>```

DIV HOVER:

```

Title: Transition doesn't work on hover off

Body:
i have problem. I wanted to transform div's background when hovering on, it works fine except when i put mouse off the div, the transition doesn't work then. How can i fix this?

When i put mouse off, it instantly changes to original flag.

$("#flag").hover(function(){
 $(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/EN.png")',
'background-size':'cover',
'transition':'1 s'
 });
}, function(){
$(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/PL.png")',
'background-size':'cover',
'transition':'1 s'
});
})

Body:
Your code is almost Ok, just change transition part 1 s to 1s . It is a syntax problem:

$("#flag").hover(function(){
 $(this).css({
     'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/EN.png")',
     'background-size':'cover',
     'transition':'3s'
 })}, function(){
 $(this).css({
     'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/PL.png")',
     'background-size':'cover',
     'transition':'3s'
 })
})

div {
    width: 100px;
    height: 100px;
    background: grey;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>DIV HOVER:</p>
<div id="flag"></div>


问:
3d Peek & Pop for search results
I use a Search Bar to filter my Table View. I display the search results in the same view controller that displays the searchable content. It works fine. Except one thing - 3d Peek and Pop is not working for the search results.
I did tried the ‘Peek & Pop’ check box in Storyboard segue. I did tried programming peek & pop in my TableViewController. Result is the same: peek & pop works for table view cells but not for search result cells.

Here is the search and peek & pop code pieces:

```<code>    // Add a search bar
    searchController = UISearchController(searchResultsController: nil)
    tableView.tableHeaderView = searchController.searchBar
    searchController.searchResultsUpdater = self
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    self.tableView.contentOffset = CGPoint(x: 0, y: searchController.searchBar.frame.height)

    // Register for preview
    if traitCollection.forceTouchCapability == .available {
        previewingContext = registerForPreviewing(with: self, sourceView: tableView)
    }

    func updateSearchResults(for searchController: UISearchController) {
        if let searchText = searchController.searchBar.text {
            filterContent(for: searchText)
            tableView.reloadData()
        }
    }

    // MARK: UIViewControllerPreviewingDelegate methods
    func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
        guard let tableView = previewingContext.sourceView as? UITableView,
            let indexPath = tableView.indexPathForRow(at: location),
            let cell = tableView.cellForRow(at: indexPath),
            let detailVC = storyboard?.instantiateViewController(withIdentifier: "AlarmViewController") as? AlarmViewController
        else { return nil }
        detailVC.alarm = alarms[indexPath.row]
        previewingContext.sourceRect = cell.frame
        return detailVC
    }

    func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
        show(viewControllerToCommit, sender: self)
    }
</code>```

Has anyone any ideas how to implement peek & pop for search results?

I guess the main problem is how to register for previewing the UISearchController?..

答:
I made it work. There were couple of 'new kid on the block' mistakes. The correct code:

```<code>// Add a search bar
searchController = UISearchController(searchResultsController: nil)
searchController.loadViewIfNeeded()
tableView.tableHeaderView = searchController.searchBar
searchController.searchResultsUpdater = self
searchController.delegate = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
self.tableView.contentOffset = CGPoint(x: 0, y: searchController.searchBar.frame.height)
// Hide search bar on detailed view and preserve search results
    self.definesPresentationContext = true

// Register for preview
if traitCollection.forceTouchCapability == .available {
    previewingContext = registerForPreviewing(with: self, sourceView: tableView)
}

func updateSearchResults(for searchController: UISearchController) {
    if let searchText = searchController.searchBar.text {
        filterContent(for: searchText)
        tableView.reloadData()
    }
}

// MARK: UIViewControllerPreviewingDelegate methods
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
    guard let tableView = previewingContext.sourceView as? UITableView,
        let indexPath = tableView.indexPathForRow(at: location),
        let cell = tableView.cellForRow(at: indexPath),
        let detailVC = storyboard?.instantiateViewController(withIdentifier: "AlarmViewController") as? AlarmViewController
    else { return nil }
    detailVC.alarm = (searchController.isActive) ? searchResults[(indexPath.row)] : alarms[indexPath.row]
    previewingContext.sourceRect = cell.frame
    return detailVC
}

func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
    show(viewControllerToCommit, sender: self)
}
</code>```

In short:
1) added delegating for searchController
2) using searchResults in UIViewControllerPreviewingDelegate if searchController.isActive

Hope it helps someone.

Title: 3d Peek & Pop for search results

Body:
I use a Search Bar to filter my Table View. I display the search results in the same view controller that displays the searchable content. It works fine. Except one thing - 3d Peek and Pop is not working for the search results.
I did tried the ‘Peek & Pop’ check box in Storyboard segue. I did tried programming peek & pop in my TableViewController. Result is the same: peek & pop works for table view cells but not for search result cells.

Here is the search and peek & pop code pieces:

    // Add a search bar
    searchController = UISearchController(searchResultsController: nil)
    tableView.tableHeaderView = searchController.searchBar
    searchController.searchResultsUpdater = self
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    self.tableView.contentOffset = CGPoint(x: 0, y: searchController.searchBar.frame.height)

    // Register for preview
    if traitCollection.forceTouchCapability == .available {
        previewingContext = registerForPreviewing(with: self, sourceView: tableView)
    }

    func updateSearchResults(for searchController: UISearchController) {
        if let searchText = searchController.searchBar.text {
            filterContent(for: searchText)
            tableView.reloadData()
        }
    }

    // MARK: UIViewControllerPreviewingDelegate methods
    func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
        guard let tableView = previewingContext.sourceView as? UITableView,
            let indexPath = tableView.indexPathForRow(at: location),
            let cell = tableView.cellForRow(at: indexPath),
            let detailVC = storyboard?.instantiateViewController(withIdentifier: "AlarmViewController") as? AlarmViewController
        else { return nil }
        detailVC.alarm = alarms[indexPath.row]
        previewingContext.sourceRect = cell.frame
        return detailVC
    }

    func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
        show(viewControllerToCommit, sender: self)
    }

Has anyone any ideas how to implement peek & pop for search results?

I guess the main problem is how to register for previewing the UISearchController?..

Body:
I made it work. There were couple of 'new kid on the block' mistakes. The correct code:

// Add a search bar
searchController = UISearchController(searchResultsController: nil)
searchController.loadViewIfNeeded()
tableView.tableHeaderView = searchController.searchBar
searchController.searchResultsUpdater = self
searchController.delegate = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
self.tableView.contentOffset = CGPoint(x: 0, y: searchController.searchBar.frame.height)
// Hide search bar on detailed view and preserve search results
    self.definesPresentationContext = true

// Register for preview
if traitCollection.forceTouchCapability == .available {
    previewingContext = registerForPreviewing(with: self, sourceView: tableView)
}

func updateSearchResults(for searchController: UISearchController) {
    if let searchText = searchController.searchBar.text {
        filterContent(for: searchText)
        tableView.reloadData()
    }
}

// MARK: UIViewControllerPreviewingDelegate methods
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
    guard let tableView = previewingContext.sourceView as? UITableView,
        let indexPath = tableView.indexPathForRow(at: location),
        let cell = tableView.cellForRow(at: indexPath),
        let detailVC = storyboard?.instantiateViewController(withIdentifier: "AlarmViewController") as? AlarmViewController
    else { return nil }
    detailVC.alarm = (searchController.isActive) ? searchResults[(indexPath.row)] : alarms[indexPath.row]
    previewingContext.sourceRect = cell.frame
    return detailVC
}

func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
    show(viewControllerToCommit, sender: self)
}

In short:
1) added delegating for searchController
2) using searchResults in UIViewControllerPreviewingDelegate if searchController.isActive

Hope it helps someone.


问:
Sum subarray's length
I'm looking to count the unread messages in all conversations where a user is a member of the conversation. A message is read by a user if it's id is in the readers array.

The following returns the number of conversations where there exist unread messages. But how to count all unread messages?

```<code>db.getCollection('conversations').count({
    'messages.readers': { $size: 1 }, //i.e. only the message author is in the message.readers array.
    'members': { $in: [ObjectId("59320e38188c5050ac99be8f")] }
})
</code>```

I have checked the aggregate method but I'm not sure if it's the right approach. The following returns the number of all messages.

```<code>        db.getCollection('conversations').aggregate([
    {$match : {
        'members': { $in: [ObjectId("59320e38188c5050ac99be8f")] }
     }},
    {$group: {_id: null, count: {$sum: {$size: "$messages"}}}},
])
</code>```

答:
You can try the below aggregation pipeline.

The below query will $unwind all messages in every matched conversation and apply the $cond expression inside of $sum operator to check if the user is not in messages.readers and return 1 if there is a match or else 0 in a $group stage.

```<code>db.getCollection('conversations').aggregate([
  {$match : {'members': ObjectId("59320e38188c5050ac99be8f") }},
  {$unwind : "$messages"},
  {$group: {_id: null, count: {$sum: {$cond: [{ $ne: ["messages.readers", ObjectId("59320e38188c5050ac99be8f")] }, 1, 0]}}}}
])
</code>```

As such, $unwindis an expensive operation and should not be preferred over other options, but I don't think in your case it is possible and $unwind following $match is little better.

Title: Sum subarray's length

Body:
I'm looking to count the unread messages in all conversations where a user is a member of the conversation. A message is read by a user if it's id is in the readers array.

The following returns the number of conversations where there exist unread messages. But how to count all unread messages?

db.getCollection('conversations').count({
    'messages.readers': { $size: 1 }, //i.e. only the message author is in the message.readers array.
    'members': { $in: [ObjectId("59320e38188c5050ac99be8f")] }
})

I have checked the aggregate method but I'm not sure if it's the right approach. The following returns the number of all messages.

        db.getCollection('conversations').aggregate([
    {$match : {
        'members': { $in: [ObjectId("59320e38188c5050ac99be8f")] }
     }},
    {$group: {_id: null, count: {$sum: {$size: "$messages"}}}},
])

Body:
You can try the below aggregation pipeline.

The below query will $unwind all messages in every matched conversation and apply the $cond expression inside of $sum operator to check if the user is not in messages.readers and return 1 if there is a match or else 0 in a $group stage.

db.getCollection('conversations').aggregate([
  {$match : {'members': ObjectId("59320e38188c5050ac99be8f") }},
  {$unwind : "$messages"},
  {$group: {_id: null, count: {$sum: {$cond: [{ $ne: ["messages.readers", ObjectId("59320e38188c5050ac99be8f")] }, 1, 0]}}}}
])

As such, $unwindis an expensive operation and should not be preferred over other options, but I don't think in your case it is possible and $unwind following $match is little better.


问:
Onclick event on a div not working
Here is my code :

```<code><script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
function klikaj() {
var title = $('inlineBlock _2tga _3e2a').attr('title');
document.getElementById('log').innerHTML += " "+ title + "titi" ;
};
$('.fbb').click(function (evt) {
 alert('123');
});
</script>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.9&appId=132911310473896";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
  <!-- Load Facebook SDK for JavaScript -->
<div class="fbb">
  <div id="fb-root"></div>

  <!-- Your like button code -->
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-action="like" data-size="large" data-show-faces="true" data-share="true" ></div>
</div>
<div id="log">initial content</div>
</code>```

I would like to activate the alert('123') when everything in the fbb div is clicked.

I've tried to add the .click(function (evt) but it's not working

if anyone have any idea

Thanks and regards

答:
By the time that the event is declared, the div has not been declared yet, so it does not exist. You can either use

```<code>$(function(){
   $('.fbb').click(function (evt) {
        alert('123');
    });
});
</code>```

or just move the the click event after the div with class fbb

Title: Onclick event on a div not working

Body:
Here is my code :

initial content

I would like to activate the alert('123') when everything in the fbb div is clicked.

I've tried to add the .click(function (evt) but it's not working

if anyone have any idea

Thanks and regards

Body:
By the time that the event is declared, the div has not been declared yet, so it does not exist. You can either use

$(function(){
   $('.fbb').click(function (evt) {
        alert('123');
    });
});

or just move the the click event after the div with class fbb


问:
Request JSON from existDB
I am rather new to eXistDB but I'm trying to build a little app with it.

I am using a JavaScript example that requests an existing JSON file via jQuery when needed with the following code:

```<code>$.getJSON('path/to/file.json').
    done(function(data) {

        $.each(data, function(key, zone) {
            addRegion(zone, element);
        });
    });
</code>```

This worked regardless of eXistDB as long as the JSON file is present. What I want now, is not to load an existing JSON file, but to call an eXist function like app:getJSON which returns a dynamically genereated JSON object. I read a bit about eXists JSON serializer here http://exist-db.org/exist/apps/wiki/blogs/eXist/XQuery31 and I think I will manage to produce and return a JSON object in a XQuery function, but I do not know how to call such a function via URL from my JavaScript (or here JQuery).

My desired solution would look somewhat like this:

Java Script:

```<code> $.getJSON('/app-getJSON?parameter1=wert1&parameter2=wert2').
    done(function(data) {

        $.each(data, function(key, zone) {
            addRegion(zone, element);
        });
    });
</code>```

and then in my app.xql I would want to have something like:

```<code>declare function app:getJSON($node as node(), $model as map(*), $parameter1 as xs:string?, $parameter2 as xs:string?){
    (:here the JSON Object is generated from the XML collection and returned:)
};
</code>```

So the question comes down to: Is it possible to access a xQuery function via URL and if so, how? If not, how else can I request JSON data that is generated from my XML files with JS/JQuery? I know this is all pretty vague and the question gives away how new I am to eXistDB but I can't find a similar example that I would understand yet. So maybe someone has an idea for me, even if it's only a "you should really read this, this and this" first.
Thanks a lot.

答:
For creating a service that returns JSON I would advise creating a standalone XQuery, e.g., getJSON.xq, and saving this in your application. (Your sample app:getJSON() function's signature suggested you were planning to use eXist's HTML templating facility, but that facility is really meant for generating HTML.) Your getJSON.xq file could simply consist of the following main module:

```<code>xquery version "3.1";

declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization";

declare option output:method "json";
declare option output:media-type "application/json";

let $p1 := request:get-parameter('parameter1', ())
let $p2 := request:get-parameter('parameter2', ())
return
    map {
        "parameter1": $p1,
        "parameter2": $p2
    }
</code>```

Saving this to a collection like /db/apps/getJSON.xq, you will then be able to call http://localhost:8080/exist/apps/myapp/getJSON.xq?parameter1=wert1&parameter2=wert2 and get the following response:

```<code>{
    "parameter1" : "wert1",
    "parameter2" : "wert2"
}
</code>```

Note: This code assumes eXist v3.x, which added handling for XQuery 3.1's JSON support. Earlier versions of eXist could serialize JSON, but in an implementation-specific way. The request module used here is eXist-specific, since there is no widely supported cross platform module for receiving HTTP requests; other XQuery implementations have some variant though.

Title: Request JSON from existDB

Body:
I am rather new to eXistDB but I'm trying to build a little app with it.

I am using a JavaScript example that requests an existing JSON file via jQuery when needed with the following code:

$.getJSON('path/to/file.json').
    done(function(data) {

        $.each(data, function(key, zone) {
            addRegion(zone, element);
        });
    });

This worked regardless of eXistDB as long as the JSON file is present. What I want now, is not to load an existing JSON file, but to call an eXist function like app:getJSON which returns a dynamically genereated JSON object. I read a bit about eXists JSON serializer here http://exist-db.org/exist/apps/wiki/blogs/eXist/XQuery31 and I think I will manage to produce and return a JSON object in a XQuery function, but I do not know how to call such a function via URL from my JavaScript (or here JQuery).

My desired solution would look somewhat like this:

Java Script:

 $.getJSON('/app-getJSON?parameter1=wert1&parameter2=wert2').
    done(function(data) {

        $.each(data, function(key, zone) {
            addRegion(zone, element);
        });
    });

and then in my app.xql I would want to have something like:

declare function app:getJSON($node as node(), $model as map(*), $parameter1 as xs:string?, $parameter2 as xs:string?){
    (:here the JSON Object is generated from the XML collection and returned:)
};

So the question comes down to: Is it possible to access a xQuery function via URL and if so, how? If not, how else can I request JSON data that is generated from my XML files with JS/JQuery? I know this is all pretty vague and the question gives away how new I am to eXistDB but I can't find a similar example that I would understand yet. So maybe someone has an idea for me, even if it's only a "you should really read this, this and this" first.
Thanks a lot.

Body:
For creating a service that returns JSON I would advise creating a standalone XQuery, e.g., getJSON.xq, and saving this in your application. (Your sample app:getJSON() function's signature suggested you were planning to use eXist's HTML templating facility, but that facility is really meant for generating HTML.) Your getJSON.xq file could simply consist of the following main module:

xquery version "3.1";

declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization";

declare option output:method "json";
declare option output:media-type "application/json";

let $p1 := request:get-parameter('parameter1', ())
let $p2 := request:get-parameter('parameter2', ())
return
    map {
        "parameter1": $p1,
        "parameter2": $p2
    }

Saving this to a collection like /db/apps/getJSON.xq, you will then be able to call http://localhost:8080/exist/apps/myapp/getJSON.xq?parameter1=wert1&parameter2=wert2 and get the following response:

{
    "parameter1" : "wert1",
    "parameter2" : "wert2"
}

Note: This code assumes eXist v3.x, which added handling for XQuery 3.1's JSON support. Earlier versions of eXist could serialize JSON, but in an implementation-specific way. The request module used here is eXist-specific, since there is no widely supported cross platform module for receiving HTTP requests; other XQuery implementations have some variant though.


问:
My solution to check if the Check Box is checked not working?
I am trying to find if the Check Box is checked or  not. I am sure I am writing the write code but it's not working. Following is my code:

```<code>@Html.CheckBoxFor(m => m.Country, new { id = "country" })
</code>```

And my JavaScript Code:

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

  if ($("#country").is(":checked"))
  {
     alert("Working");
  }

});
</code>```

答:
Make sure the checkbox is actually checked when the document has loaded, if not the if state will return false and it runs only once.
You could always try with

```<code>$('#country').prop('checked')
</code>```

Also here is another thread which provides multiple solutions Get checkbox value in jQuery

Body:
I am trying to find if the Check Box is checked or  not. I am sure I am writing the write code but it's not working. Following is my code:

@Html.CheckBoxFor(m => m.Country, new { id = "country" })

And my JavaScript Code:

$(document).ready(function () {

  if ($("#country").is(":checked"))
  {
     alert("Working");
  }

});

Body:
Make sure the checkbox is actually checked when the document has loaded, if not the if state will return false and it runs only once.
You could always try with

$('#country').prop('checked')

Also here is another thread which provides multiple solutions Get checkbox value in jQuery


答:
Something like

```<code>dims <- dim(dd)
dd2 <- matrix(dd,nrow=prod(dims[2:3]),ncol=dims[1])
dd3 <- data.frame(ID=rep(1:dims[3],each=dims[2]),
                  dd2)
rownames(dd3) <- c("ID",dimnames(dd)[[2]])
</code>```

should work, I think.

Title: Wide to long format in R list: 3D to 2D array with 3rd dimension as ID

Body:
I have imported a *.mat data set of ECG data and it turns out to be an array nested in a list with (1:19, 1:2000, 1:45) dimensions.

I'd like to convert this array into a data.table in long format where each of the 1:45 are 'ids'. I like the look of reshape2 and tidyr but I don't see an easy way of doing it when a 'list' is involved. Any thoughts?

ADDED: E.g. as the following picture:

EDIT: Added dput from ECGa

    dput(ECGa[1:4,1:4,1:4])
structure(c(0.266687798848186, 0.243782451327742, 0.256932437720159,
0.298861598151174, 0.198233672667731, 0.0917952258522064, 0.0911852809187542,
0.0896079263551856, 0.236398290801764, 0.0864552727199747, 0.0745517747485495,
0.141094205953345, 0.134887167694073, 0.0747942533151883, 0.0955856952160322,
0.0351423350784724, 0.0280172116375036, 0.0137183766752048, 0.00632054977574689,
0.0140727955279187, 0.0690137281047283, 0.078048395374513, 0.103558903741209,
0.0440585188615387, 0.156352265056089, 0.112594108595364, 0.162727838219577,
0.171253189308951, 0.10110879614821, 0.0815894300030362, 0.11782535820017,
0.0422632188213653, 0.0555849641766514, 0.0677027788598739, 0.0459698146330784,
0.0388415858274208, 0.0843241755529416, 0.0607574029475139, 0.0572549162201976,
0.0507991887467287, 0.0505785290171543, 0.064132492222132, 0.0527843866043094,
0.0354988312446934, 0.104654374350645, 0.0881949907935882, 0.0429712078085868,
0.0576943626267035, 0.0382280461459995, 0.124883693856915, 0.0481763535955804,
0.0397818749456581, 0.0782161984603273, 0.155594086108477, 0.121039425233015,
0.0563997196467123, 0.0513952066155024, 0.209997229543773, 0.0745673273804948,
0.0647872565452434, 0.0801540099609934, 0.147046389860838, 0.162708859129276,
0.0766361733056703), .Dim = c(4L, 4L, 4L), .Dimnames = list(NULL,
    c("P7", "P4", "Cz", "Pz"), NULL))

I've tried doing:
ECGa<-as.data.frame(ECGa)
gives the right dimensions but it renames all the columns (e.g. the first becomes P7.1, P7.2 ... P7.45) I want to make a new column called ID that gives a value of 1 for the first patient and 2 for the second, up to 45 for the forty fifth.

NEW ADDITION:
I've found that using abind does part of the job I want. But imagine I had a 1000 arrays, can I automate it?
e.g.

 abind(ECGa[,,1],ECGa[,,2],ECGa[,,3],ECGa[,,4],ECGa[,,5],along=1)
> dim(abind(ECGa[,,1],ECGa[,,2],ECGa[,,3],ECGa[,,4],ECGa[,,5],along=1))
[1] 10000    19

Body:
Something like

dims <- dim(dd)
dd2 <- matrix(dd,nrow=prod(dims[2:3]),ncol=dims[1])
dd3 <- data.frame(ID=rep(1:dims[3],each=dims[2]),
                  dd2)
rownames(dd3) <- c("ID",dimnames(dd)[[2]])

should work, I think.


答:
Three issues - first as already noted - you have no content in the .fbb div so its not easy to see what you are clicking. I have added some text - "click here" to ensure the click location is obvious. Second - the source URL for the jQuery is incorrect - you have HTTP: - it needs HTTPS: and third - you need to wrap your jQuery in a $(document).ready wrapper or move the function to the end of the page so it is available after the rest of the page has rendered.

.fbb{
  cursor:pointer
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>

function klikaj() {
var title = $('inlineBlock _2tga _3e2a').attr('title');
document.getElementById('log').innerHTML += " "+ title + "titi" ;
};

$(document).ready(function(){
  $('.fbb').click(function (evt) {
   alert('123');
  });
})
</script>

<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.9&appId=132911310473896";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
  <!-- Load Facebook SDK for JavaScript -->
<div class="fbb"> fbb div - Click Here
  <div id="fb-root"></div>

  <!-- Your like button code -->
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-action="like" data-size="large" data-show-faces="true" data-share="true" ></div>
</div>
<div id="log">initial content</div></code>```

Title: Onclick event on a div not working

Body:
Three issues - first as already noted - you have no content in the .fbb div so its not easy to see what you are clicking. I have added some text - "click here" to ensure the click location is obvious. Second - the source URL for the jQuery is incorrect - you have HTTP: - it needs HTTPS: and third - you need to wrap your jQuery in a $(document).ready wrapper or move the function to the end of the page so it is available after the rest of the page has rendered.

.fbb{
  cursor:pointer
}

<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>

function klikaj() {
var title = $('inlineBlock _2tga _3e2a').attr('title');
document.getElementById('log').innerHTML += " "+ title + "titi" ;
};

$(document).ready(function(){
  $('.fbb').click(function (evt) {
   alert('123');
  });
})
</script>

<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.9&appId=132911310473896";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
  <!-- Load Facebook SDK for JavaScript -->
<div class="fbb"> fbb div - Click Here
  <div id="fb-root"></div>

  <!-- Your like button code -->
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-action="like" data-size="large" data-show-faces="true" data-share="true" ></div>
</div>
<div id="log">initial content</div>


答:
First off, I would consider using an enum when passing in the parameter "level" into the function. This will help fix possible logic issues within your function.

Where your problem probably lies: If you do not pass in a non-nil ingredient String, you will encounter an error when accessing or using bought_ingredient_market_graphic. You could have a typo in your string that you use to initialize your image. Make sure your string matches your image name. This is likely what is happening.

Also why not try initializing your sprite in the else logic?

```<code>func show_market_graphic(x: CGFloat, y: CGFloat, level: String, ingredient: String?) {

   var market_graphic: SKSpriteNode

   var bought_ingredient_market_graphic: SKSpriteNode

   if level == "locked" {

      market_graphic = SKSpriteNode(imageNamed: "locked_ingredient")

   } else {

      market_graphic = SKSpriteNode(imageNamed: "bought_ingredient")

      bought_ingredient_market_graphic = SKSpriteNode(imageNamed: ingredient!)
      bought_ingredient_market_graphic.zPosition = 20
      bought_ingredient_market_graphic.position = market_graphic.position
      addChild(bought_ingredient_market_graphic)

   }

   market_graphic.zPosition = 10
   market_graphic.position = CGPoint(x: x, y: y)
   addChild(market_graphic)
}
</code>```

Title: Need help to handle this error: Variable 'x' used before being initialized

Body:
I have a problem in Swift whit optional function param. I want to set an value for an SKSpriteNote within a function, but this value dos not exist before the function is called, so i obviously get an error ;/

Can anyone please tell me what to do, to solve this?

THIS IS THE ERROR I GET:
Variable 'bought_ingredient_market_graphic' used before being initialized

THIS IS MY FUNCTION (see

func show_market_graphic(x: CGFloat, y: CGFloat, level: String, ingredient: String?){

    var market_graphic: SKSpriteNode

    var bought_ingredient_market_graphic: SKSpriteNode

    if(level == "locked"){

        market_graphic = SKSpriteNode(imageNamed: "locked_ingredient")

    } else {

        market_graphic = SKSpriteNode(imageNamed: "bought_ingredient")

        bought_ingredient_market_graphic = SKSpriteNode(imageNamed: ingredient!)
    }

    market_graphic.zPosition = 10

    market_graphic.position = CGPoint(x: x, y: y)

    addChild(market_graphic)

    if(level != "locked"){
        // * ERROR ON LINE BELOW
        bought_ingredient_market_graphic.zPosition = 20
        // * ERROR ON LINE BELOW
        bought_ingredient_market_graphic.position = market_graphic.position
        // * ERROR ON LINE BELOW
        addChild(bought_ingredient_market_graphic)
    }
}

Body:
First off, I would consider using an enum when passing in the parameter "level" into the function. This will help fix possible logic issues within your function.

Where your problem probably lies: If you do not pass in a non-nil ingredient String, you will encounter an error when accessing or using bought_ingredient_market_graphic. You could have a typo in your string that you use to initialize your image. Make sure your string matches your image name. This is likely what is happening.

Also why not try initializing your sprite in the else logic?

func show_market_graphic(x: CGFloat, y: CGFloat, level: String, ingredient: String?) {

   var market_graphic: SKSpriteNode

   var bought_ingredient_market_graphic: SKSpriteNode

   if level == "locked" {

      market_graphic = SKSpriteNode(imageNamed: "locked_ingredient")

   } else {

      market_graphic = SKSpriteNode(imageNamed: "bought_ingredient")

      bought_ingredient_market_graphic = SKSpriteNode(imageNamed: ingredient!)
      bought_ingredient_market_graphic.zPosition = 20
      bought_ingredient_market_graphic.position = market_graphic.position
      addChild(bought_ingredient_market_graphic)

   }

   market_graphic.zPosition = 10
   market_graphic.position = CGPoint(x: x, y: y)
   addChild(market_graphic)
}


问:
Behaviour of arr[i] = i++ and i = i + 1 statements in C and C++
In the C and C++ languages, the arr[i] = i++; statement invokes undefined behavior. Why does the statement i = i + 1; not invoke undefined behavior?

答:
Note that this will change in C++17. In C++17, arr[i] = i++ does not invoke undefined behavior. This is due to the following change in [expr.ass]:

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.

That is, we do i++ then we do arr[i] then we perform the assignment. The now well-defined ordering is:

```<code>auto src = i++;
auto& dst = arr[i];
dst = src;
</code>```

Body:
Note that this will change in C++17. In C++17, arr[i] = i++ does not invoke undefined behavior. This is due to the following change in [expr.ass]:

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.

That is, we do i++ then we do arr[i] then we perform the assignment. The now well-defined ordering is:

auto src = i++;
auto& dst = arr[i];
dst = src;


问:
OAuth with GWT against Strava API
I am trying to create a GWT application against the Strava API.
The first thing to do is authentication.

On http://strava.github.io/api/v3/oauth/ they say that for the token exchange you have to do something like :

```<code>curl -X POST https://www.strava.com/oauth/token \
   -F client_id=5 \
   -F client_secret=7b2946535949ae70f015d696d8ac602830ece412 \
   -F code=75e251e3ff8fff
</code>```

As far as I know those -F things represent fields in a multiform post ?
So I created something like :

```<code>   final FormPanel form = new FormPanel();
   container.add(form);
   form.setAction("https://www.strava.com/oauth/token");
   form.setEncoding(FormPanel.ENCODING_MULTIPART);
   form.setMethod(FormPanel.METHOD_POST);

   VerticalPanel panel = new VerticalPanel();
   form.setWidget(panel);
   panel.add(new Hidden("client_id", CLIENT_ID));
   panel.add(new Hidden("client_secret", CLIENT_SECRET));
   panel.add(new Hidden("code", code));

   form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler()
   {
       @Override
       public void onSubmitComplete(SubmitCompleteEvent event)
       {
          GWT.log("complete " + event.getResults());
       }
    });

   container.addAttachHandler(new AttachEvent.Handler()
  {

     @Override
     public void onAttachOrDetach(AttachEvent event)
     {
        form.submit();
     }
  });
</code>```

Now when I do this I see the following error in Chrome dev tools :

```<code>Refused to display 'https://www.strava.com/oauth/token' in a frame because it set 'X-Frame-Options' to 'deny'.
FormPanelImpl.java:117 POST https://www.strava.com/oauth/token net::ERR_BLOCKED_BY_RESPONSE
</code>```

Now the questions are. Am I correct by creating a form to mimic that curl example ?
Has that frame error something to do with GWT using IFRAME stuff ? How do I fix this ?

答:
Strava is setting a header on their response to you that disallows loading it within an iframe (see How to set 'X-Frame-Options' on iframe?). I assume your GWT app is loading this form within one.

On further reading they also describe this process and I see that's where you found your example curl.

Completing the token exchange

If the user accepts the request to share access to their Strava data, Strava will redirect back to redirect_uri with the authorization code. The application must now exchange the temporary authorization code for an access token, using its client ID and client secret.

You may want to look into using the RequestBuilder. You can set your form data by encoding it via URL.encode and with setHeader("Content-Type", "application/x-www-form-urlencodeddata") on the builder. Your callback there can take care of accepting the token for use elsewhere.

Example partially ganked from GWT Server Communication and written in buffer, not tested:

```<code>String url = "https://www.strava.com/oauth/token";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
builder.setHeader("Content-Type", "application/x-www-form-urlencodeddata");
String data = URL.encodeQueryString("client_id=5&client_secret=7b2946535949ae70f015d696d8ac602830ece412&code=75e251e3ff8fff");
try {
  Request request = builder.sendRequest(data, new RequestCallback() {
    public void onError(Request request, Throwable exception) {
       // Couldn't connect to server (could be timeout, SOP violation, etc.)
    }

    public void onResponseReceived(Request request, Response response) {
      if (200 == response.getStatusCode()) {
          // Process the response in response.getText()
      } else {
        // Handle the error.  Can get the status text from response.getStatusText()
      }
    }
  });
} catch (RequestException e) {
  // Couldn't connect to server
</code>```

Having not tested this, I'm not sure the above is the appropriate way of sending the request data, so you may need to figure that part out.

We do have an extra wrinkle though:

All developers need to register their application before getting started. A registered application will be assigned a Client ID and Client SECRET. The SECRET should never be shared.

If this is an application meant to be used by the general public, you shouldn't use the above code. You would have to perform this part on your server.

Title: OAuth with GWT against Strava API

Body:
I am trying to create a GWT application against the Strava API.
The first thing to do is authentication.

On http://strava.github.io/api/v3/oauth/ they say that for the token exchange you have to do something like :

curl -X POST https://www.strava.com/oauth/token \
   -F client_id=5 \
   -F client_secret=7b2946535949ae70f015d696d8ac602830ece412 \
   -F code=75e251e3ff8fff

As far as I know those -F things represent fields in a multiform post ?
So I created something like :

   final FormPanel form = new FormPanel();
   container.add(form);
   form.setAction("https://www.strava.com/oauth/token");
   form.setEncoding(FormPanel.ENCODING_MULTIPART);
   form.setMethod(FormPanel.METHOD_POST);

   VerticalPanel panel = new VerticalPanel();
   form.setWidget(panel);
   panel.add(new Hidden("client_id", CLIENT_ID));
   panel.add(new Hidden("client_secret", CLIENT_SECRET));
   panel.add(new Hidden("code", code));

   form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler()
   {
       @Override
       public void onSubmitComplete(SubmitCompleteEvent event)
       {
          GWT.log("complete " + event.getResults());
       }
    });

   container.addAttachHandler(new AttachEvent.Handler()
  {

     @Override
     public void onAttachOrDetach(AttachEvent event)
     {
        form.submit();
     }
  });

Now when I do this I see the following error in Chrome dev tools :

Refused to display 'https://www.strava.com/oauth/token' in a frame because it set 'X-Frame-Options' to 'deny'.
FormPanelImpl.java:117 POST https://www.strava.com/oauth/token net::ERR_BLOCKED_BY_RESPONSE

Now the questions are. Am I correct by creating a form to mimic that curl example ?
Has that frame error something to do with GWT using IFRAME stuff ? How do I fix this ?

Body:
Strava is setting a header on their response to you that disallows loading it within an iframe (see How to set 'X-Frame-Options' on iframe?). I assume your GWT app is loading this form within one.

On further reading they also describe this process and I see that's where you found your example curl.

Completing the token exchange

If the user accepts the request to share access to their Strava data, Strava will redirect back to redirect_uri with the authorization code. The application must now exchange the temporary authorization code for an access token, using its client ID and client secret.

You may want to look into using the RequestBuilder. You can set your form data by encoding it via URL.encode and with setHeader("Content-Type", "application/x-www-form-urlencodeddata") on the builder. Your callback there can take care of accepting the token for use elsewhere.

Example partially ganked from GWT Server Communication and written in buffer, not tested:

String url = "https://www.strava.com/oauth/token";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
builder.setHeader("Content-Type", "application/x-www-form-urlencodeddata");
String data = URL.encodeQueryString("client_id=5&client_secret=7b2946535949ae70f015d696d8ac602830ece412&code=75e251e3ff8fff");
try {
  Request request = builder.sendRequest(data, new RequestCallback() {
    public void onError(Request request, Throwable exception) {
       // Couldn't connect to server (could be timeout, SOP violation, etc.)
    }

    public void onResponseReceived(Request request, Response response) {
      if (200 == response.getStatusCode()) {
          // Process the response in response.getText()
      } else {
        // Handle the error.  Can get the status text from response.getStatusText()
      }
    }
  });
} catch (RequestException e) {
  // Couldn't connect to server

Having not tested this, I'm not sure the above is the appropriate way of sending the request data, so you may need to figure that part out.

We do have an extra wrinkle though:

All developers need to register their application before getting started. A registered application will be assigned a Client ID and Client SECRET. The SECRET should never be shared.

If this is an application meant to be used by the general public, you shouldn't use the above code. You would have to perform this part on your server.


问:
How can I set the initial value of Select2 when using AJAX?
I have a select2 v4.0.0 being populated from an Ajax array. If I set the val of the select2 I can see via javascript debugging that it has selected the correct item (#3 in my case), however this is not shown in the select box, it is still showing the placeholder.

Whereas I should be seeing something like this:

In my form fields:

<input name="creditor_id" type="hidden" value="3" />

        Creditor:

            <select class="creditor_select2 input-xlarge form-control minimal select2 col-xs-8">
                <option></option>
            </select>

```
<p>My javascript:</p>
<pre class="lang-js prettyprint-override"><code>var initial_creditor_id="3";
$(".creditor_select2").select2({
    ajax: {
        url: "/admin/api/transactions/creditorlist",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term,
                c_id: initial_creditor_id,
                page: params.page
            };
        },
        processResults: function (data, page) {
            return {
                results: data
            };
        },
        cache: true
    },
    placeholder: "Search for a Creditor",
    width: "element",
    theme: "bootstrap",
    allowClear: true
}).on("select2:select", function (e) {
    var selected=e.params.data;
    if (typeof selected!=="undefined") {
        $("[name='creditor_id']").val(selected.creditor_id);
        $("#allocationsDiv").hide();
        $("[name='amount_cash']").val("");
        $("[name='amount_cheque']").val("");
        $("[name='amount_direct']").val("");
        $("[name='amount_creditcard']").val("");
    }
}).on("select2:unselecting", function (e) {
    $("form").each(function () {
        this.reset()
    });
    ("#allocationsDiv").hide();
    $("[name='creditor_id']").val("");
}).val(initial_creditor_id);
</code>```

How can I make the select box show the selected item rather than the placeholder? Should I be sending this as part of the AJAX JSON response perhaps?

In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This worked fine for me in v3.5.

答:
For a simple and semantic solution i prefer to define the initial value in HTML, example:

```<code><select name="myfield" data-placeholder="Select an option">
    <option value="initial-value" selected>Initial text</option>
</select>
</code>```

So when i call $('select').select2({ ajax: {...}}); the initial value is initial-value and its option text is Initial text.

My current Select2 version is 4.0.3, but i think it has a great compatibility with other versions.

ContentLicense: CC BY-SA 4.0

Body:
I have a select2 v4.0.0 being populated from an Ajax array. If I set the val of the select2 I can see via javascript debugging that it has selected the correct item (#3 in my case), however this is not shown in the select box, it is still showing the placeholder.

Whereas I should be seeing something like this:

In my form fields:

<input name="creditor_id" type="hidden" value="3" />

        Creditor:

            <select class="creditor_select2 input-xlarge form-control minimal select2 col-xs-8">
                <option></option>
            </select>

My javascript:

var initial_creditor_id="3";
$(".creditor_select2").select2({
    ajax: {
        url: "/admin/api/transactions/creditorlist",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term,
                c_id: initial_creditor_id,
                page: params.page
            };
        },
        processResults: function (data, page) {
            return {
                results: data
            };
        },
        cache: true
    },
    placeholder: "Search for a Creditor",
    width: "element",
    theme: "bootstrap",
    allowClear: true
}).on("select2:select", function (e) {
    var selected=e.params.data;
    if (typeof selected!=="undefined") {
        $("[name='creditor_id']").val(selected.creditor_id);
        $("#allocationsDiv").hide();
        $("[name='amount_cash']").val("");
        $("[name='amount_cheque']").val("");
        $("[name='amount_direct']").val("");
        $("[name='amount_creditcard']").val("");
    }
}).on("select2:unselecting", function (e) {
    $("form").each(function () {
        this.reset()
    });
    ("#allocationsDiv").hide();
    $("[name='creditor_id']").val("");
}).val(initial_creditor_id);

How can I make the select box show the selected item rather than the placeholder? Should I be sending this as part of the AJAX JSON response perhaps?

In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This worked fine for me in v3.5.

Body:
For a simple and semantic solution i prefer to define the initial value in HTML, example:

<select name="myfield" data-placeholder="Select an option">
    <option value="initial-value" selected>Initial text</option>
</select>

So when i call $('select').select2({ ajax: {...}}); the initial value is initial-value and its option text is Initial text.

My current Select2 version is 4.0.3, but i think it has a great compatibility with other versions.


问:
Sharepoint2013:Getting error onclick of selectedShapeText Button which is provided by new javascript api for Visio provided by microsoft
I am working on visio in SharePoint-2013 using visio web access web part .In VWA  I was able to read all the shapes and there by displaying shape text. Now Microsoft has released new javascript api . where it will take the url of the visio file and it displays Visio on click of a button named initEmbeddedframe.

Also they have given one more button, on click of which selected shape text is supposed to display.But it's coming to catch block of getSelectedShapeText() method. As I am new to sharepoint as well as Visio I need help from you guys.

would like to provide the code which need to be embed in Script editor web aprt of a sharepoint page.

Enter Visio File Url:

```

the Issue is Error i coming on click of selected shape Text Button.

Any help would greatly appreciated.Let me know if any query's in case you have not understood my question.

答:
Which URL do you enter? It is supposed to look like this:

..../_layouts/15/WopiFrame.aspx?sourcedoc=%7BXXX-XXX-XX%7D&file=Drawing4.vsdx&action=embedView

Means, you open Visio diagram in SharePoint, copy URL from the address bar and paste it into that field (replace XXXX with your value). If it does not work, replace "default" at the end with "embedView".

Body:
I am working on visio in SharePoint-2013 using visio web access web part .In VWA  I was able to read all the shapes and there by displaying shape text. Now Microsoft has released new javascript api . where it will take the url of the visio file and it displays Visio on click of a button named initEmbeddedframe.

Also they have given one more button, on click of which selected shape text is supposed to display.But it's coming to catch block of getSelectedShapeText() method. As I am new to sharepoint as well as Visio I need help from you guys.

would like to provide the code which need to be embed in Script editor web aprt of a sharepoint page.

Enter Visio File Url:

the Issue is Error i coming on click of selected shape Text Button.

Any help would greatly appreciated.Let me know if any query's in case you have not understood my question.


问:
retrieve parent text on click (jQuery)
I'm trying to select first td element, when button "Add" is clicked.

```<code>              <tr>
                <td>tt3783958</td>
                <td>La La Land</td>
                <td>2016</td>
                <td>Comedy, Drama, Music</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
</code>```

I can't figure out what I'm doing wrong here.

```<code>$(document).ready(function() {
  $(".btn.btn-outline-success").eq(0).click(function() {
    var test = $(this).parent().parent().find("td").first()
    console.log(test)
    var fest = $(this).find("td").first()
    console.log(fest)
  });
});
</code>```

Live Demo: https://jsfiddle.net/ma1Lac9v/2/

答:
You can select the closest tr and then the first td:

```<code>$(this).closest('tr').find("td:first")
</code>```

$(".btn.btn-outline-success").on('click', function(e) {
    var test = $(this).closest('tr').find("td:first");
    console.log(test.text());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />

<div class="container">
    <div class="row">
        <div class="col">
            <table class="table">
                <thead class="thead-inverse">
                <tr>
                    <th>id</th>
                    <th>Title</th>
                    <th>Year</th>
                    <th>Type</th>
                    <th>Option</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td>tt3783958</td>
                    <td>La La Land</td>
                    <td>2016</td>
                    <td>Comedy, Drama, Music</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                <tr>
                    <td>tt0488120</td>
                    <td>Fracture</td>
                    <td>2007</td>
                    <td>Crime, Drama, Mystery</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                <tr>
                    <td>tt3569230</td>
                    <td>Legend</td>
                    <td>2015</td>
                    <td>Biography, Crime, Drama</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                <tr>
                    <td>tt2692904</td>
                    <td>Locke</td>
                    <td>2013</td>
                    <td>Drama</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                <tr>
                    <td>tt1392190</td>
                    <td>Mad Max: Fury Road</td>
                    <td>2015</td>
                    <td>Action, Adventure, Sci-Fi</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                <tr>
                    <td>tt0993846</td>
                    <td>The Wolf of Wall Street</td>
                    <td>2013</td>
                    <td>Biography, Comedy, Crime</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
</div></code>```

Title: retrieve parent text on click (jQuery)

Body:
I'm trying to select first td element, when button "Add" is clicked.

                tt3783958
                La La Land
                2016
                Comedy, Drama, Music

                  <button class="btn btn-outline-success">Add</button>

I can't figure out what I'm doing wrong here.

$(document).ready(function() {
  $(".btn.btn-outline-success").eq(0).click(function() {
    var test = $(this).parent().parent().find("td").first()
    console.log(test)
    var fest = $(this).find("td").first()
    console.log(fest)
  });
});

Live Demo: https://jsfiddle.net/ma1Lac9v/2/

Body:
You can select the closest tr and then the first td:

$(this).closest('tr').find("td:first")

$(".btn.btn-outline-success").on('click', function(e) {
    var test = $(this).closest('tr').find("td:first");
    console.log(test.text());
});

<script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />

<div class="container">
    <div class="row">
        <div class="col">
            <table class="table">
                <thead class="thead-inverse">
                <tr>
                    <th>id</th>
                    <th>Title</th>
                    <th>Year</th>
                    <th>Type</th>
                    <th>Option</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td>tt3783958</td>
                    <td>La La Land</td>
                    <td>2016</td>
                    <td>Comedy, Drama, Music</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                <tr>
                    <td>tt0488120</td>
                    <td>Fracture</td>
                    <td>2007</td>
                    <td>Crime, Drama, Mystery</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                <tr>
                    <td>tt3569230</td>
                    <td>Legend</td>
                    <td>2015</td>
                    <td>Biography, Crime, Drama</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                <tr>
                    <td>tt2692904</td>
                    <td>Locke</td>
                    <td>2013</td>
                    <td>Drama</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                <tr>
                    <td>tt1392190</td>
                    <td>Mad Max: Fury Road</td>
                    <td>2015</td>
                    <td>Action, Adventure, Sci-Fi</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                <tr>
                    <td>tt0993846</td>
                    <td>The Wolf of Wall Street</td>
                    <td>2013</td>
                    <td>Biography, Comedy, Crime</td>
                    <td>
                        <button class="btn btn-outline-success">Add</button>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>


问:
Dynamically Creating / Implementing Data in A Table with a 2D Array in Javascript/Html
The goal I am trying to achieve is to dynamically create a table with data based off of the info from a 2D array. I've seen examples of table creation with 1D arrays, but I can't seem to wrap around creating it with 2D. Furthermore, once this table is created, I need to be able to manipulate it, for example deleting a row with insignificant information etc. I like to use a nested for loop for this. This needs to be created with Javascript / Html.
The table for example :

```<code>|item   | price | description|

|chicken | $20  | yummy |
</code>```

And the array [0][0] is chicken, [0][1] is $20, [0][2] is yummy.
Any help / leads are appreciated!.

答:
Do it dynamically with Vanilla and ES6

const food = [{
  Item: "chicken",
  Price: "$20",
  Description: "buck,buck,,,,, buck,,, buckAHHHH yumm"
}, {
  Item: "Beef",
  Price: "$20",
  Description: "Moo yumm"
}, {
  Item: "Dog",
  Price: "$20",
  Description: "woof-woof yumm"
}, {
  Item: "Cat",
  Price: "$20",
  Description: "meow-meow yumm"
}];

function tableCreate(items) {
  let lables = items.reduce((s, o) => [...new Set([...s, ...Object.keys(o)])], []);
  items.unshift(lables);
  let body = document.body,
    tbl = document.createElement('table');
  tbl.style.width = '100px';
  tbl.style.border = '1px solid black';
  for (let [i, index] of items.entries()) {
    let tr = tbl.insertRow();
    for (let j in items[i]) {
      let td = tr.insertCell();
      td.appendChild(document.createTextNode(items[i][j]));
      td.style.border = '1px solid black';
    }
  }
  body.appendChild(tbl);
  tbl.rows[0].style.fontWeight = 'bold';
}

tableCreate(food);```
</div>
</div>
</p>

<p>And you can modify it like so</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const food = [{
  Item: "chicken",
  Price: "$20",
  Description: "buck,buck,,,,, buck,,, buckAHHHH yumm"
}, {
  Item: "Beef",
  Price: "$20",
  Description: "Moo yumm"
}, {
  Item: "Dog",
  Price: "$20",
  Description: "woof-woof yumm"
}, {
  Item: "Cat",
  Price: "$20",
  Description: "meow-meow yumm"
}];

function tableCreate(items) {
  let lables = items.reduce((s, o) => [...new Set([...s, ...Object.keys(o)])], []);
  items.unshift(lables);
  let body = document.body,
    tbl = document.createElement('table');
  tbl.style.width = '100px';
  tbl.style.border = '1px solid black';
  for (let [i, index] of items.entries()) {
    let tr = tbl.insertRow();
    for (let j in items[i]) {
      let td = tr.insertCell();
      td.appendChild(document.createTextNode(items[i][j]));
      td.style.border = '1px solid black';
    }
  }
  body.appendChild(tbl);
  tbl.rows[0].style.fontWeight = 'bold';
}

const modify = {
  remove(from, val) {
    for (let [i, product] of from.entries()) {
      if (product.Item === val) {
        console.log(i)
        from.splice(i, 1);
        console.log(from)
      }
    }
  },
  removeOnLengthsLargerThan(from, val) {
    for (let [i, product] of from.entries()) {
      if (product.Description) {
        if (product.Description.length > val) {
          from.splice(i, 1);
        }
      }
    }
  },
  shorten(from, val) {
    for (let [i, product] of from.entries()) {
      if (product.Description) {
        if (product.Description.length > val) {
          product.Description = product.Description.substr(0, val);

        }
      }
    }
  }
}

modify.shorten(food, 10);
console.log('shorten',food);
modify.remove(food, 'chicken');
console.log('remove',food);
modify.removeOnLengthsLargerThan(food, 10)
console.log('removeOnLengthsLargerThan',food);
tableCreate(food);</code>```

Body:
The goal I am trying to achieve is to dynamically create a table with data based off of the info from a 2D array. I've seen examples of table creation with 1D arrays, but I can't seem to wrap around creating it with 2D. Furthermore, once this table is created, I need to be able to manipulate it, for example deleting a row with insignificant information etc. I like to use a nested for loop for this. This needs to be created with Javascript / Html.
The table for example :

|item   | price | description|

|chicken | $20  | yummy |

And the array [0][0] is chicken, [0][1] is $20, [0][2] is yummy.
Any help / leads are appreciated!.

Body:
Do it dynamically with Vanilla and ES6

const food = [{
  Item: "chicken",
  Price: "$20",
  Description: "buck,buck,,,,, buck,,, buckAHHHH yumm"
}, {
  Item: "Beef",
  Price: "$20",
  Description: "Moo yumm"
}, {
  Item: "Dog",
  Price: "$20",
  Description: "woof-woof yumm"
}, {
  Item: "Cat",
  Price: "$20",
  Description: "meow-meow yumm"
}];

function tableCreate(items) {
  let lables = items.reduce((s, o) => [...new Set([...s, ...Object.keys(o)])], []);
  items.unshift(lables);
  let body = document.body,
    tbl = document.createElement('table');
  tbl.style.width = '100px';
  tbl.style.border = '1px solid black';
  for (let [i, index] of items.entries()) {
    let tr = tbl.insertRow();
    for (let j in items[i]) {
      let td = tr.insertCell();
      td.appendChild(document.createTextNode(items[i][j]));
      td.style.border = '1px solid black';
    }
  }
  body.appendChild(tbl);
  tbl.rows[0].style.fontWeight = 'bold';
}

tableCreate(food);

And you can modify it like so

const food = [{
  Item: "chicken",
  Price: "$20",
  Description: "buck,buck,,,,, buck,,, buckAHHHH yumm"
}, {
  Item: "Beef",
  Price: "$20",
  Description: "Moo yumm"
}, {
  Item: "Dog",
  Price: "$20",
  Description: "woof-woof yumm"
}, {
  Item: "Cat",
  Price: "$20",
  Description: "meow-meow yumm"
}];

function tableCreate(items) {
  let lables = items.reduce((s, o) => [...new Set([...s, ...Object.keys(o)])], []);
  items.unshift(lables);
  let body = document.body,
    tbl = document.createElement('table');
  tbl.style.width = '100px';
  tbl.style.border = '1px solid black';
  for (let [i, index] of items.entries()) {
    let tr = tbl.insertRow();
    for (let j in items[i]) {
      let td = tr.insertCell();
      td.appendChild(document.createTextNode(items[i][j]));
      td.style.border = '1px solid black';
    }
  }
  body.appendChild(tbl);
  tbl.rows[0].style.fontWeight = 'bold';
}

const modify = {
  remove(from, val) {
    for (let [i, product] of from.entries()) {
      if (product.Item === val) {
        console.log(i)
        from.splice(i, 1);
        console.log(from)
      }
    }
  },
  removeOnLengthsLargerThan(from, val) {
    for (let [i, product] of from.entries()) {
      if (product.Description) {
        if (product.Description.length > val) {
          from.splice(i, 1);
        }
      }
    }
  },
  shorten(from, val) {
    for (let [i, product] of from.entries()) {
      if (product.Description) {
        if (product.Description.length > val) {
          product.Description = product.Description.substr(0, val);

        }
      }
    }
  }
}

modify.shorten(food, 10);
console.log('shorten',food);
modify.remove(food, 'chicken');
console.log('remove',food);
modify.removeOnLengthsLargerThan(food, 10)
console.log('removeOnLengthsLargerThan',food);
tableCreate(food);


问:
Why are user-defined conversions to and from only allowed without generics?
```<code>using System;

public class Program
{
    public static void Main()
    {
        T<A> g = new T<A>();
        T2 g = new T2();
    }
}

public class T<A>
{
    public static extern implicit operator T<A> (A v);
}

public class T2
{
    public static extern implicit operator T2 (A v);
}

public interface A{}
</code>```

Fiddle

The code only works with T of A. With T2 it gives the error "Compilation error (line 19, col 26): T2.implicit operator T2(A): user-defined conversions to or from an interface are not allowed", why is it allowed with generics? Are there any limitations to using generics as a workaround?

This question is not a duplicate of this question because this question is asking why it is allowed with generics and if there are any limitations to this workaround not why user-defined conversions to and from interfaces are not allowed.

答:
Actually both would not work, however you have re-defined A in your T class to be a generic parameter. If you rename your class to T and use B in the approprate spots it will give you the same error for the generic conversion.

```<code>public class T<B>
{
    public static extern implicit operator T<B> (A v);
}
</code>```

gives the error

Compilation error (line 14, col 26): T.implicit operator T(A): user-defined conversions to or from an interface are not allowed

The problem you are having has nothing to do with generics and is instead caused by the fact that you are trying to do a implicit conversion from a interface. If you switched A to a class instead of a interface both methods would work.

```<code>using System;

public class Program
{
    public static void Main()
    {
        T<A> g = new T<A>();
        T2 g2 = new T2();
    }
}

public class T<B>
{
    public static extern implicit operator T<B> (A v);
}

public class T2
{
    public static extern implicit operator T2 (A v);
}

public class A{}
</code>```

Body:
using System;

public class Program
{
    public static void Main()
    {
        T g = new T();
        T2 g = new T2();
    }
}

public class T
{
    public static extern implicit operator T (A v);
}

public class T2
{
    public static extern implicit operator T2 (A v);
}

public interface A{}

Fiddle

The code only works with T of A. With T2 it gives the error "Compilation error (line 19, col 26): T2.implicit operator T2(A): user-defined conversions to or from an interface are not allowed", why is it allowed with generics? Are there any limitations to using generics as a workaround?

This question is not a duplicate of this question because this question is asking why it is allowed with generics and if there are any limitations to this workaround not why user-defined conversions to and from interfaces are not allowed.

Body:
Actually both would not work, however you have re-defined A in your T<A> class to be a generic parameter. If you rename your class to T<B> and use B in the approprate spots it will give you the same error for the generic conversion.

public class T<B>
{
    public static extern implicit operator T<B> (A v);
}

gives the error

Compilation error (line 14, col 26): T<B>.implicit operator T<B>(A): user-defined conversions to or from an interface are not allowed

The problem you are having has nothing to do with generics and is instead caused by the fact that you are trying to do a implicit conversion from a interface. If you switched A to a class instead of a interface both methods would work.

using System;

public class Program
{
    public static void Main()
    {
        T<A> g = new T<A>();
        T2 g2 = new T2();
    }
}

public class T<B>
{
    public static extern implicit operator T<B> (A v);
}

public class T2
{
    public static extern implicit operator T2 (A v);
}

public class A{}


问:
How to make create and update use the same route
I have a route and form that looks like this:

```<code><%= form_for @address, url: {action: "update_contact", controller: "checkouts"}, html: {class: ""} do |f| %>
</code>```

My route looks like:

```<code>post "checkouts/:cart_token/update_contact" => "checkouts#update_contact", as: "checkouts_update_contact"
</code>```

For updates the form is looking for a PATCH which I haven't defined, and so I get an error when the @address model already exists i.e. updates

How can I make my form always POST no matter what?

答:
Add method: :post

```<code><%= form_for @address,
    url: {action: "update_contact", controller: "checkouts"},
    html: {class: ""},
    method: :post do |f| %>
</code>```

Without that Rails adds a hidden field which is used to fake a PATCH request when the form is used to update an object.

```<code><input type="hidden" name="_method" value="patch" />
</code>```

Body:
I have a route and form that looks like this:

<%= form_for @address, url: {action: "update_contact", controller: "checkouts"}, html: {class: ""} do |f| %>

My route looks like:

post "checkouts/:cart_token/update_contact" => "checkouts#update_contact", as: "checkouts_update_contact"

For updates the form is looking for a PATCH which I haven't defined, and so I get an error when the @address model already exists i.e. updates

How can I make my form always POST no matter what?

Body:
Add method: :post

<%= form_for @address,
    url: {action: "update_contact", controller: "checkouts"},
    html: {class: ""},
    method: :post do |f| %>

Without that Rails adds a hidden field which is used to fake a PATCH request when the form is used to update an object.

<input type="hidden" name="_method" value="patch" />


问:
Minimizing a multivariable function of loop iterations
I'm trying to minimize a function f of ~80 variables stored in an array. The function is defined by two nested loops: the outer one indexes array by i, while the inner loop is performed array[i] times and adds the result of a computation to a running total. The computation depends on some conditions x and y and changes slightly every time it's performed, which is why I need the loop structure. Here is a minimal working example in Python:

```<code>def f[array]:
    total = 0
    x = 0
    y = 0
    for i in range(len(array)):
        for j in range(array[i]):
            result = 2*x + y
            total = total + result
            x = x+1
        x = 0
        y = y+1
    return total
</code>```

So for instance, print f([2,1]) returns 3, since [(2*0) + 0] + [(2*1) + 0] + [(2*0) + 1] = 0+2+1 = 3.

I want to find the entries of array that minimize the value of f. However, when I tell (e.g.) Mathematica to minimize f([x1, x2, ..., x80]) and spit out the minimizer array, the program complains because it can't perform the loops defining f an indeterminate number of times.

In light of this, my question is the following:

How do I minimize a multivariate function whose parameters describe the number of times a given loop is to be iterated?

I had originally tried to implement this in Mathematica, but found that I could not define f by the procedure above. The best I could do is tell Mathematica to perform the loops above, then define f[array_] := total after total had been computed. When I ran my code, Mathematica naturally claimed that it could not evaluate f, throwing an error even before it executed my command to NMinimize[{f[array] array ϵ Integers}, array]. The fact that Mathematica is trying to evaluate f before it is called in NMinimize indicates that I don't quite understand how functions work in Mathematica. Any help in untangling this situation would be greatly appreciated!

答: As written your function has an analytical minimum and there is no need for numerical optimization. Unfortunately, StackOverflow won't let me show the mathematics of it (if you ask it on MathExchange I can provide a derivation), but given an array A = [a0 a1 ... an] where each ai is a positive integer, and an array Y = [0 1 ... n] the function you posted reduces to the following matrix multiplication A * (A - 1 + Y)' where ' denotes a matrix transpose and * denotes matrix multiplication. So, trivially, the function is minimized when each ai is minimized. So, if this is part of a larger optimization, your task should be focused on finding the minimum of each element of A if the elements themselves are constrained.

Body:
I'm trying to minimize a function f of ~80 variables stored in an array. The function is defined by two nested loops: the outer one indexes array by i, while the inner loop is performed array[i] times and adds the result of a computation to a running total. The computation depends on some conditions x and y and changes slightly every time it's performed, which is why I need the loop structure. Here is a minimal working example in Python:

def f[array]:
    total = 0
    x = 0
    y = 0
    for i in range(len(array)):
        for j in range(array[i]):
            result = 2*x + y
            total = total + result
            x = x+1
        x = 0
        y = y+1
    return total

So for instance, print f([2,1]) returns 3, since [(2*0) + 0] + [(2*1) + 0] + [(2*0) + 1] = 0+2+1 = 3.

I want to find the entries of array that minimize the value of f. However, when I tell (e.g.) Mathematica to minimize f([x1, x2, ..., x80]) and spit out the minimizer array, the program complains because it can't perform the loops defining f an indeterminate number of times.

In light of this, my question is the following:

How do I minimize a multivariate function whose parameters describe the number of times a given loop is to be iterated?

I had originally tried to implement this in Mathematica, but found that I could not define f by the procedure above. The best I could do is tell Mathematica to perform the loops above, then define f[array_] := total after total had been computed. When I ran my code, Mathematica naturally claimed that it could not evaluate f, throwing an error even before it executed my command to NMinimize[{f[array] array ϵ Integers}, array]. The fact that Mathematica is trying to evaluate f before it is called in NMinimize indicates that I don't quite understand how functions work in Mathematica. Any help in untangling this situation would be greatly appreciated!