问:
Can't send keys selenium webdriver python
Trying to execute simple test

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()

driver.get('http://google.com')
driver.find_element_by_name('q')
driver.send_keys('hey')
</code>```

And getting the error

```<code>Traceback (most recent call last):
  File "C:/webdriver/test.py", line 8, in <module>
    driver.send_keys('hey')
AttributeError: 'WebDriver' object has no attribute 'send_keys'
</code>```

What's the problem?

答:
You must change the reference element</p>

```<code>driver.get('http://google.com')
elem.find_element_by_name('q')
elem.send_keys('hey')
</code>```

Body:
Trying to execute simple test

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()

driver.get('http://google.com')
driver.find_element_by_name('q')
driver.send_keys('hey')

And getting the error

Traceback (most recent call last):
  File "C:/webdriver/test.py", line 8, in <module>
    driver.send_keys('hey')
AttributeError: 'WebDriver' object has no attribute 'send_keys'

What's the problem?

Body:
You must change the reference element

driver.get('http://google.com')
elem.find_element_by_name('q')
elem.send_keys('hey')


来源: stackexchange

问:
Typescript import using path from some root
Is there any simple way to set up so that I can import starting from some root point?

e.g.:

```<code>- module1
   \- file1.ts
- module2
   \- file2.ts
</code>```

in file2 i want to import file1

```<code>import { foo } from '../module1/file1'
</code>```

What I would like to do instead is something like:

```<code>import { foo } from 'src/module1/file1'
</code>```

Angular2 somehow uses this (see https://github.com/angular/angular/blob/master/modules/angular2/src/core/compiler/compiler.ts). I looked into their build process, but it's so complex, I'm not sure how they enabled this.

答:
I am working with Angular CLI and the standard structure it produces.

So everything I work with is in src/app.

My main HTTP service is located at src/app/services/httpService.ts.

To get import this service I use:

```<code>import { HttpService } from 'app/services/httpService'
</code>```

I'm not sure if this relies on any special config that Angular CLI does (and I realise Angular CLI wasn't around at the time this question was posted) but it would be worth a try in your environment.

ContentLicense: CC BY-SA 3.0

Body:
Is there any simple way to set up so that I can import starting from some root point?

e.g.:

- module1
   \- file1.ts
- module2
   \- file2.ts

in file2 i want to import file1

import { foo } from '../module1/file1'

What I would like to do instead is something like:

import { foo } from 'src/module1/file1'

Angular2 somehow uses this (see https://github.com/angular/angular/blob/master/modules/angular2/src/core/compiler/compiler.ts). I looked into their build process, but it's so complex, I'm not sure how they enabled this.

Body:
I am working with Angular CLI and the standard structure it produces.

So everything I work with is in src/app.

My main HTTP service is located at src/app/services/httpService.ts.

To get import this service I use:

import { HttpService } from 'app/services/httpService'

I'm not sure if this relies on any special config that Angular CLI does (and I realise Angular CLI wasn't around at the time this question was posted) but it would be worth a try in your environment.


问:
i'm not able to update the label when i tapped on stepper which is placed in uitable view cell
here is the image i had designed
here is the code for UITableviewCell and in this I had placed the stepper action method to trigger but unable to update the price label when I tap on stepper can anyone help me?

```<code>class productTableViewCell: UITableViewCell {

    @IBOutlet var stepper: UIStepper!
    @IBOutlet var imageview: UIImageView!
    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var priceLabel: UILabel!
    @IBOutlet var quantityTextField: UITextField!
    var pricearr = [String]()
    var price : String = ""
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    @IBAction func changeCart(_ sender: Any) {
        let value = Int(stepper.value)
        quantityTextField.text = String(value)
   }
}
</code>```

Here is the code for UITableViewCell and in this I had placed the stepper action method to trigger but unable to update the price label when I tap on the stepper can anyone help me?

```<code> @IBOutlet var tableDetails: UITableView!
    var productsArray = [String]()
    var nameArray = [String]()
    var priceArray = [String]()
    let urlstring = "http://www.json-generator.com/api/json/get/ceghMiWudK?indent=2"
    var price = [String]()
    var sum = 0

    override func viewDidLoad() {
        super.viewDidLoad()
       self.downloadJsonWithURL()
        tableDetails.delegate = self
        tableDetails.dataSource = self
        tableDetails.alwaysBounceVertical = false
        // Do any additional setup after loading the view.
    }

    func downloadJsonWithURL() {
            let url = NSURL(string: urlstring)
            URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
                if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                    print(jsonObj!.value(forKey: "Detail"))
                if let detailsArray = jsonObj!.value(forKey: "Detail") as? NSArray {
                    for item in detailsArray {
                        if let detailDict = item as? NSDictionary {
                            if let name = detailDict.value(forKey: "productName"){
                                self.nameArray.append(name as! String)
                            }
                            if let price = detailDict.value(forKey: "productPrice"){
                                self.priceArray.append(price as! String)
                            }
                            if let image = detailDict.value(forKey: "img"){
                                self.productsArray.append(image as! String)
                            }
                        }
                    }
                }
                OperationQueue.main.addOperation({
                    self.tableDetails.reloadData()
                    for item in self.priceArray{
                        let endIndex = item.index(item.endIndex, offsetBy: -5)
                        let truncated = item.substring(to: endIndex)
                        self.price.append(truncated)
                    }
                    print(self.price)
                })
            }
        }).resume()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 3
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if (section == 0){
            return productsArray.count
        }else{
            return 1
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! productTableViewCell
            let arr = self.productsArray[indexPath.row]
            let urls = NSURL(string: arr)
            let data = NSData (contentsOf: urls! as URL)
            cell.imageview.image = UIImage(data: data! as Data)
            cell.nameLabel.text = nameArray[indexPath.row]
            let x = priceArray[indexPath.row]
            let array = String(x)
            cell.priceLabel.text = array
            cell.quantityTextField.text = "1"
            cell.pricearr = [price[indexPath.row]]
            return cell
        }else if indexPath.section == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "couponcell", for: indexPath) as! CouponTableViewCell
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "checkout", for: indexPath) as! checkoutTableViewCell
            return cell
        }
    }
</code>```

答:
I think the problem is with the following line

```<code> priceLabel.text = x * String(value)
</code>```

What are you trying to accomplish here? This should not compile

Body:
here is the image i had designed
here is the code for UITableviewCell and in this I had placed the stepper action method to trigger but unable to update the price label when I tap on stepper can anyone help me?

class productTableViewCell: UITableViewCell {

    @IBOutlet var stepper: UIStepper!
    @IBOutlet var imageview: UIImageView!
    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var priceLabel: UILabel!
    @IBOutlet var quantityTextField: UITextField!
    var pricearr = [String]()
    var price : String = ""
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    @IBAction func changeCart(_ sender: Any) {
        let value = Int(stepper.value)
        quantityTextField.text = String(value)
   }
}

Here is the code for UITableViewCell and in this I had placed the stepper action method to trigger but unable to update the price label when I tap on the stepper can anyone help me?

 @IBOutlet var tableDetails: UITableView!
    var productsArray = [String]()
    var nameArray = [String]()
    var priceArray = [String]()
    let urlstring = "http://www.json-generator.com/api/json/get/ceghMiWudK?indent=2"
    var price = [String]()
    var sum = 0

    override func viewDidLoad() {
        super.viewDidLoad()
       self.downloadJsonWithURL()
        tableDetails.delegate = self
        tableDetails.dataSource = self
        tableDetails.alwaysBounceVertical = false
        // Do any additional setup after loading the view.
    }

    func downloadJsonWithURL() {
            let url = NSURL(string: urlstring)
            URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
                if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                    print(jsonObj!.value(forKey: "Detail"))
                if let detailsArray = jsonObj!.value(forKey: "Detail") as? NSArray {
                    for item in detailsArray {
                        if let detailDict = item as? NSDictionary {
                            if let name = detailDict.value(forKey: "productName"){
                                self.nameArray.append(name as! String)
                            }
                            if let price = detailDict.value(forKey: "productPrice"){
                                self.priceArray.append(price as! String)
                            }
                            if let image = detailDict.value(forKey: "img"){
                                self.productsArray.append(image as! String)
                            }
                        }
                    }
                }
                OperationQueue.main.addOperation({
                    self.tableDetails.reloadData()
                    for item in self.priceArray{
                        let endIndex = item.index(item.endIndex, offsetBy: -5)
                        let truncated = item.substring(to: endIndex)
                        self.price.append(truncated)
                    }
                    print(self.price)
                })
            }
        }).resume()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 3
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if (section == 0){
            return productsArray.count
        }else{
            return 1
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! productTableViewCell
            let arr = self.productsArray[indexPath.row]
            let urls = NSURL(string: arr)
            let data = NSData (contentsOf: urls! as URL)
            cell.imageview.image = UIImage(data: data! as Data)
            cell.nameLabel.text = nameArray[indexPath.row]
            let x = priceArray[indexPath.row]
            let array = String(x)
            cell.priceLabel.text = array
            cell.quantityTextField.text = "1"
            cell.pricearr = [price[indexPath.row]]
            return cell
        }else if indexPath.section == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "couponcell", for: indexPath) as! CouponTableViewCell
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "checkout", for: indexPath) as! checkoutTableViewCell
            return cell
        }
    }

Body:
I think the problem is with the following line

 priceLabel.text = x * String(value)

What are you trying to accomplish here? This should not compile


问:
Rails server is running, but cannot connect to localhost:3000
I am learning Ruby on Rails with railstutorial.org
I had set everything up and working fine from Chapter 1. However, all of a sudden my next app has an issue.

I run "rails server"

```<code>=> Booting WEBrick
=> Rails 3.2.9 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-11-15 00:45:08] INFO  WEBrick 1.3.1
[2012-11-15 00:45:08] INFO  ruby 1.9.3 (2012-11-10) [x86_64-linux]
[2012-11-15 00:45:08] INFO  WEBrick::HTTPServer#start: pid=2752 port=3000
</code>```

Seems to be working fine, just like with my previous app.

However, I try connecting to localhost:3000 , 0.0.0.0:3000 , 127.0.0.1:3000 on various browsers and they all cannot establish a connection to the server.

Some things to note:

-I was able to connect to localhost just a while ago--it just seems like it suddenly stopped working out of the blue.

-My first app was working perfectly fine, but now it doesn't work for my first app either.

-I don't have firewalls blocking the port, and my hosts file is not the problem.

-I am on Ubuntu 12.10

I almost always find solutions via search, but not this time.. so I need some help please. It's very frustrating as I feel like it's a simple problem that I spent way too long being stuck on.

Thank you.

答: check your /etc/hosts file..is ip 0.0.0.0 or localhost pointing to some other address.</p>

Body:
I am learning Ruby on Rails with railstutorial.org
I had set everything up and working fine from Chapter 1. However, all of a sudden my next app has an issue.

I run "rails server"

=> Booting WEBrick
=> Rails 3.2.9 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-11-15 00:45:08] INFO  WEBrick 1.3.1
[2012-11-15 00:45:08] INFO  ruby 1.9.3 (2012-11-10) [x86_64-linux]
[2012-11-15 00:45:08] INFO  WEBrick::HTTPServer#start: pid=2752 port=3000

Seems to be working fine, just like with my previous app.

However, I try connecting to localhost:3000 , 0.0.0.0:3000 , 127.0.0.1:3000 on various browsers and they all cannot establish a connection to the server.

Some things to note:

-I was able to connect to localhost just a while ago--it just seems like it suddenly stopped working out of the blue.

-My first app was working perfectly fine, but now it doesn't work for my first app either.

-I don't have firewalls blocking the port, and my hosts file is not the problem.

-I am on Ubuntu 12.10

I almost always find solutions via search, but not this time.. so I need some help please. It's very frustrating as I feel like it's a simple problem that I spent way too long being stuck on.

Thank you.


问:
How to add manufacturer attribute on Checkout Page in Magento 2
I need add manufacturer attribute next to product name on Checkout Page. I will be grateful for any help. </p>

答:
Thank You MageVision Team :-)

https://www.magevision.com/blog/post/get-a-product-attribute-in-checkout-summary-magento-2/


问:
Hide terminal, C + GTK
```<code>gcc -o program program.c `pkg-config --libs --cflags gtk+-2.0`
</code>```

When I run the program, it show both the GUI and the terminal. How can I hide the terminal?

答: add -mwindows parameter to compiler command line </p>

ContentLicense: CC BY-SA 2.5

Title: Hide terminal, C + GTK

Body:
gcc -o program program.c `pkg-config --libs --cflags gtk+-2.0`

When I run the program, it show both the GUI and the terminal. How can I hide the terminal?


问:
how to make text over images in a row using bootstrap?
Now it is not responsive, the two images should be in one row. I want to make text like painting and photography over these images. how can it be possible?

.caption {
  position: absolute;
  top: 9%;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.caption1 {
  position: absolute;
  top: -51px;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.imageandtext {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-two imageandtext">
  <figure>

    <img src="http://lorempixel.com/300/300/" class="img-thumbnail">
    <div class="caption">
      <p>Painting</p>
    </div>
    <div class="imageandtext image_grid">
      <img src="http://lorempixel.com/300/300/?r" class="img-thumbnail">
      <div class="caption1">
        <p>Photography</p>
      </div>
    </div>
  </figure>
</div></code>```

答:
Update css part

```<code>    figure {
      display: flex; /*For image lineup */
    }
   .imageandtext, .image_grid {
      position: relative;
    }

   .imageandtext, .image_grid {
       position: relative;
       margin:5px;
    }
</code>```

figure {
  display: flex;
}

.caption {
  position: absolute;
  top: 9%;/*Change as your need*/
  left: 52px;/*Change as your need*/
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.caption1 {
  position: absolute;
  top: 51px; /*Change as your need*/
  left: 11px; /*Change as your need*/
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.imageandtext,
.image_grid {
  position: relative;
  margin:5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-two imageandtext">
  <figure>
    <img src="http://lorempixel.com/300/300/" class="img-thumbnail">
    <div class="caption">
      <p>Painting</p>
    </div>
    <div class="imageandtext image_grid">
      <img src="http://lorempixel.com/300/300/?r" class="img-thumbnail">
      <div class="caption1">
        <p>Photography</p>
      </div>
    </div>
  </figure>
</div></code>```

Body:
Now it is not responsive, the two images should be in one row. I want to make text like painting and photography over these images. how can it be possible?

.caption {
  position: absolute;
  top: 9%;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.caption1 {
  position: absolute;
  top: -51px;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.imageandtext {
  position: relative;
}

Painting

Photography

Body:
Update css part

    figure {
      display: flex; /*For image lineup */
    }
   .imageandtext, .image_grid {
      position: relative;
    }

   .imageandtext, .image_grid {
       position: relative;
       margin:5px;
    }

figure {
  display: flex;
}

.caption {
  position: absolute;
  top: 9%;/*Change as your need*/
  left: 52px;/*Change as your need*/
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.caption1 {
  position: absolute;
  top: 51px; /*Change as your need*/
  left: 11px; /*Change as your need*/
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.imageandtext,
.image_grid {
  position: relative;
  margin:5px;
}

<div class="grid-two imageandtext">
  <figure>
    <img src="http://lorempixel.com/300/300/" class="img-thumbnail">
    <div class="caption">
      <p>Painting</p>
    </div>
    <div class="imageandtext image_grid">
      <img src="http://lorempixel.com/300/300/?r" class="img-thumbnail">
      <div class="caption1">
        <p>Photography</p>
      </div>
    </div>
  </figure>
</div>


问:
Getting 404 while calling rest api developed in Spring
Controller

```<code>package com.example;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ws")
public class Controller {
    @RequestMapping(value="/req", method = RequestMethod.GET,produces="application/json")
    TestBean readBookmarks() {
    TestBean bean = new TestBean("Test", 25);
    return bean;
}
}
</code>```

Web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
<display-name>Spring MVC Application</display-name>
  <servlet>
    <servlet-name>App</servlet-name>
    <servlet-class>  org.springframework.web.servlet.DispatcherServlet</servlet-class
<load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
    <servlet-name>App</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
</code>```

App-Servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-
 context.xsd">

<context:component-scan base-package="com.example"/>
</beans>
</code>```

When I try to hit http://localhost:8080/ws/req on browser it says HTTP Status 404.

URL's are registered as observed in logs:

```<code>Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:MathWebApp' did not find a matching property.
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          May 10 2017 17:21:09 UTC
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         8.0.44.0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Mac OS X
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.12.4
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          x86_64
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/jre
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_111-b14
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         /Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         /Users/kegupta/Desktop/apache-tomcat-8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=/Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=/Users/kegupta/Desktop/apache-tomcat-8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=/Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=/Users/kegupta/Desktop/apache-tomcat-8.0.44/endorsed
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/kegupta/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
Jun 07, 2017 10:35:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 07, 2017 10:35:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 480 ms
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.44
Jun 07, 2017 10:35:40 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 07, 2017 10:35:40 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Jun 07, 2017 10:35:40 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'App'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'App': initialization started
Jun 07, 2017 10:35:40 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'App-servlet': startup date [Wed Jun 07 10:35:40 IST 2017]; root of context hierarchy
Jun 07, 2017 10:35:40 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/App-servlet.xml]
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req.*] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req/] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'App': initialization completed in 617 ms
Jun 07, 2017 10:35:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Jun 07, 2017 10:35:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Jun 07, 2017 10:35:40 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1514 ms
</code>```

I am stuck since very long. Any help would be greatly appreciated.

答:
From the logs i can see a war name App is being deployed. Try using this url : </p>

```<code>http://localhost:8080/App/ws/req

Or

http://localhost:8080/<deployed tomcat war name>/ws/req
</code>```

Body:
Controller

package com.example;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ws")
public class Controller {
    @RequestMapping(value="/req", method = RequestMethod.GET,produces="application/json")
    TestBean readBookmarks() {
    TestBean bean = new TestBean("Test", 25);
    return bean;
}
}

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
<display-name>Spring MVC Application</display-name>
  <servlet>
    <servlet-name>App</servlet-name>
    <servlet-class>  org.springframework.web.servlet.DispatcherServlet</servlet-class
<load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
    <servlet-name>App</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

App-Servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-
 context.xsd">

<context:component-scan base-package="com.example"/>
</beans>

When I try to hit http://localhost:8080/ws/req on browser it says HTTP Status 404.

URL's are registered as observed in logs:

Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:MathWebApp' did not find a matching property.
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          May 10 2017 17:21:09 UTC
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         8.0.44.0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Mac OS X
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.12.4
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          x86_64
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/jre
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_111-b14
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         /Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         /Users/kegupta/Desktop/apache-tomcat-8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=/Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=/Users/kegupta/Desktop/apache-tomcat-8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=/Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=/Users/kegupta/Desktop/apache-tomcat-8.0.44/endorsed
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/kegupta/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
Jun 07, 2017 10:35:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 07, 2017 10:35:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 480 ms
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.44
Jun 07, 2017 10:35:40 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 07, 2017 10:35:40 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Jun 07, 2017 10:35:40 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'App'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'App': initialization started
Jun 07, 2017 10:35:40 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'App-servlet': startup date [Wed Jun 07 10:35:40 IST 2017]; root of context hierarchy
Jun 07, 2017 10:35:40 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/App-servlet.xml]
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req.*] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req/] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'App': initialization completed in 617 ms
Jun 07, 2017 10:35:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Jun 07, 2017 10:35:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Jun 07, 2017 10:35:40 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1514 ms

I am stuck since very long. Any help would be greatly appreciated.

Body:
From the logs i can see a war name App is being deployed. Try using this url :

http://localhost:8080/App/ws/req

Or

http://localhost:8080/<deployed tomcat war name>/ws/req


问:
Find matching values in a row and sum them up (excel)
Please help with the following I'm assuming SUPER SIMPLE excel solution that I can't for the life of me figure out.

In Sheet1 I have people and total:

```<code>People | Total
John   | (9=6+2+1)<=formula goes here
James  |
Adam   |
</code>```

In Sheet2 I have their info as follows:

```<code>People | Total
John   | 6
John   | 2
John   | 1
James  | 4
James  | 8
James  | 6
James  | 2
Adam   | 1
Adam   | 3
</code>```

How can I have excel search for all the matching names in sheet2 e.g. John, find their scores 6,2,1 and sum them up? The names are unique to the users so no two "Johns" are alike. Thank you!

答:
The SUMIF function helps here:

The formula should look similar to this

```<code>=SUMIF(Sheet2!$A$2:$A$10;Sheet1!A2;Sheet2!$B$2:$B$10)
</code>```

This assumes that A2 is the name of one of your persons (in your example John) and that your values are in a sheet called "Sheet2" within the range A2 - B10. Just put your formula in column B2 (the one next to John)

Body:
Please help with the following I'm assuming SUPER SIMPLE excel solution that I can't for the life of me figure out.

In Sheet1 I have people and total:

People | Total
John   | (9=6+2+1)<=formula goes here
James  |
Adam   |

In Sheet2 I have their info as follows:

People | Total
John   | 6
John   | 2
John   | 1
James  | 4
James  | 8
James  | 6
James  | 2
Adam   | 1
Adam   | 3

How can I have excel search for all the matching names in sheet2 e.g. John, find their scores 6,2,1 and sum them up? The names are unique to the users so no two "Johns" are alike. Thank you!

Body:
The SUMIF function helps here:

The formula should look similar to this

=SUMIF(Sheet2!$A$2:$A$10;Sheet1!A2;Sheet2!$B$2:$B$10)

This assumes that A2 is the name of one of your persons (in your example John) and that your values are in a sheet called "Sheet2" within the range A2 - B10. Just put your formula in column B2 (the one next to John)


问:
log4j JDBCAppender rotate table name
I have successfully configured an application that uses log4j for it's logging to log into a MySQL database. (Using org.apache.log4j.jdbc.JDBCAppender).

I also have some perl applications that log into the database as well. My perl apps are setup so that the name of the database table changes every month (log_2010_11, log_2010_10 etc). At the end of each month, I run reporting scripts on the month just completed, dump the table to an external file (which gets compressed and archived), and then drop the table. This way the total size of the logging database stays within sensible limits.

I would like to do the same with log4j, but there does not appear to be a log4j appender suitable for the purpose.

Is it possible to do something like this:

```<code>log4j.appender.SQ=org.apache.log4j.jdbc.JDBCRollingAppender

log4j.appender.SQ.Driver=com.mysql.jdbc.Driver

log4j.appender.SQ.URL=jdbc:mysql://localhost:3306/logs_{%year}_{%month}
</code>```

Thank you.

答: How about a script to run monthly and dump that particular table into a back up file and then zip it for archiving.  Upon complete, truncate the table or delete rows within date range.</p>

Title: log4j JDBCAppender rotate table name

Body:
I have successfully configured an application that uses log4j for it's logging to log into a MySQL database. (Using org.apache.log4j.jdbc.JDBCAppender).

I also have some perl applications that log into the database as well. My perl apps are setup so that the name of the database table changes every month (log_2010_11, log_2010_10 etc). At the end of each month, I run reporting scripts on the month just completed, dump the table to an external file (which gets compressed and archived), and then drop the table. This way the total size of the logging database stays within sensible limits.

I would like to do the same with log4j, but there does not appear to be a log4j appender suitable for the purpose.

Is it possible to do something like this:

log4j.appender.SQ=org.apache.log4j.jdbc.JDBCRollingAppender

log4j.appender.SQ.Driver=com.mysql.jdbc.Driver

log4j.appender.SQ.URL=jdbc:mysql://localhost:3306/logs_{%year}_{%month}

Thank you.


问:
This project does not use the Gradle build system warning to imported Boofcv into Android Studio
So, Finally I have install BoofCV into Android Studio (Tx to Q&A on this website) and all examples are running perfectly by opening pop up windows (including Template Matching and Webcam Capture):

but message in Event Log [says], 'Migrate Project to Gradle? This project does not use the Gradle build system. We recommend that you migrate to using the Gradle build system.' So, what changes should I do!?

I want to create an app of Template matching via Webcam. Is it possible to create my app ignoring above warning message.!?

Thanks in Advance.

答:
You are having this error because you started the android project by just opening it on android studio.

Here is the fix, instead Import the project like this:

File -> New-> import project

And Voila, the issue will be resolved.


问:
Dates and MongoDB - FAIL
I've found a TON of documentation on working with dates in mongodb. Unfortunately none of it seems to work as it's supposed to. Here's my problem... I'm trying to query by date. This is what my document looks like when I just search with a find():

```<code>{
    "_id": ObjectId("5935ff97d1d72d2134d7ad8f"),
    "username": "Test",
    "email": "test@test",
    "password": "sha1$8dbb9bdc$1$b0096596e0e3aba3ad883489bc713b0462ad6472",
    "access": "test",
    "cookies": [{
            "hash": "ZOddh981SZ7uiw3XPQYwJzET18byscWo3BV0RzIc8Eo8QY2VdlVm23qs28AAvxPx",
            "exipires": ISODate("2017-06-12T01:34:45.895Z")
        }, {
            "hash": "gk8voLrc2JtX832GExcWlSoVdjkiEoFAvLQAayevtPJGJ7tCchYAP0it93aAMBlb",
            "exipires": "ISODate(\"2017-06-11 20:37:10.167\")"
        }
    ]
}
</code>```

(As you can see, I have 2 cookies. One with escaped quotes around the date, one without.)

And here are the searches I've tried so far:

```<code>db.getCollection("auth").find({ 'cookies.expires': {'$gte': {$date: "2017-06-07T01:37:14.362Z"} } })
db.getCollection("auth").find({ 'cookies.expires': {'$lte': {$date: "2017-06-07T01:37:14.362Z"} } })
db.getCollection("auth").find('cookies.expires': { '$gte': new ISODate("2017-06-07T01:37:14.362Z") } })
db.getCollection("auth").find('cookies.expires': { '$lte': new ISODate("2017-06-07T01:37:14.362Z") } })
db.getCollection("auth").find('cookies.expires': { '$gte': new ISODate() } })
db.getCollection("auth").find('cookies.expires': { '$gte': new Date("2017-06-07T01:37:14.362Z") } })
db.getCollection("auth").find('cookies.expires': { '$lte': new Date("2017-06-07T01:37:14.362Z") } })
db.getCollection("auth").find('cookies.expires': { '$gte': new Date("2017-06-07T01:37:14.362Z") } })
</code>```

I'm pretty positive that the search SHOULD be for $gte, since I want to find all dates in the future. But I've tried both ways just in case it was backwards from what I expected.

None of these work and I can't figure out why - been at this for a good 2 hours now. A fresh set of eyes would be appreciated.

答:
```<code>db.getCollection("auth").find({
      'cookies.expires': { '$gte': ISODate("2017-06-07T01:37:14.362Z") }
})
</code>```

Title: Dates and MongoDB - FAIL

Body:
I've found a TON of documentation on working with dates in mongodb. Unfortunately none of it seems to work as it's supposed to. Here's my problem... I'm trying to query by date. This is what my document looks like when I just search with a find():

{
    "_id": ObjectId("5935ff97d1d72d2134d7ad8f"),
    "username": "Test",
    "email": "test@test",
    "password": "sha1$8dbb9bdc$1$b0096596e0e3aba3ad883489bc713b0462ad6472",
    "access": "test",
    "cookies": [{
            "hash": "ZOddh981SZ7uiw3XPQYwJzET18byscWo3BV0RzIc8Eo8QY2VdlVm23qs28AAvxPx",
            "exipires": ISODate("2017-06-12T01:34:45.895Z")
        }, {
            "hash": "gk8voLrc2JtX832GExcWlSoVdjkiEoFAvLQAayevtPJGJ7tCchYAP0it93aAMBlb",
            "exipires": "ISODate(\"2017-06-11 20:37:10.167\")"
        }
    ]
}

(As you can see, I have 2 cookies. One with escaped quotes around the date, one without.)

And here are the searches I've tried so far:

db.getCollection("auth").find({ 'cookies.expires': {'$gte': {$date: "2017-06-07T01:37:14.362Z"} } })
db.getCollection("auth").find({ 'cookies.expires': {'$lte': {$date: "2017-06-07T01:37:14.362Z"} } })
db.getCollection("auth").find('cookies.expires': { '$gte': new ISODate("2017-06-07T01:37:14.362Z") } })
db.getCollection("auth").find('cookies.expires': { '$lte': new ISODate("2017-06-07T01:37:14.362Z") } })
db.getCollection("auth").find('cookies.expires': { '$gte': new ISODate() } })
db.getCollection("auth").find('cookies.expires': { '$gte': new Date("2017-06-07T01:37:14.362Z") } })
db.getCollection("auth").find('cookies.expires': { '$lte': new Date("2017-06-07T01:37:14.362Z") } })
db.getCollection("auth").find('cookies.expires': { '$gte': new Date("2017-06-07T01:37:14.362Z") } })

I'm pretty positive that the search SHOULD be for $gte, since I want to find all dates in the future. But I've tried both ways just in case it was backwards from what I expected.

None of these work and I can't figure out why - been at this for a good 2 hours now. A fresh set of eyes would be appreciated.


问:
Unable to insert records using insertMany using compose for mongodb
I am using nodejs to connect and insert records in compose for mongodb.I am getting the below error when I try to use insertMany and save records.

(node:10140) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: Writes to conf
  ig servers must have batch size of 1, found 23

Below is my code snippet:

```<code>MongoClient.connect(url, function(err, db) {

    if(err){
    console.log('Error is ' + err);
    }
    else{
     console.log("Connected correctly to server");
    try {
    var col = db.collection('offshift');
        col.insertMany(result).then(function(result){
         res.json({message:'Data saved succesfully!',error_code:0, data: result});
       });

    } catch (e) {
       console.log(e);
    }
     db.close();
    }
});
</code>```

答:
If you do not use promise unable to use .then(). So instead of .then() you can use callback function. can try bellow code

```<code>var col = db.collection('offshift');
  col.insertMany(result, function(error, result){
       if(error){
          console.log('Error is on insert', error);
        } else
           res.json({message:'Data saved succesfully!',error_code:0, data: result});
});
</code>```

OR

you can use .exec() that return promise and then can use .then()

```<code>var col = db.collection('offshift');
        col.insertMany(result).exec().then(.....)
</code>```

Body:
I am using nodejs to connect and insert records in compose for mongodb.I am getting the below error when I try to use insertMany and save records.

(node:10140) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: Writes to conf
  ig servers must have batch size of 1, found 23

Below is my code snippet:

MongoClient.connect(url, function(err, db) {

    if(err){
    console.log('Error is ' + err);
    }
    else{
     console.log("Connected correctly to server");
    try {
    var col = db.collection('offshift');
        col.insertMany(result).then(function(result){
         res.json({message:'Data saved succesfully!',error_code:0, data: result});
       });

    } catch (e) {
       console.log(e);
    }
     db.close();
    }
});

Body:
If you do not use promise unable to use .then(). So instead of .then() you can use callback function. can try bellow code

var col = db.collection('offshift');
  col.insertMany(result, function(error, result){
       if(error){
          console.log('Error is on insert', error);
        } else
           res.json({message:'Data saved succesfully!',error_code:0, data: result});
});

OR

you can use .exec() that return promise and then can use .then()

var col = db.collection('offshift');
        col.insertMany(result).exec().then(.....)


问:
How to replace "\\" to "\" C#
Here is an example: "\\\r\\\n\\\u003c"

Expected Result: "\r\n\u003c"

I have tried string.Replace(@"\\\", @"\");, but it doesn't work.

答: Replace the full char \\n to \n. Your way does't work because a backslash is used to escape charachters.

Title: How to replace "\\" to "\" C#


问:
Switch between classes / jQuery
I have a login form with some input methods like drop downs, blank fields. My client needs a feature that select yes or no switch like this.

So I used jQuery add/remove functions when click.

HTML:

```<code><div class="form-group">
  <label for="member" class="col-md-5 col-sm-12 control-label">
    Do you have the car right now?
  </label>
  <div class="col-lg-10">
    <div class="btn-group">
      <button type="button" class="btn btn-default btn-switch switch1 active"> <span class="goods">Yes</span>
      </button>
      <div class="btn-group">
        <button type="button" class="btn btn-default btn-switch switch1"><span class="services">No</span>
        </button>
      </div>
    </div>
  </div>
</div>
</code>```

CSS:

```<code>.switch1.active{
  background: #e46a5d!important;
  color: #fff;
  font-weight: normal;
  text-shadow: none;
}
</code>```

Here is a working link for jsfiddle But my problem is..

In some pages, I need to add more yes or no fields like 5 or 6. So I need to repeat jquery script more time.

So looking for a best practice to do in this kind of situation.

答:
Without changing your html structure you could simply replace your JS with this;</p>

```<code>   $('.btn-switch').click(function() {
     var $group = $(this).closest('.form-group');
     $('.btn-switch', $group).removeClass("active");
     $(this).addClass("active");
   });
</code>```

Title: Switch between classes / jQuery

Body:
I have a login form with some input methods like drop downs, blank fields. My client needs a feature that select yes or no switch like this.

So I used jQuery add/remove functions when click.

HTML:

    Do you have the car right now?

      <button type="button" class="btn btn-default btn-switch switch1 active"> Yes
      </button>

        <button type="button" class="btn btn-default btn-switch switch1">No
        </button>

CSS:

.switch1.active{
  background: #e46a5d!important;
  color: #fff;
  font-weight: normal;
  text-shadow: none;
}

Here is a working link for jsfiddle But my problem is..

In some pages, I need to add more yes or no fields like 5 or 6. So I need to repeat jquery script more time.

So looking for a best practice to do in this kind of situation.

Body:
Without changing your html structure you could simply replace your JS with this;

   $('.btn-switch').click(function() {
     var $group = $(this).closest('.form-group');
     $('.btn-switch', $group).removeClass("active");
     $(this).addClass("active");
   });


问:
C Encrypt data in file.txt
I have problem in encrypting my plain text in C.
I am able to write and read the file in C
Inside the text:

```<code>ID  Promo   Points  Password    Name
1   NONE    0       awdawdawd   daw
</code>```

Which in this case it just print password in plain text, Is it possible to encrypt the data any method, which shows like this:

```<code>ID  Promo   Points  Password    Name
1   NONE    0      ENCRYPTEDDATA daw
</code>```

Of course the password wont be "ENCRYPTEDDATA", I just want it avoid plain text which user can easily see the file.
The reason I create file cause I need to read it from the file and make a login function.
My program itself able to decrypt the password when in request of checking id and password.
It can use any method only the program can encrypt and decrypt the data
Any solution guys?
If possible I also need to limit the encrypted text

答:
You should hash password with strong hash function like SHA2 and  store the hash in your file rather than storing it in plain

Hashing might be better in this case than encryption, as for encryption you will have to worry about storing key somewhere securely.

When your login function needs to validate incoming password, you can just hash incoming password and match it against the hashed password from you file

Title: C Encrypt data in file.txt

Body:
I have problem in encrypting my plain text in C.
I am able to write and read the file in C
Inside the text:

ID  Promo   Points  Password    Name
1   NONE    0       awdawdawd   daw

Which in this case it just print password in plain text, Is it possible to encrypt the data any method, which shows like this:

ID  Promo   Points  Password    Name
1   NONE    0      ENCRYPTEDDATA daw

Of course the password wont be "ENCRYPTEDDATA", I just want it avoid plain text which user can easily see the file.
The reason I create file cause I need to read it from the file and make a login function.
My program itself able to decrypt the password when in request of checking id and password.
It can use any method only the program can encrypt and decrypt the data
Any solution guys?
If possible I also need to limit the encrypted text


问:
qt open a jpg file with warning image format not supported

I open a file of format "jpg" in qt creator ,but qt creator returns a warning with "image format not supported". I also try other format as "png" ,but the waring is same.I hope someone can give me advice on it.I really need help.

答:
This Warning is about PNG formats and Qt, Irrelevant to @ztono code.
Read more about PNG (Portable Network Graphics) https://en.wikipedia.org/wiki/Portable_Network_Graphics

PNG has many Formats some old, some not standard for Qt. see more History_and_development
You need to use Standard format in Qt.

You can convert your image to PNG Standard with Software.

OR

You can use QImage in Qt to convert your PNG pictures.

```<code>QImage *image = new QImage();
image->load("E:/Qt/TestProject/Images/connect.png");
image->save("E:/Qt/TestProject/Images/connect2.png");
</code>```

Use new converted png and you will not see the warning.

Body:
This Warning is about PNG formats and Qt, Irrelevant to @ztono code.
Read more about PNG (Portable Network Graphics) https://en.wikipedia.org/wiki/Portable_Network_Graphics

PNG has many Formats some old, some not standard for Qt. see more History_and_development
You need to use Standard format in Qt.

You can convert your image to PNG Standard with Software.

OR

You can use QImage in Qt to convert your PNG pictures.

QImage *image = new QImage();
image->load("E:/Qt/TestProject/Images/connect.png");
image->save("E:/Qt/TestProject/Images/connect2.png");

Use new converted png and you will not see the warning.


问:
Read Existing Avro File and Send to Kafka
I have an existing Avro File with the schema. I need to send the file to Producer.

Following is the code i have written.

```<code>public class ProducerDataSample {

    public static void main(String[] args) {

        String topic = "my-topic";

        Schema.Parser parser = new Schema.Parser();
        Schema schema = parser.parse(AvroSchemaDefinitionLoader.fromFile("encounter.avsc").get());

            File file = new File("/home/hello.avro");
        try{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
        DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);
        dataFileWriter.create(schema, outputStream);
        dataFileWriter.appendTo(file);
        dataFileWriter.close();
        System.out.println("Here comes the data: " + outputStream);

        // Start KAFKA publishing

        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092");
        props.put("serializer.class", "kafka.serializer.StringEncoder");
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");

        KafkaProducer<String, byte[]> messageProducer = new KafkaProducer<String, byte[]>(props);
        ProducerRecord<String, byte[]> producerRecord = null;
        producerRecord = new ProducerRecord<String, byte[]>("m-topic","1",outputStream.toByteArray());
        messageProducer.send(producerRecord);
        messageProducer.close();
        }catch(Exception e){
            System.out.println("Error in sending to kafka");
            e.printStackTrace();
        }

    }
}
</code>```

As soon as I execute this, I get the error:

```<code>Error in sending to kafka org.apache.avro.AvroRuntimeException: already open
at org.apache.avro.file.DataFileWriter.assertNotOpen(DataFileWriter.java:85)
at org.apache.avro.file.DataFileWriter.appendTo(DataFileWriter.java:203)
at org.apache.avro.file.DataFileWriter.appendTo(DataFileWriter.java:193)
at ProducerDataSample.main(ProducerDataSample.java:51)
</code>```

Any help.
Thanks.

答:
You will have to read the data from the avro file and serialize it to bytes array

Something like below snippet

```<code>        final Schema schema = new Schema.Parser().parse(new File("sample.avsc"));
        File file ="sample.avro"

        //read the avro file to GenericRecord
        final GenericDatumReader<GenericRecord> genericDatumReader = new GenericDatumReader<>(schema);
        final DataFileReader<GenericRecord> genericRecords = new DataFileReader<>(file, genericDatumReader);

        //serialize GenericRecords
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DatumWriter<GenericRecord> writer = new GenericDatumWriter<GenericRecord>(schema);

        Encoder binaryEncoder = EncoderFactory.get().binaryEncoder(out, null);

        while (genericRecords.hasNext()) {
            writer.write(genericRecords.next(), binaryEncoder);
        }
        binaryEncoder.flush();
        out.close();
       //send out.toByteArray() to kakfa
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an existing Avro File with the schema. I need to send the file to Producer.

Following is the code i have written.

public class ProducerDataSample {

    public static void main(String[] args) {

        String topic = "my-topic";

        Schema.Parser parser = new Schema.Parser();
        Schema schema = parser.parse(AvroSchemaDefinitionLoader.fromFile("encounter.avsc").get());

            File file = new File("/home/hello.avro");
        try{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
        DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);
        dataFileWriter.create(schema, outputStream);
        dataFileWriter.appendTo(file);
        dataFileWriter.close();
        System.out.println("Here comes the data: " + outputStream);

        // Start KAFKA publishing

        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092");
        props.put("serializer.class", "kafka.serializer.StringEncoder");
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");

        KafkaProducer<String, byte[]> messageProducer = new KafkaProducer<String, byte[]>(props);
        ProducerRecord<String, byte[]> producerRecord = null;
        producerRecord = new ProducerRecord<String, byte[]>("m-topic","1",outputStream.toByteArray());
        messageProducer.send(producerRecord);
        messageProducer.close();
        }catch(Exception e){
            System.out.println("Error in sending to kafka");
            e.printStackTrace();
        }

    }
}

As soon as I execute this, I get the error:

Error in sending to kafka org.apache.avro.AvroRuntimeException: already open
at org.apache.avro.file.DataFileWriter.assertNotOpen(DataFileWriter.java:85)
at org.apache.avro.file.DataFileWriter.appendTo(DataFileWriter.java:203)
at org.apache.avro.file.DataFileWriter.appendTo(DataFileWriter.java:193)
at ProducerDataSample.main(ProducerDataSample.java:51)

Any help.
Thanks.

Body:
You will have to read the data from the avro file and serialize it to bytes array

Something like below snippet

        final Schema schema = new Schema.Parser().parse(new File("sample.avsc"));
        File file ="sample.avro"

        //read the avro file to GenericRecord
        final GenericDatumReader<GenericRecord> genericDatumReader = new GenericDatumReader<>(schema);
        final DataFileReader<GenericRecord> genericRecords = new DataFileReader<>(file, genericDatumReader);

        //serialize GenericRecords
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DatumWriter<GenericRecord> writer = new GenericDatumWriter<GenericRecord>(schema);

        Encoder binaryEncoder = EncoderFactory.get().binaryEncoder(out, null);

        while (genericRecords.hasNext()) {
            writer.write(genericRecords.next(), binaryEncoder);
        }
        binaryEncoder.flush();
        out.close();
       //send out.toByteArray() to kakfa


问:
create empty workbook in memory openpyxl
```<code>from openpyxl import Workbook
book = Workbook()
for country in "IN US JP UK".split():
    book.create_sheet(title=country)
</code>```

This creates 5 sheets with the first sheet being unwanted.

I know that I can do this:

```<code>book = Workbook()
us_ws = book.active
us_ws.title = "IN"
for country in "US JP UK".split():
    book.create_sheet(title=country)
</code>```

Is there any short cut?

答:
From the (Docs)

A workbook is always created with at least one worksheet. You can get it by using the openpyxl.workbook.Workbook.active() property

So if you do not need the default sheet, you can delete it:

```<code>from openpyxl import Workbook

book = Workbook()
book.remove(book.active)
for country in "IN US JP UK".split():
    book.create_sheet(title=country)
</code>```

This deletes the first sheet, which will be the default created sheet, before creating the desired sheets.

Or, as pointed out in comments, if you are OK with the caveats of a write-only workbook you can do:

```<code>from openpyxl import Workbook

book = Workbook(write_only=True)
for country  in "IN US JP UK".split():
    book.create_sheet(title=country )
</code>```

Body:
from openpyxl import Workbook
book = Workbook()
for country in "IN US JP UK".split():
    book.create_sheet(title=country)

This creates 5 sheets with the first sheet being unwanted.

I know that I can do this:

book = Workbook()
us_ws = book.active
us_ws.title = "IN"
for country in "US JP UK".split():
    book.create_sheet(title=country)

Is there any short cut?

Body:
From the (Docs)

A workbook is always created with at least one worksheet. You can get it by using the openpyxl.workbook.Workbook.active() property

So if you do not need the default sheet, you can delete it:

from openpyxl import Workbook

book = Workbook()
book.remove(book.active)
for country in "IN US JP UK".split():
    book.create_sheet(title=country)

This deletes the first sheet, which will be the default created sheet, before creating the desired sheets.

Or, as pointed out in comments, if you are OK with the caveats of a write-only workbook you can do:

from openpyxl import Workbook

book = Workbook(write_only=True)
for country  in "IN US JP UK".split():
    book.create_sheet(title=country )


问:
SMTP connect() failed. While Sending Authentication Email
I'm Trying to send email via php by using php mailer, but it's showing SMTP connect() failed. here is my code. can't find out what is problem in that. if somebody help to track error it will be very helpful for me.

```<code>$mail = new PHPMailer;

$mail->isSMTP();                                   // Set mailer to use SMTP
$mail->Host = 'dds.uemtv.com';                    // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                            // Enable SMTP authentication
$mail->Username = 'no-reply@domain.com';          // SMTP username
$mail->Password = 'pssword'; // SMTP password
$mail->SMTPSecure = 'tls';                         // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                 // TCP port to connect to

$mail->setFrom('no-reply@domain.com', 'title');
$mail->addReplyTo($email, '$name');
$mail->addAddress($email);   // Add a recipient
//$mail->addCC('cc@example.com');
//$mail->addBCC('bcc@example.com');

$mail->isHTML(true);  // Set email format to HTML

$bodyContent = '<h1>Your Registration Completed. </h1>'
$mail->Subject = 'Verify Account- Rozgar';
$mail->Body    = $bodyContent;
if(!$mail->send()) {

    echo $data->msg = $mail->ErrorInfo;
} else {
    // echo 'Message has been sent';
    echo $data->msg="Please Verify Your Email Address";
}
</code>```

Showing this error.

2017-06-07 05:36:44 SERVER -> CLIENT: 220-dds.uemtv.com ESMTP Exim 4.89 #1 Wed, 07 Jun 2017 10:36:40 +0500 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.

  2017-06-07 05:36:44  CLIENT -> SERVER: EHLO localhost

  2017-06-07 05:36:44  SERVER -> CLIENT: 250-dds.uemtv.com Hello localhost  [182.186.132.245] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-STARTTLS 250 HELP

  2017-06-07 05:36:44  CLIENT -> SERVER: STARTTLS

  2017-06-07 05:36:45  SERVER -> CLIENT: 220 TLS go ahead

  2017-06-07 05:36:46  CLIENT -> SERVER: EHLO localhost

  2017-06-07 05:36:47  SERVER -> CLIENT: 250-dds.uemtv.com Hello localhost [182.186.132.245] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-AUTH PLAIN LOGIN 250 HELP

  2017-06-07 05:36:47  CLIENT -> SERVER: AUTH LOGIN

  2017-06-07 05:36:47  SERVER -> CLIENT: 334 VXNlcm5hbWU6

  2017-06-07 05:36:47  CLIENT -> SERVER: xxx=

  2017-06-07 05:36:47  SERVER -> CLIENT: 334 UGFzc3dvcmQ6

  2017-06-07 05:36:47  CLIENT -> SERVER: xxx

  2017-06-07 05:36:49  SERVER -> CLIENT: 535 Incorrect authentication data

  2017-06-07 05:36:49  SMTP ERROR: Password command failed: 535 Incorrect authentication data

  2017-06-07 05:36:49  SMTP Error: Could not authenticate.

  2017-06-07 05:36:49  CLIENT -> SERVER: QUIT

  2017-06-07 05:36:50  SERVER -> CLIENT: 221 dds.uemtv.com closing connection

  2017-06-07 05:36:50  SMTP connect() failed.  https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

答:
it seems not a code issue,
and as such not something we can fix for you.
Talk to your ISP, read their docs.

So either your Host setting is wrong, or you are being redirected by
  your ISP. Either way, this is all covered in the troubleshooting
  guide the error message pointed you at, which is why it's there.

Body:
I'm Trying to send email via php by using php mailer, but it's showing SMTP connect() failed. here is my code. can't find out what is problem in that. if somebody help to track error it will be very helpful for me.

$mail = new PHPMailer;

$mail->isSMTP();                                   // Set mailer to use SMTP
$mail->Host = 'dds.uemtv.com';                    // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                            // Enable SMTP authentication
$mail->Username = 'no-reply@domain.com';          // SMTP username
$mail->Password = 'pssword'; // SMTP password
$mail->SMTPSecure = 'tls';                         // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                 // TCP port to connect to

$mail->setFrom('no-reply@domain.com', 'title');
$mail->addReplyTo($email, '$name');
$mail->addAddress($email);   // Add a recipient
//$mail->addCC('cc@example.com');
//$mail->addBCC('bcc@example.com');

$mail->isHTML(true);  // Set email format to HTML

$bodyContent = '
Your Registration Completed.
'
$mail->Subject = 'Verify Account- Rozgar';
$mail->Body    = $bodyContent;
if(!$mail->send()) {

    echo $data->msg = $mail->ErrorInfo;
} else {
    // echo 'Message has been sent';
    echo $data->msg="Please Verify Your Email Address";
}

Showing this error.

2017-06-07 05:36:44 SERVER -> CLIENT: 220-dds.uemtv.com ESMTP Exim 4.89 #1 Wed, 07 Jun 2017 10:36:40 +0500 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.

  2017-06-07 05:36:44  CLIENT -> SERVER: EHLO localhost

  2017-06-07 05:36:44  SERVER -> CLIENT: 250-dds.uemtv.com Hello localhost  [182.186.132.245] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-STARTTLS 250 HELP

  2017-06-07 05:36:44  CLIENT -> SERVER: STARTTLS

  2017-06-07 05:36:45  SERVER -> CLIENT: 220 TLS go ahead

  2017-06-07 05:36:46  CLIENT -> SERVER: EHLO localhost

  2017-06-07 05:36:47  SERVER -> CLIENT: 250-dds.uemtv.com Hello localhost [182.186.132.245] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-AUTH PLAIN LOGIN 250 HELP

  2017-06-07 05:36:47  CLIENT -> SERVER: AUTH LOGIN

  2017-06-07 05:36:47  SERVER -> CLIENT: 334 VXNlcm5hbWU6

  2017-06-07 05:36:47  CLIENT -> SERVER: xxx=

  2017-06-07 05:36:47  SERVER -> CLIENT: 334 UGFzc3dvcmQ6

  2017-06-07 05:36:47  CLIENT -> SERVER: xxx

  2017-06-07 05:36:49  SERVER -> CLIENT: 535 Incorrect authentication data

  2017-06-07 05:36:49  SMTP ERROR: Password command failed: 535 Incorrect authentication data

  2017-06-07 05:36:49  SMTP Error: Could not authenticate.

  2017-06-07 05:36:49  CLIENT -> SERVER: QUIT

  2017-06-07 05:36:50  SERVER -> CLIENT: 221 dds.uemtv.com closing connection

  2017-06-07 05:36:50  SMTP connect() failed.  https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting


问:
bootstraping service in angular for globals uses
i create a service and i want to share the data inside this service so i found in some tutorial that i have to bootstrap the service in the appmodule of my application to make sure that is only one instance of this service :

```<code>@NgModule({
  declarations: [
    AppComponent,
    ProfileComponent,
    TestComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    SlimLoadingBarModule.forRoot(),
    FormWizardModule

  ],
  exports: [BrowserModule, SlimLoadingBarModule],
  providers: [UserResolverService,SessionService,  appRoutingProviders ],
  bootstrap: [AppComponent,[SessionService]]
})
export class AppModule { }
</code>```

i make the SessionService in the boostrap but i have an error in the browser console :

zone.js:522 Unhandled Promise rejection: Component SessionService is
  not part of any NgModule or the module has not been imported into your
  module. ; Zone:  ; Task: Promise.then ; Value:  ZoneAwareError
  {__zone_symbol__error: Error: Component SessionService is not part of
  any NgModule or the module has not been imported into……}  Error:
  Component SessionService is not part of any NgModule or the module has
  not been imported into your module.

this is my main.ts:

```<code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/app.module';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

答:
I think your tutorial is from a beta version.

because before the r.c version, the notation was like

```<code>bootstrap(AppComponent, [provide(SharedService, {useValue: sharedService})]);
</code>```

Now if you want to provide a service globally as a singleton, all you have to do is to provide it inside the providers array in your root module.

```<code>@NgModule({
  declarations: [
    AppComponent,
    ProfileComponent,
    TestComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    SlimLoadingBarModule.forRoot(),
    FormWizardModule

  ],
  exports: [BrowserModule, SlimLoadingBarModule],
  providers: [UserResolverService, SessionService,  appRoutingProviders ],
  bootstrap: [AppComponent] //<---- remove it from here
})
export class AppModule { }
</code>```

Body:
i create a service and i want to share the data inside this service so i found in some tutorial that i have to bootstrap the service in the appmodule of my application to make sure that is only one instance of this service :

@NgModule({
  declarations: [
    AppComponent,
    ProfileComponent,
    TestComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    SlimLoadingBarModule.forRoot(),
    FormWizardModule

  ],
  exports: [BrowserModule, SlimLoadingBarModule],
  providers: [UserResolverService,SessionService,  appRoutingProviders ],
  bootstrap: [AppComponent,[SessionService]]
})
export class AppModule { }

i make the SessionService in the boostrap but i have an error in the browser console :

zone.js:522 Unhandled Promise rejection: Component SessionService is
  not part of any NgModule or the module has not been imported into your
  module. ; Zone:  ; Task: Promise.then ; Value:  ZoneAwareError
  {__zone_symbol__error: Error: Component SessionService is not part of
  any NgModule or the module has not been imported into……}  Error:
  Component SessionService is not part of any NgModule or the module has
  not been imported into your module.

this is my main.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/app.module';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);

Body:
I think your tutorial is from a beta version.

because before the r.c version, the notation was like

bootstrap(AppComponent, [provide(SharedService, {useValue: sharedService})]);

Now if you want to provide a service globally as a singleton, all you have to do is to provide it inside the providers array in your root module.

@NgModule({
  declarations: [
    AppComponent,
    ProfileComponent,
    TestComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    SlimLoadingBarModule.forRoot(),
    FormWizardModule

  ],
  exports: [BrowserModule, SlimLoadingBarModule],
  providers: [UserResolverService, SessionService,  appRoutingProviders ],
  bootstrap: [AppComponent] //<---- remove it from here
})
export class AppModule { }


问:
Elasticsearch script_fields to update another field?
Is there a way to use the output of an ElasticSearch script_fields to update another variable in the index?

I have an index in ElasticSearch 1.x which has timestamp enabled, but not stored. (See below for mapping)

This means that the timestamp can be accessed for searches, or using script_fields like -

```<code>GET twitter/_search
{
     "script_fields": {
       "script1": {
          "script": "_fields['_timestamp']"
        }
  }
}
</code>```

I need to extract this timestamp field, and store it in the index. It is easy enough to write a script to copy any other field e.g. (I am using the update API)

```<code>ctx._source.t1=ctx._source.message
</code>```

But how can I use the value from the script_fields output to update another field in the index? I want the field 'tcopy' to get the value of the timestamp for each document.

Further, I tried to use java to get the values as below, but it returned null.

```<code>SearchResponse response = client.prepareSearch("twitter")
                .setQuery(QueryBuilders.matchAllQuery())
                .addScriptField("test", "doc['_timestamp'].value")
                .execute().actionGet();
</code>```

The mapping

```<code> {
         "mappings": {
             "tweet": {
                "_timestamp": {
                   "enabled": true,
                   "doc_values" : true
                },
                "properties": {
                   "message": {
                      "type": "string"
                   },
                   "user": {
                      "type": "string"
                   },
                   "tcopy": {
                      "type": "long"
                   }
                }
             }
          }
    }
</code>```

答:
You need to do this in two runs:

Run the query and get a mapping id<->timestamp and

Then run a bulk update with the timestamp

So to extract the timestamp data from your twitter index you can for instance use elasticdump like this:

```<code>elasticdump \
   --input=http://localhost:9200/twitter \
   --output=$ \
   --searchBody '{"script_fields": {"ts": {"script": "doc._timestamp.value"}}}' > twitter.json
</code>```

This will produce a file called twitter.json having the following content:

```<code>{"_index":"twitter","_type":"tweet","_id":"1","_score":1,"fields":{"ts":[1496806671021]}}
{"_index":"twitter","_type":"tweet","_id":"2","_score":1,"fields":{"ts":[1496807154630]}}
{"_index":"twitter","_type":"tweet","_id":"3","_score":1,"fields":{"ts":[1496807161591]}}
</code>```

You can then easily use that file to update your documents. First create a shell script named read.sh

```<code>#!/bin/sh
while read LINE; do
    INDEX=$(echo "${LINE}" | jq '._index' | sed "s/\"//g");
    TYPE=$(echo "${LINE}" | jq '._type' | sed "s/\"//g");
    ID=$(echo "${LINE}" | jq '._id' | sed "s/\"//g");
    TS=$(echo "${LINE}" | jq '.fields.ts[0]');
    curl -XPOST "http://localhost:9200/$INDEX/$TYPE/$ID/_update" -d "{\"doc\":{\"tcopy\":"$TS"}}"
done
</code>```

And finally you can run it like this:

```<code>./read.sh < twitter.json
</code>```

After the script has finished running, your documents will have a tcopy field with the _timestamp value.

Body:
Is there a way to use the output of an ElasticSearch script_fields to update another variable in the index?

I have an index in ElasticSearch 1.x which has timestamp enabled, but not stored. (See below for mapping)

This means that the timestamp can be accessed for searches, or using script_fields like -

GET twitter/_search
{
     "script_fields": {
       "script1": {
          "script": "_fields['_timestamp']"
        }
  }
}

I need to extract this timestamp field, and store it in the index. It is easy enough to write a script to copy any other field e.g. (I am using the update API)

ctx._source.t1=ctx._source.message

But how can I use the value from the script_fields output to update another field in the index? I want the field 'tcopy' to get the value of the timestamp for each document.

Further, I tried to use java to get the values as below, but it returned null.

SearchResponse response = client.prepareSearch("twitter")
                .setQuery(QueryBuilders.matchAllQuery())
                .addScriptField("test", "doc['_timestamp'].value")
                .execute().actionGet();

The mapping

 {
         "mappings": {
             "tweet": {
                "_timestamp": {
                   "enabled": true,
                   "doc_values" : true
                },
                "properties": {
                   "message": {
                      "type": "string"
                   },
                   "user": {
                      "type": "string"
                   },
                   "tcopy": {
                      "type": "long"
                   }
                }
             }
          }
    }

Body:
You need to do this in two runs:

Run the query and get a mapping id<->timestamp and

Then run a bulk update with the timestamp

So to extract the timestamp data from your twitter index you can for instance use elasticdump like this:

elasticdump \
   --input=http://localhost:9200/twitter \
   --output=$ \
   --searchBody '{"script_fields": {"ts": {"script": "doc._timestamp.value"}}}' > twitter.json

This will produce a file called twitter.json having the following content:

{"_index":"twitter","_type":"tweet","_id":"1","_score":1,"fields":{"ts":[1496806671021]}}
{"_index":"twitter","_type":"tweet","_id":"2","_score":1,"fields":{"ts":[1496807154630]}}
{"_index":"twitter","_type":"tweet","_id":"3","_score":1,"fields":{"ts":[1496807161591]}}

You can then easily use that file to update your documents. First create a shell script named read.sh

#!/bin/sh
while read LINE; do
    INDEX=$(echo "${LINE}" | jq '._index' | sed "s/\"//g");
    TYPE=$(echo "${LINE}" | jq '._type' | sed "s/\"//g");
    ID=$(echo "${LINE}" | jq '._id' | sed "s/\"//g");
    TS=$(echo "${LINE}" | jq '.fields.ts[0]');
    curl -XPOST "http://localhost:9200/$INDEX/$TYPE/$ID/_update" -d "{\"doc\":{\"tcopy\":"$TS"}}"
done

And finally you can run it like this:

./read.sh < twitter.json

After the script has finished running, your documents will have a tcopy field with the _timestamp value.