问:
Why I am getting undefined on using document.write()?
Why I am getting undefined in browser while using document.write() ?

```<code><script type="text/javascript">
    function Person (name) {
        this.name = name;
        this.greeting = function() {
            document.write("Hello " + name +  " Go rock the industry!!");
        };
    }

    var person1 = new Person("Sara");
    var person2 = new Person("Bob");

    document.write(person1.name + "<br>");
    document.write(person1.greeting() + "<br>");
    document.write(person2.name + "<br>");
    document.write(person2.greeting() + "<br>");

</script>
</code>```

In browser I get this output:

```<code>Sara
Hello Sara Go rock the industry!!undefined
Bob
Hello Bob Go rock the industry!!undefined
</code>```

答:
You need to update the greeting function to return a string instead of calling document.write() itself.

Currently, the greeting function is calling document.write() and then implicitly returning the value undefined.

When you evaluate the expression

personX.greeting() + "
"

it evaluates to

undefined + "
"

and, according to the rules of JavaScript string concatenation, undefined is first cast to the string "undefined" and then concatenated with the next value.

Edit:

If you're interested in exploring property getter functions, you could also refactor as

```<code>function Person (name) {
    this.name = name;
    Object.defineProperty(this, 'greeting', {
        get: function() {
            return "Hello " + this.name +  " Go rock the industry!!";
        }
    });
}

var person1 = new Person("Sara");
var person2 = new Person("Bob");

document.write(person1.name + "<br>");
document.write(person1.greeting + "<br>");
document.write(person2.name + "<br>");
document.write(person2.greeting + "<br>");
</code>```

Notice how we can then access the computed value personX.greeting as if it were just a string property.

Depending on your environment, etc., if you can use ES2015+ syntax, you could achieve the same result with

```<code>class Person {

  constructor(name) {
    this.name = name;
  }

  get greeting() {
    return `Hello ${this.name} Go rock the industry!!`
  }
}

let person1 = new Person('Sara');
let person2 = new Person('Bob');

document.write(person1.name + "<br>");
document.write(person1.greeting + "<br>");
document.write(person2.name + "<br>");
document.write(person2.greeting + "<br>");
</code>```

Body:
Why I am getting undefined in browser while using document.write() ?

In browser I get this output:

Sara
Hello Sara Go rock the industry!!undefined
Bob
Hello Bob Go rock the industry!!undefined

Body:
You need to update the greeting function to return a string instead of calling document.write() itself.

Currently, the greeting function is calling document.write() and then implicitly returning the value undefined.

When you evaluate the expression

personX.greeting() + "<br/>"

it evaluates to

undefined + "<br/>"

and, according to the rules of JavaScript string concatenation, undefined is first cast to the string "undefined" and then concatenated with the next value.

Edit:

If you're interested in exploring property getter functions, you could also refactor as

function Person (name) {
    this.name = name;
    Object.defineProperty(this, 'greeting', {
        get: function() {
            return "Hello " + this.name +  " Go rock the industry!!";
        }
    });
}

var person1 = new Person("Sara");
var person2 = new Person("Bob");

document.write(person1.name + "<br>");
document.write(person1.greeting + "<br>");
document.write(person2.name + "<br>");
document.write(person2.greeting + "<br>");

Notice how we can then access the computed value personX.greeting as if it were just a string property.

Depending on your environment, etc., if you can use ES2015+ syntax, you could achieve the same result with

class Person {

  constructor(name) {
    this.name = name;
  }

  get greeting() {
    return `Hello ${this.name} Go rock the industry!!`
  }
}

let person1 = new Person('Sara');
let person2 = new Person('Bob');

document.write(person1.name + "<br>");
document.write(person1.greeting + "<br>");
document.write(person2.name + "<br>");
document.write(person2.greeting + "<br>");


来源: stackexchange

问:
method in class can not be applied to given type
I made a class called that creates a constructer and a method.

```<code>public class Car
{
private double speed;
private String make;
private int year;

public Car(int year, String make, double speed) {
this.year = year;
this.make = make;
this.speed = speed;
}

public String getMake(){
  return make;
}
public double getSpeed(){
  return speed;
}
public int getYear(){
     return year;
}

  public void accelerate (double speed)
{
        speed = speed + 1.00;
}

}
</code>```

the only problem i am having here is that when I go to my driver class to try and run it, this is the error I'm receiving

```<code>public class CarTester
{
public static void main (String[] args){

Car p1 = new Car(2010, "toyota", 4.50);
Car.accelerate();
Car.accelerate();

}
}
</code>```

"error: method accelerate in class Car cannot be applied to given types"

why is that so? because it says "required: double" but the "speed" variable is a double?

答:
You create a Car object :

```<code>Car p1 = new Car(2010, "toyota", 4.50);
</code>```

1) But you call accelerate in a static way while   accelerate (double speed) is an instance method :

```<code>Car.accelerate();
Car.accelerate();
</code>```

2) accelerate() specifies a parameter but you don't provide it in the method.

You should rather write :

```<code>car.accelerate(5);
car.accelerate(5);
</code>```

3) This :

```<code>  public void accelerate (double speed){
        speed = speed + 1.00;
  }
</code>```

will not work as the local variable has the same name as the field name.

A local variable with the same name than a field name shadows the field variable.

To avoid it you should rename the parameter name or better prefixing the field name with this when you use it in the method  :

```<code>  public void accelerate (double speed){
        this.speed = this.speed + speed;
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I made a class called that creates a constructer and a method.

public class Car
{
private double speed;
private String make;
private int year;

public Car(int year, String make, double speed) {
this.year = year;
this.make = make;
this.speed = speed;
}

public String getMake(){
  return make;
}
public double getSpeed(){
  return speed;
}
public int getYear(){
     return year;
}

  public void accelerate (double speed)
{
        speed = speed + 1.00;
}

}

the only problem i am having here is that when I go to my driver class to try and run it, this is the error I'm receiving

public class CarTester
{
public static void main (String[] args){

Car p1 = new Car(2010, "toyota", 4.50);
Car.accelerate();
Car.accelerate();

}
}

"error: method accelerate in class Car cannot be applied to given types"

why is that so? because it says "required: double" but the "speed" variable is a double?

Body:
You create a Car object :

Car p1 = new Car(2010, "toyota", 4.50);

1) But you call accelerate in a static way while   accelerate (double speed) is an instance method :

Car.accelerate();
Car.accelerate();

2) accelerate() specifies a parameter but you don't provide it in the method.

You should rather write :

car.accelerate(5);
car.accelerate(5);

3) This :

  public void accelerate (double speed){
        speed = speed + 1.00;
  }

will not work as the local variable has the same name as the field name.

A local variable with the same name than a field name shadows the field variable.

To avoid it you should rename the parameter name or better prefixing the field name with this when you use it in the method  :

  public void accelerate (double speed){
        this.speed = this.speed + speed;
  }


问:
How to set the size of a newly created TextField without a reference for it
My code for creating a Textfield using new TextFieldwas used as a parameter for a method like this

```<code>x.getChildren.addAll(new TextField());
</code>```

My program has a button that creates TextField.

It's a loop to create a number TextFields until the condition is satisfied.

   My own code looks like this:

```<code>sub.setOnAction(e-> {
    v.getChildren().clear(); //just clearing things
    v1.getChildren().clear(); //just clearing things

    makeStr(Integer.valueOf(numOpt.getText()));
    for(int i = 0; i < list.size(); i++){
        v.getChildren().addAll(new Label(list.get(i).toString()));
        v1.getChildren().addAll(new TextField());
    }
    list.clear();
});
</code>```

However I cant just change its size like this.

```<code>v1.getChildren().addAll(new TextField().setPrefWidth(800));
</code>```

Maybe a better code can fix the problem!

答:
Create reference to every TextField you instantiate, set size and then add it to view. Do not use ObservableList#addAll method because you are adding only one component. Invoke standard ObservableList#add method.

```<code>for (int i = 0; i < list.size(); i++) {
    v.getChildren().add(new Label(list.get(i).toString()));
    TextField tf = new TextField();
    tf.setPrefWidth(800);
    v1.getChildren().add(tf);
}
</code>```

Body:
My code for creating a Textfield using new TextFieldwas used as a parameter for a method like this

x.getChildren.addAll(new TextField());

My program has a button that creates TextField.

It's a loop to create a number TextFields until the condition is satisfied.

   My own code looks like this:

sub.setOnAction(e-> {
    v.getChildren().clear(); //just clearing things
    v1.getChildren().clear(); //just clearing things

    makeStr(Integer.valueOf(numOpt.getText()));
    for(int i = 0; i < list.size(); i++){
        v.getChildren().addAll(new Label(list.get(i).toString()));
        v1.getChildren().addAll(new TextField());
    }
    list.clear();
});

However I cant just change its size like this.

v1.getChildren().addAll(new TextField().setPrefWidth(800));

Maybe a better code can fix the problem!

Body:
Create reference to every TextField you instantiate, set size and then add it to view. Do not use ObservableList#addAll method because you are adding only one component. Invoke standard ObservableList#add method.

for (int i = 0; i < list.size(); i++) {
    v.getChildren().add(new Label(list.get(i).toString()));
    TextField tf = new TextField();
    tf.setPrefWidth(800);
    v1.getChildren().add(tf);
}


问:
How to Daemonize a Java Program?
I have a Java program that I'd like to daemonize on a linux system. In other words, I want to start running it in a shell and have it continue running after I've logged out. I also want to be able to stop the program cleanly.

I found this article which uses a combination of shell scripting and Java code to do the trick. It looks good, but I'd like something simpler, if possible.

What's your preferred method to daemonize a Java program on a Linux system?

答:
Take a look here:

http://jnicookbook.owsiak.org/recipe-no-022/

for a sample code that is based on JNI. In this case you daemonize the code that was started as Java and main loop is executed in C. But it is also possible to put main, daemon's, service loop inside Java.

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo029

Have fun with JNI!

OwnerDisplayName: Rich Apodaca

ContentLicense: CC BY-SA 2.5

Title: How to Daemonize a Java Program?

ContentLicense: CC BY-SA 4.0


问:
Changing classes in javascript on click
I have this side bar with a bunch of  linked to the same page

I have this JS code, but the previous  link does not change back to tab-title and remains active

I would want it so that when the user clicks a link, the  would change from class="tab-title" to class="tab-title-active"

$(document).ready(function() {
  $('a').click(function() {
    $(this).removeClass('tab-title');
    $(this).addClass('tab-title-active');
    $(this).siblings().removeClass('tab-title-active');
    $(this).siblings().addClass('tab-title');
    console.log($(this).attr("class"));
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a.tab-title{
    font-size: 18px;
    font-weight: 400;
    list-style: none;
    color: #444;
    margin-top: 10px;
}

a.tab-title-active{
    font-size: 18px;
    font-weight: bold;
    list-style: none;
    color: #0091e4;
    margin-top: 10px;
}</code>```

href="#tab-title-0" class="tab-title-active">Binary

href="#tab-title-1" class="tab-title">About

href="#tab-title-2" class="tab-title">Representation

Binary

About

Representation

```

答:
```<code>$(document).ready(function() {
  $('a').click(function() {
    $('a').removeClass('tab-title-active');//this would remove active class from previous hyperlinks and the remaining code will apply the same
    $(this).removeClass('tab-title');
    $(this).addClass('tab-title-active');
    $(this).siblings().removeClass('tab-title-active');
    $(this).siblings().addClass('tab-title');
    console.log($(this));
  });
});
</code>```

Title: Changing classes in javascript on click

Body:
I have this side bar with a bunch of  linked to the same page

I have this JS code, but the previous  link does not change back to tab-title and remains active

I would want it so that when the user clicks a link, the  would change from class="tab-title" to class="tab-title-active"

$(document).ready(function() {
  $('a').click(function() {
    $(this).removeClass('tab-title');
    $(this).addClass('tab-title-active');
    $(this).siblings().removeClass('tab-title-active');
    $(this).siblings().addClass('tab-title');
    console.log($(this).attr("class"));
  });
});

a.tab-title{
    font-size: 18px;
    font-weight: 400;
    list-style: none;
    color: #444;
    margin-top: 10px;
}

a.tab-title-active{
    font-size: 18px;
    font-weight: bold;
    list-style: none;
    color: #0091e4;
    margin-top: 10px;
}

Binary

About

Representation

Binary

About

Representation


问:
Button doesn't work above UICollectionView in Swift
I'm trying to show a menu when I click on the Navigation Bar (Like Instagram when to use several accounts). So, this is what I have:

And with the menu:

The list into the menu is buttons which are added in code. My problem is that only the first button is working. After several tests, it's working because this button is above the searchbar. But if a button is above the UICollectionView, it's not working any more.

I tried to play with the position of the layer :

```<code>currentView.layer.zPosition = 2
</code>```

But it's not working. Do you have any idea about what I could do to enable button above the UICollection View ?

This is the code to launch the CollectionView:

```<code>   func collectionViewLaunch() {

      // Layout of collectionView
      let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()

      layout.itemSize = CGSize(width: self.view.frame.size.width * 0.47, height: self.view.frame.size.width * 0.47)

      layout.scrollDirection = UICollectionViewScrollDirection.vertical

      let frame = CGRect(x: 0, y: 44, width: self.view.frame.size.width, height: self.view.frame.size.height - self.tabBarController!.tabBar.frame.size.height - self.navigationController!.navigationBar.frame.size.height - 62 )

      layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)

      collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
      collectionView.delegate = self
      collectionView.dataSource = self
      collectionView.alwaysBounceVertical = true
      collectionView.backgroundColor = UIColor.white
      self.view.addSubview(collectionView)

      // Define cell for collectionView
      collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")

      // Call function to load posts
      loadPosts()

   }
</code>```

Edit

Creation of buttons (the view is the menu view) :

```<code>   func menuTapped(_ list: Array<String>, view: UIView, xCoord: CGFloat, yCoord: CGFloat, buttonWidth: CGFloat, buttonHeight: CGFloat){

      var yCoord = yCoord
      var itemCount = 0

      for i in 0 ..< list.count {
         itemCount = i

         let listButton = UIButton(type: .custom)
         listButton.frame = CGRect(x: xCoord, y: (yCoord), width: buttonWidth, height: 45)
         // istButton.tag = itemCount
         listButton.addTarget(self, action: #selector(self.menuButtonTapped(_:)), for: .touchUpInside)
         listButton.setTitle("\(list[i])", for: .normal)
         listButton.setTitleColor(UIColor(red: 109 / 255, green: 109 / 255, blue: 109 / 255, alpha: 1), for: .normal)
         listButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightThin)
         listButton.tag = itemCount

         // Add Buttons in the Scroll View
         yCoord +=  buttonHeight
         view.addSubview(listButton)
      }
   }

   func menuButtonTapped(_ sender: Any){
      let button = sender as! UIButton
      // let tmpButton = self.view.viewWithTag(button.tag) as? UIButton

      print(button.tag)
   }
</code>```

In the view did load:

```<code>sportMenuView = UIView(frame: CGRect(x: 0, y: CGFloat(-menuSport.count * 45), width: self.view.frame.size.width, height: CGFloat(menuSport.count * 45)))
      sportMenuView.backgroundColor = UIColor.white
      self.view.addSubview(sportMenuView)
      sportMenuView.layer.zPosition = 2

menuTapped(menuSport, view: sportMenuView, xCoord: xCoord, yCoord: yCoord, buttonWidth: buttonWidth, buttonHeight: buttonHeight)
</code>```

答:
It was pretty simple ...

I just moved the collectionViewLaunch() function before to add the menu's subview.

Indeed, in that case, the menu's view is above the collectionView.

Body:
I'm trying to show a menu when I click on the Navigation Bar (Like Instagram when to use several accounts). So, this is what I have:

And with the menu:

The list into the menu is buttons which are added in code. My problem is that only the first button is working. After several tests, it's working because this button is above the searchbar. But if a button is above the UICollectionView, it's not working any more.

I tried to play with the position of the layer :

currentView.layer.zPosition = 2

But it's not working. Do you have any idea about what I could do to enable button above the UICollection View ?

This is the code to launch the CollectionView:

   func collectionViewLaunch() {

      // Layout of collectionView
      let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()

      layout.itemSize = CGSize(width: self.view.frame.size.width * 0.47, height: self.view.frame.size.width * 0.47)

      layout.scrollDirection = UICollectionViewScrollDirection.vertical

      let frame = CGRect(x: 0, y: 44, width: self.view.frame.size.width, height: self.view.frame.size.height - self.tabBarController!.tabBar.frame.size.height - self.navigationController!.navigationBar.frame.size.height - 62 )

      layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)

      collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
      collectionView.delegate = self
      collectionView.dataSource = self
      collectionView.alwaysBounceVertical = true
      collectionView.backgroundColor = UIColor.white
      self.view.addSubview(collectionView)

      // Define cell for collectionView
      collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")

      // Call function to load posts
      loadPosts()

   }

Edit

Creation of buttons (the view is the menu view) :

   func menuTapped(_ list: Array<String>, view: UIView, xCoord: CGFloat, yCoord: CGFloat, buttonWidth: CGFloat, buttonHeight: CGFloat){

      var yCoord = yCoord
      var itemCount = 0

      for i in 0 ..< list.count {
         itemCount = i

         let listButton = UIButton(type: .custom)
         listButton.frame = CGRect(x: xCoord, y: (yCoord), width: buttonWidth, height: 45)
         // istButton.tag = itemCount
         listButton.addTarget(self, action: #selector(self.menuButtonTapped(_:)), for: .touchUpInside)
         listButton.setTitle("\(list[i])", for: .normal)
         listButton.setTitleColor(UIColor(red: 109 / 255, green: 109 / 255, blue: 109 / 255, alpha: 1), for: .normal)
         listButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightThin)
         listButton.tag = itemCount

         // Add Buttons in the Scroll View
         yCoord +=  buttonHeight
         view.addSubview(listButton)
      }
   }

   func menuButtonTapped(_ sender: Any){
      let button = sender as! UIButton
      // let tmpButton = self.view.viewWithTag(button.tag) as? UIButton

      print(button.tag)
   }

In the view did load:

sportMenuView = UIView(frame: CGRect(x: 0, y: CGFloat(-menuSport.count * 45), width: self.view.frame.size.width, height: CGFloat(menuSport.count * 45)))
      sportMenuView.backgroundColor = UIColor.white
      self.view.addSubview(sportMenuView)
      sportMenuView.layer.zPosition = 2

menuTapped(menuSport, view: sportMenuView, xCoord: xCoord, yCoord: yCoord, buttonWidth: buttonWidth, buttonHeight: buttonHeight)


答:
accelerate is not a static method, so Car.accelerate () can not be called

You have to call it on the Object the you have created i.e. p1.

Also - this method expects to be passed the speed parameter, but this looks wrong.

I would rewrite it as

```<code>public void accelerate ()
{
    speed = speed + 1.00;
}
</code>```

as speed is already a field

Alternatively you could leave it as

```<code>public void accelerate (double speedUpBy)
{
    speed = speed + speedUpBy;
}
</code>```

so that you can specifiy by how much you want to accelerate by

Title: method in class can not be applied to given type

Body:
accelerate is not a static method, so Car.accelerate () can not be called

You have to call it on the Object the you have created i.e. p1.

Also - this method expects to be passed the speed parameter, but this looks wrong.

I would rewrite it as

public void accelerate ()
{
    speed = speed + 1.00;
}

as speed is already a field

Alternatively you could leave it as

public void accelerate (double speedUpBy)
{
    speed = speed + speedUpBy;
}

so that you can specifiy by how much you want to accelerate by


问:
Reusing the same viewController on top of the navigationStack in swift
For my app project i have created a tableView that show a wine including, rating reviews, tasting notes and all sorts of data in each section. In the last section the user is shown two similar wines, once pushed it is the purpose to reUse the current viewController, and throw it onto the navigation stack as the user might browse another wine inside that viewController and so forth.

How would you go about, reUsing the same viewController. Since building infinite numbers of the same viewController in storyboards seems abit rookie to me. Thanks all help appreciated.

答:
You can use Storyboards and reuse the ViewController with no problem.
In the Storyboard use the Storyboard ID in the identity inspector, Add a unique ID to the ViewController.

After that it's pretty simple, you can ether:

Instantiate the first level viewController with the segue, than once you want to add another ViewController (of the same type) with the UIStoryboard instantiateviewcontrollerwithidentifier: and give the unique id of the ViewController, and present it

or

You can just use the UIStoryboard instantiateviewcontrollerwithidentifier: every time you want to present the ViewController


问:
Create a table as, where 'date condition' in dynamic PL/SQL
I got assigned the following task.

Assume we have a table A structured with an id column and a date column.
Write a procedure in PL/SQL that: takes as parameters the table name (in our case A) and a date D, creates a backup table named A_bck containing only the records of A with dates < D and removes from the table A all the records inserted in A_bck.

Here there is my code.

Unluckily I get this error:

```<code>Error report -
ORA-00904: "MAY": invalid identifier
ORA-06512: at line 41
ORA-06512: at line 80
00904. 00000 -  "%s: invalid identifier"
</code>```

If I try to achieve the same result using a where condition on the id column instead that on the date one, I have no problems.
Where is the mistake? Am I implementing it completely in the wrong way?

答:
The problem you have is that as you're executing dynamic sql you're query is built up as a string. Oracle does not know that the date you've given is actually a date, it is simply being treated as part of the string. To solve this you should be able to do the following:

my_query := 'CREATE TABLE ' || table_name_backup || ' AS (SELECT * FROM ' || table_name || ' WHERE table_date < to_date(''' || backup_date || '''))';

This should sort out your issue for you. As a side note, you will probably want to change your "table_exists" query, as table names are all stored in upper case, e.g.

SELECT COUNT(*) INTO table_exists FROM USER_TABLES WHERE TABLE_NAME = upper(my_table);

Edit: Further explanation following comment

To explain why you don't have the above problem when using integers, it is important to remember that using execute immediate simply executes the given string as an SQL query.

For example:

```<code>declare
  x INTEGER := 1;
  i integer;
  my_query VARCHAR2(256);
begin
  my_query := 'select 1 from dual where 1 = ' || x;
  EXECUTE IMMEDIATE my_query INTO i;
end;
</code>```

my_query in the above example would be executed as:

select 1 from dual where 1 = 1

which is perfectly valid sql. In your example however, you were ending up with something like this:

CREATE TABLE abaco_bck AS (SELECT * FROM abaco WHERE table_date < 27-MAY-17)

As it isn't wrapped in quotes, or explicitly converted to a date, the SQL engine is trying to subtract "MAY" from 27, but it doesn't know what "MAY" is.

One other thing to mention, is that for some operations you could use bind variables instead of quotes (although you can't for DDL) e.g.

```<code>declare
  lToday    DATE := SYSDATE;
  i         INTEGER;
  my_query  VARCHAR2(256);
begin
  my_query := 'select 1 from dual where sysdate = :1';
  EXECUTE IMMEDIATE my_query INTO i USING lToday;
end;
</code>```

Body:
I got assigned the following task.

Assume we have a table A structured with an id column and a date column.
Write a procedure in PL/SQL that: takes as parameters the table name (in our case A) and a date D, creates a backup table named A_bck containing only the records of A with dates < D and removes from the table A all the records inserted in A_bck.

Here there is my code.

Unluckily I get this error:

Error report -
ORA-00904: "MAY": invalid identifier
ORA-06512: at line 41
ORA-06512: at line 80
00904. 00000 -  "%s: invalid identifier"

If I try to achieve the same result using a where condition on the id column instead that on the date one, I have no problems.
Where is the mistake? Am I implementing it completely in the wrong way?

Body:
The problem you have is that as you're executing dynamic sql you're query is built up as a string. Oracle does not know that the date you've given is actually a date, it is simply being treated as part of the string. To solve this you should be able to do the following:

my_query := 'CREATE TABLE ' || table_name_backup || ' AS (SELECT * FROM ' || table_name || ' WHERE table_date < to_date(''' || backup_date || '''))';

This should sort out your issue for you. As a side note, you will probably want to change your "table_exists" query, as table names are all stored in upper case, e.g.

SELECT COUNT(*) INTO table_exists FROM USER_TABLES WHERE TABLE_NAME = upper(my_table);

Edit: Further explanation following comment

To explain why you don't have the above problem when using integers, it is important to remember that using execute immediate simply executes the given string as an SQL query.

For example:

declare
  x INTEGER := 1;
  i integer;
  my_query VARCHAR2(256);
begin
  my_query := 'select 1 from dual where 1 = ' || x;
  EXECUTE IMMEDIATE my_query INTO i;
end;

my_query in the above example would be executed as:

select 1 from dual where 1 = 1

which is perfectly valid sql. In your example however, you were ending up with something like this:

CREATE TABLE abaco_bck AS (SELECT * FROM abaco WHERE table_date < 27-MAY-17)

As it isn't wrapped in quotes, or explicitly converted to a date, the SQL engine is trying to subtract "MAY" from 27, but it doesn't know what "MAY" is.

One other thing to mention, is that for some operations you could use bind variables instead of quotes (although you can't for DDL) e.g.

declare
  lToday    DATE := SYSDATE;
  i         INTEGER;
  my_query  VARCHAR2(256);
begin
  my_query := 'select 1 from dual where sysdate = :1';
  EXECUTE IMMEDIATE my_query INTO i USING lToday;
end;


问:
Sharepoint XSL - break string into componant parts
I'm using a "choice" site column with the multiple-check option enabled so that users can tag a list item with several choices from the column.

This column then powers a design feature in a content query webpart - where the column choice is appended to create an image filename.

Choice1

Choice2

Choice3

Choice4

becomes

```<code><img src="http://mysite/content-Choice1.jpg />
</code>```

The problem I've got is that the XSL parser is fed a string which has semicolons (;) and hashes (#) separating the choice values. If all 4 options were ticked, the string fed into the XSLT parser would be:

```<code>;#Choice1;#Choice2;#Choice3;#Choice4
</code>```

How can I work through the string and separate each choice into its own XSL variable?

I've tried various substring-before functions, but I can't get anything working.

答: I would recommend to use JavaScript to parse the string and accordingly display the image using JavaScript.</p>

Body:
I'm using a "choice" site column with the multiple-check option enabled so that users can tag a list item with several choices from the column.

This column then powers a design feature in a content query webpart - where the column choice is appended to create an image filename.

Choice1

Choice2

Choice3

Choice4

becomes

The problem I've got is that the XSL parser is fed a string which has semicolons (;) and hashes (#) separating the choice values. If all 4 options were ticked, the string fed into the XSLT parser would be:

;#Choice1;#Choice2;#Choice3;#Choice4

How can I work through the string and separate each choice into its own XSL variable?

I've tried various substring-before functions, but I can't get anything working.


问:
how to list the nodes in docker swarm via api call?
I am trying to get the node details of the swarm manager via api call.

```<code>my question is, is there an api call equivalent to

docker node ls
</code>```

I tried to get the api details, i searched enough and i cant get it ?

答:
Did you check the /info call? I believe you do not need to look any further. And here is a detailed discussion around this particular issue. You will get enough pointer from there I believe.

I am not sure that a fully supported API end point has been added yet. However, as that link suggests you can parse the return of the /info call and get a lot of info that you may need.

Does this help?

Body:
I am trying to get the node details of the swarm manager via api call.

my question is, is there an api call equivalent to

docker node ls

I tried to get the api details, i searched enough and i cant get it ?


问:
Run a Java Application as a Service on Linux
I have written a Java server application that runs on a standard virtual hosted Linux solution.  The application runs all the time listening for socket connections and creating new handlers for them.  It is a server side implementation to a client-server application.

The way I start it is by including it in the start up rc.local script of the server.  However once started I do not know how to access it to stop it and if I want to install an update, so I have to restart the server in order to restart the application.

On a windows PC, for this type of application I might create a windows service and then I can stop and start it as I want.  Is there anything like that on a Linux box so that if I start this application I can stop it and restart it without doing a complete restart of the server.

My application is called WebServer.exe.  It is started on server startup by including it in my rc.local as such:

```<code>java -jar /var/www/vhosts/myweb.com/phpserv/WebServer.jar &
</code>```

I am a bit of a noob at Linux so any example would be appreciated with any posts.   However I do have SSH, and full FTP access to the box to install any updates as well as access to a Plesk panel.

答:
To run Java code as daemon (service) you can write JNI based stub.

http://jnicookbook.owsiak.org/recipe-no-022/

for a sample code that is based on JNI. In this case you daemonize the code that was started as Java and main loop is executed in C. But it is also possible to put main, daemon's, service loop inside Java.

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo029

Have fun with JNI!

Body:
I have written a Java server application that runs on a standard virtual hosted Linux solution.  The application runs all the time listening for socket connections and creating new handlers for them.  It is a server side implementation to a client-server application.

The way I start it is by including it in the start up rc.local script of the server.  However once started I do not know how to access it to stop it and if I want to install an update, so I have to restart the server in order to restart the application.

On a windows PC, for this type of application I might create a windows service and then I can stop and start it as I want.  Is there anything like that on a Linux box so that if I start this application I can stop it and restart it without doing a complete restart of the server.

My application is called WebServer.exe.  It is started on server startup by including it in my rc.local as such:

java -jar /var/www/vhosts/myweb.com/phpserv/WebServer.jar &

I am a bit of a noob at Linux so any example would be appreciated with any posts.   However I do have SSH, and full FTP access to the box to install any updates as well as access to a Plesk panel.


问:
Aspectj Pointcut expression not working for one method and working for another method in single class
I have written below code in controller.

For this controllerMethod method the aspectj Pointcut expression is working fine but for executeService method Aspect is not working.

```<code>@RequestMapping(value = "URL", method = RequestMethod.POST)
public ModelAndView controllerMethod(@ModelAttribute ModelAttribute reqModel, HttpServletRequest req, HttpServletResponse res) {

    try {
        response = executeService(param1, param2);

    } catch (Exception e) {

    }

    }
private ResponseObject executeService(String param1, String param2){
    //Code....
}
</code>```

I have written the aspect as below.

```<code>@Before("execution(* com.*.*.Controller.executeService(..))")
public void logBefore(JoinPoint joinPoint) {
    logger.info("Before aspect: " + joinPoint.getSignature().getName());
}
</code>```

Can you please let me know where is the issues. I need to execute aspect before calling executeService method.

答:
Although our colleagues have provided correct answers, I'll summarize.

When it comes to aspects implementation, spring generates a proxy that wraps your controller. The proxy is implemented in a way that it has special hooks to invoke aspects before and after the class (or around, altering the flow altogether).

Spring uses two different strategies for proxy generation:

java.lang.Proxy based

CGLIB based

The first one is in general better, faster but works only with interfaces. The generated proxy is "something" that implements all the methods of the interface. The implementation methods contain those hooks I've talked before, but since the methods are only methods in the interface they have to be public

CGLIB - is slower, but it can work with classes as well (with some restrictions though). The way it works is sub-classing the parent class and overriding the methods provided by the super class. This new method (let's call it foo) will call all the hooks and somewhere in code if needed will call super.foo().

Now, obviously this can't really work with private methods because its impossible to override private methods.
That's why my colleagues have pointed that private won't work here.

Now regarding the self injection stuff:

When you're inside the method of original controller and you're trying to call just another method (even if its public), you're not working with proxy any more, you're kind of behind the proxy and work with original class. So this means that you won't be able to take advantage of "enhanced" method.

That's why there is a self injection - you can see (with debugger for example) that the self-injected dependency is actually a dependency with all the proxies, that's why it starts to work.

Another workaround is to refactor the method to another Spring bean, inject this bean to your controller, and provide a definition for that bean.

Body:
I have written below code in controller.

For this controllerMethod method the aspectj Pointcut expression is working fine but for executeService method Aspect is not working.

@RequestMapping(value = "URL", method = RequestMethod.POST)
public ModelAndView controllerMethod(@ModelAttribute ModelAttribute reqModel, HttpServletRequest req, HttpServletResponse res) {

    try {
        response = executeService(param1, param2);

    } catch (Exception e) {

    }

    }
private ResponseObject executeService(String param1, String param2){
    //Code....
}

I have written the aspect as below.

@Before("execution(* com.*.*.Controller.executeService(..))")
public void logBefore(JoinPoint joinPoint) {
    logger.info("Before aspect: " + joinPoint.getSignature().getName());
}

Can you please let me know where is the issues. I need to execute aspect before calling executeService method.


问:
Autocomplete extender for multiple textbox using Javascript
I want to apply one autocomplete extender for multiple textbox having same name attribute, For eg.

I just want to apply same autocomplete extender to all having name="txtQtyPkgs". How I can do this?
My html

```<code><table cellspacing="0" cellpadding="0" border="0" style="" id="flex1">
        <tbody>
            <tr id="rowGH03013">
                <td align="Left" class="sorted">
                    <div style="text-align: left; width: 150px;">
                        GH03013</div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 150px;">
                        999</div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 161px;">
                        <input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
                            id="QtyPkgs19523"></div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 446px;">
                        <input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
                            id="Buyer19523"></div>
                </td>
            </tr>
            <tr class="erow" id="rowGH03011">
                <td align="Left" class="sorted">
                    <div style="text-align: left; width: 150px;">
                        GH03011</div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 150px;">
                        999</div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 161px;">
                        <input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
                            id="QtyPkgs19521"></div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 446px;">
                        <input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
                            id="Buyer19521"></div>
                </td>
            </tr>
        </tbody>
    </table>
</code>```

my xml data

```<code><table>
  <userid>23</userid>
  <userdispname>GUJARAT PACKERS LTD</userdispname>
  <usercode>GTPL</usercode>
</table>

<table>
  <userid>26</userid>
  <userdispname>Lipton India Limited</userdispname>
  <usercode>Lipton</usercode>
</table>
<table>
  <userid>27</userid>
  <userdispname>TOSH LTD.</userdispname>
  <usercode>ATosh</usercode>
</table>
<table>
  <userid>28</userid>
  <userdispname>SERVICES INDIA PVT. LTD.</userdispname>
  <usercode>TSI</usercode>
</table>
<table>
  <userid>29</userid>
  <userdispname>Parekh Company</userdispname>
  <usercode>Parekh</usercode>
</table>
<table>
  <userid>30</userid>
  <userdispname>SHREE BALAJI CO.</userdispname>
  <usercode>Balaji</usercode>
</table>
<table>
  <userid>31</userid>
  <userdispname>Kesaria Company</userdispname>
  <usercode>Kesaria</usercode>
</table>
</code>```

my javascript

```<code>$(document).ready(function () {
            AuctoCmplBuyer();
            $(".auto").autocomplete({ source: [AuctoCmpData] });
        });
 function AuctoCmplBuyer() {
            $.ajax({
                type: "POST",
                url: "../service/WebService.asmx/XmlData",
                data: "{strData:'BuyerList'}",
                contentType: "application/json; charset=UTF-8",
                dataType: "xml",
                success: function (msg) {
                    $(msg).find('Table').each(function () {
                        if (StrData.length != 0) {
                            StrData = StrData + ",";
                        }
                        StrData = '{"id":"' + $(this).find('UserID').text() + '","label":"' + $(this).find('UserDispName').text() + '","value":"' + $(this).find('UserDispName').text() + '"}';
                    });
                }
            });
            AuctoCmpData = StrData;
        }
</code>```

答:
Please put a common class name for all your textbox and using jQuery autocomplete you can do it.

```<code> $(".auto").autocomplete({
        source: "../Ajax/AjaxGetData.ashx,
        minLength: 2,
        select: function(event, ui) {
            $(this).val(ui.item.value);
        }
    });
</code>```

Please refer for more.
http://jqueryui.com/demos/autocomplete/#remote

What I am doing is to make a class called auto and assign it to all of the text box. so when ever the user enters the value it will be going to the handler page (asp.net) or u can use a .php page. In that handler page I am selecting data from database using the like operator of Sql.After selecting the values just Response.Write() (in asp.net) or echo(in php please refer) to send the data.The data is send in the JSON format

```<code>[ { "id":"XYZ" , "label":"XYZ" , "value": "XYZ"}]
</code>```

The above is the format of JSON

For all auto suggest you might have a lot of data.To do so you have to get the total number of results returned after the execution of the query and make a loop.Initialize a string variable with the default value as "[" to the start and append the string with {"id":"Data","label:Data","value":"data"}(this constitutes a JSON object).If it is having more than you just add a , and do looping at the end add "]" to string.

So ur array will be in the format of

```<code>  [ { "id":"XYZ1" , "label":"XYZ1" , "value": "XYZ1"}, { "id":"XYZ2" , "label":"XYZ2" , "value": "XYZ2"}]
</code>```

The [' denotes the starting of array and ']' denotes the end
The{` denotes the starting of object and '}' denotes the end

Pls refer  JSON  to know more

Body:
I want to apply one autocomplete extender for multiple textbox having same name attribute, For eg.

I just want to apply same autocomplete extender to all having name="txtQtyPkgs". How I can do this?
My html

                        GH03013

                        999

                        <input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
                            id="QtyPkgs19523">

                        <input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
                            id="Buyer19523">

                        GH03011

                        999

                        <input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
                            id="QtyPkgs19521">

                        <input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
                            id="Buyer19521">

my xml data

  <userid>23</userid>
  <userdispname>GUJARAT PACKERS LTD</userdispname>
  <usercode>GTPL</usercode>

  <userid>26</userid>
  <userdispname>Lipton India Limited</userdispname>
  <usercode>Lipton</usercode>

  <userid>27</userid>
  <userdispname>TOSH LTD.</userdispname>
  <usercode>ATosh</usercode>

  <userid>28</userid>
  <userdispname>SERVICES INDIA PVT. LTD.</userdispname>
  <usercode>TSI</usercode>

  <userid>29</userid>
  <userdispname>Parekh Company</userdispname>
  <usercode>Parekh</usercode>

  <userid>30</userid>
  <userdispname>SHREE BALAJI CO.</userdispname>
  <usercode>Balaji</usercode>

  <userid>31</userid>
  <userdispname>Kesaria Company</userdispname>
  <usercode>Kesaria</usercode>

my javascript

$(document).ready(function () {
            AuctoCmplBuyer();
            $(".auto").autocomplete({ source: [AuctoCmpData] });
        });
 function AuctoCmplBuyer() {
            $.ajax({
                type: "POST",
                url: "../service/WebService.asmx/XmlData",
                data: "{strData:'BuyerList'}",
                contentType: "application/json; charset=UTF-8",
                dataType: "xml",
                success: function (msg) {
                    $(msg).find('Table').each(function () {
                        if (StrData.length != 0) {
                            StrData = StrData + ",";
                        }
                        StrData = '{"id":"' + $(this).find('UserID').text() + '","label":"' + $(this).find('UserDispName').text() + '","value":"' + $(this).find('UserDispName').text() + '"}';
                    });
                }
            });
            AuctoCmpData = StrData;
        }

Body:
Please put a common class name for all your textbox and using jQuery autocomplete you can do it.

 $(".auto").autocomplete({
        source: "../Ajax/AjaxGetData.ashx,
        minLength: 2,
        select: function(event, ui) {
            $(this).val(ui.item.value);
        }
    });

Please refer for more.
http://jqueryui.com/demos/autocomplete/#remote

What I am doing is to make a class called auto and assign it to all of the text box. so when ever the user enters the value it will be going to the handler page (asp.net) or u can use a .php page. In that handler page I am selecting data from database using the like operator of Sql.After selecting the values just Response.Write() (in asp.net) or echo(in php please refer) to send the data.The data is send in the JSON format

[ { "id":"XYZ" , "label":"XYZ" , "value": "XYZ"}]

The above is the format of JSON

For all auto suggest you might have a lot of data.To do so you have to get the total number of results returned after the execution of the query and make a loop.Initialize a string variable with the default value as "[" to the start and append the string with {"id":"Data","label:Data","value":"data"}(this constitutes a JSON object).If it is having more than you just add a , and do looping at the end add "]" to string.

So ur array will be in the format of

  [ { "id":"XYZ1" , "label":"XYZ1" , "value": "XYZ1"}, { "id":"XYZ2" , "label":"XYZ2" , "value": "XYZ2"}]

The [' denotes the starting of array and ']' denotes the end
The{` denotes the starting of object and '}' denotes the end

Pls refer  JSON  to know more


问:
What does Symfony cache:clear actually do?
I have bee using Symfony for a while now, and recently ran into an issue where the app/console cache:clear  didn't want to clear the cache.

I then discovered that you can manually remove the app/cache directory to clear the cache.

So aside from doing the app/cache folder, what does cache:clear actually do? Why would i keep using it rather than removing the cache folder?

答:
You can also attach event to clear some of your custom cache.
This mean if you remove cache directory, you're not sure to clear custom cache handling</p>


问:
Implement Motion Event in android button to show password on Edittext with alternate button clicks
I have an Edit text in android for a password field.The input type for the edit text is password.To, the right of the Edit text,I have a button which will show the password when the button is clicked.I have implemented the "Show Password" part using Motion Event in android.Below is the code which is working properly:

```<code>EditText passwordET;
Button showPassword;

passwordET = (EditText) findViewById(R.id.passwordET);
showPassword = (Button) findViewById(R.id.showpasswordBtn);

 showPassword.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        passwordET.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        return true;

                    case MotionEvent.ACTION_UP:
                        passwordET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        return true;
                }
                return true;
            }
        });
</code>```

The above code is working fine for the case when the user clicks on the Button, the password is shown and as the button touch event is removed, the text becomes Password field again. But,what I want is that if the button is clicked once,the edit text will show the password and the password will remain shown until the button is clicked again.So, when the button is clicked again, the edit text will change its state to password type again.Can anyone please let me know how to proceed?

答:
Use below code:

Define one flag,

```<code>    boolean isPassWordShowing = false;
</code>```

The click of ShowPassword Button:

```<code>showPassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(isPassWordShowing)
            {
                passwordET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                isPassWordShowing = false;
            }
            else
            {
                passwordET.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                isPassWordShowing = true;
            }

        }
    });
</code>```

Body:
I have an Edit text in android for a password field.The input type for the edit text is password.To, the right of the Edit text,I have a button which will show the password when the button is clicked.I have implemented the "Show Password" part using Motion Event in android.Below is the code which is working properly:

EditText passwordET;
Button showPassword;

passwordET = (EditText) findViewById(R.id.passwordET);
showPassword = (Button) findViewById(R.id.showpasswordBtn);

 showPassword.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        passwordET.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        return true;

                    case MotionEvent.ACTION_UP:
                        passwordET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        return true;
                }
                return true;
            }
        });

The above code is working fine for the case when the user clicks on the Button, the password is shown and as the button touch event is removed, the text becomes Password field again. But,what I want is that if the button is clicked once,the edit text will show the password and the password will remain shown until the button is clicked again.So, when the button is clicked again, the edit text will change its state to password type again.Can anyone please let me know how to proceed?

Body:
Use below code:

Define one flag,

    boolean isPassWordShowing = false;

The click of ShowPassword Button:

showPassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(isPassWordShowing)
            {
                passwordET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                isPassWordShowing = false;
            }
            else
            {
                passwordET.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                isPassWordShowing = true;
            }

        }
    });


问:
How can I create given query In SQL Server?
I want to create this query in SQL Server 2012 to add a column

In MySQL I use:

```<code>ALTER TABLE employee
  ADD COLUMN field BOOLEAN NOT NULL;
</code>```

答:
Couple of things wrong here

SQL Server does not have a boolean type - try bit type

SQL Server insists on a default value if you specify not null

Try

```<code>ALTER TABLE employee
    ADD BitFIELD BIT NOT NULL DEFAULT 0;
</code>```

Body:
I want to create this query in SQL Server 2012 to add a column

In MySQL I use:

ALTER TABLE employee
  ADD COLUMN field BOOLEAN NOT NULL;

Body:
Couple of things wrong here

SQL Server does not have a boolean type - try bit type

SQL Server insists on a default value if you specify not null

Try

ALTER TABLE employee
    ADD BitFIELD BIT NOT NULL DEFAULT 0;


问:
Kendo Grid Export To Excel Currency formatting
I am trying to export my Kendo grid to excel. It works fine except the formatting is missing. I think it is because I am using a template.

The Telerik documentation explicitly states:

To format the cell values during the export of the Grid to Excel, set
  the format option of the cells.

I have tried this and it is not working:

```<code>columns: [
    {
        field: "EntryWage",
        headerTemplate: entryLevelWageColumnHeading + "<span name='EntryWage' class='k-icon k-i-close remove' style='float: right;'></span>",
        width: 125,
        attributes: { style: "text-align:right;" },
        format: "{0:c}",
        template: "#= (EntryWage != null) ? kendo.toString(EntryWage, 'C') : 'N/A' #"
    }];
</code>```

I also have this function (for excel grid defintiion):

```<code>    excelExport: function (e) {
        var sheet = e.workbook.sheets[0];
        var row = sheet.rows[0];
        $("#grid .k-grid-header .k-link").each(function (index) { //for each column header in the grid...
            row.cells[index].value = $(this).text(); //set cell text from grid column text
            row.cells[index].background = "#0070C0"; //set cell to "blue" color
        });
    },
</code>```

Do I need to parse each cell here? Am I doing something wrong? I would think this would be really simple, since the whole Export to Excel is straightforward??

答:
I don't think template should have any effect on the data being exported (as the excelExport is based on the dataSource).

Here is a jsFiddle of a working example of excelExport which changes the formatting of each cell.

Note the difference between the excelExport code:

```<code>excelExport: function(e) {
  var sheet = e.workbook.sheets[0];

  for (var rowIndex = 0; rowIndex < sheet.rows.length; rowIndex++) {
    var row = sheet.rows[rowIndex];
    for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
        var cell = row.cells[cellIndex];
        if (row.type === "data") {
            //if (cellIndex == 2) {
            if (sheet.rows[0].cells[cellIndex].value == "unitPrice") {// like this
                cell.format = "number";
                cell.background = "#0070C0"
                cell.hAlign = "right";
            }
        }
    }
  }
</code>```

Body:
I am trying to export my Kendo grid to excel. It works fine except the formatting is missing. I think it is because I am using a template.

The Telerik documentation explicitly states:

To format the cell values during the export of the Grid to Excel, set
  the format option of the cells.

I have tried this and it is not working:

columns: [
    {
        field: "EntryWage",
        headerTemplate: entryLevelWageColumnHeading + "",
        width: 125,
        attributes: { style: "text-align:right;" },
        format: "{0:c}",
        template: "#= (EntryWage != null) ? kendo.toString(EntryWage, 'C') : 'N/A' #"
    }];

I also have this function (for excel grid defintiion):

    excelExport: function (e) {
        var sheet = e.workbook.sheets[0];
        var row = sheet.rows[0];
        $("#grid .k-grid-header .k-link").each(function (index) { //for each column header in the grid...
            row.cells[index].value = $(this).text(); //set cell text from grid column text
            row.cells[index].background = "#0070C0"; //set cell to "blue" color
        });
    },

Do I need to parse each cell here? Am I doing something wrong? I would think this would be really simple, since the whole Export to Excel is straightforward??

Body:
I don't think template should have any effect on the data being exported (as the excelExport is based on the dataSource).

Here is a jsFiddle of a working example of excelExport which changes the formatting of each cell.

Note the difference between the excelExport code:

excelExport: function(e) {
  var sheet = e.workbook.sheets[0];

  for (var rowIndex = 0; rowIndex < sheet.rows.length; rowIndex++) {
    var row = sheet.rows[rowIndex];
    for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
        var cell = row.cells[cellIndex];
        if (row.type === "data") {
            //if (cellIndex == 2) {
            if (sheet.rows[0].cells[cellIndex].value == "unitPrice") {// like this
                cell.format = "number";
                cell.background = "#0070C0"
                cell.hAlign = "right";
            }
        }
    }
  }


问:
what is the alternate method for driver.findelements("").get(i) in Ruby?
Let's say,

```<code>i=2
@driver.find_elements("...").get(i).click
</code>```

How to define similar method in ruby; any tweak on the same?

答:
Use this code to click that link

get method is not available for array, you can take first element by first and last element by last and if you want any other elements you could use [i]

```<code>@driver.find_elements("...")[i].click
</code>```

Body:
Let's say,

i=2
@driver.find_elements("...").get(i).click

How to define similar method in ruby; any tweak on the same?

Body:
Use this code to click that link

get method is not available for array, you can take first element by first and last element by last and if you want any other elements you could use [i]

@driver.find_elements("...")[i].click


问:
Drawable to byte[]
I have an image from the web in an ImageView. It is very small (a favicon) and I'd like to store it in my SQLite database.
I can get a Drawable from mImageView.getDrawable() but then I don't know what to do next. I don't fully understand the Drawable class in Android.

I know I can get a byte array from a Bitmap like:

```<code>Bitmap defaultIcon = BitmapFactory.decodeStream(in);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);

byte[] bitmapdata = stream.toByteArray();
</code>```

But how do I get a byte array from a Drawable?

答:
```<code>File myFile = new File(selectedImagePath);

byte [] mybytearray  = new byte [filelenghth];

BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(myFile));

bis1.read(mybytearray,0,mybytearray.length);
</code>```

now the image is stored in the bytearray..

Title: Drawable to byte[]

Body:
I have an image from the web in an ImageView. It is very small (a favicon) and I'd like to store it in my SQLite database.
I can get a Drawable from mImageView.getDrawable() but then I don't know what to do next. I don't fully understand the Drawable class in Android.

I know I can get a byte array from a Bitmap like:

Bitmap defaultIcon = BitmapFactory.decodeStream(in);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);

byte[] bitmapdata = stream.toByteArray();

But how do I get a byte array from a Drawable?

Body:
File myFile = new File(selectedImagePath);

byte [] mybytearray  = new byte [filelenghth];

BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(myFile));

bis1.read(mybytearray,0,mybytearray.length);

now the image is stored in the bytearray..


问:
Invalid advertisement payload when using BluetoothLEAdvertisementDataSection in Advertisement
I am a BLE newbie. I am using my Raspberry Pi 3, running Windows 10 Iot Core, to send some advertisement packets.

When sending only the Manufacturer Data, it works perfectly fine. But when I try to send data in Data Section, it gives me the following error.

The data is invalid. Invalid advertisement payload detected

Here is the code

Using only Manufacturer Data

```<code>private void StartPublish()
    {
        string data = "SHASHWAT";
        DataWriter writer = new DataWriter();
        writer.WriteInt32(data.Length);
        writer.WriteString(data);
        var adv = new BluetoothLEAdvertisement();

        var manufacturerData = new BluetoothLEManufacturerData(
          0x0006, writer.DetachBuffer());

        adv.ManufacturerData.Add(manufacturerData);

        var publisher = new BluetoothLEAdvertisementPublisher(adv);

        publisher.Start();
    }
</code>```

Using Data Section along with Manufacturer Data

```<code>private void StartPublishWithDataSection()
    {
        string data = "SHASHWAT";
        DataWriter writer = new DataWriter();
        writer.WriteInt32(data.Length);
        writer.WriteString(data);
        var adv = new BluetoothLEAdvertisement();

        var manufacturerData = new BluetoothLEManufacturerData(
          0x0006, writer.DetachBuffer());

        adv.ManufacturerData.Add(manufacturerData);

        DataWriter writer2 = new DataWriter();
        writer2.WriteString("Hello Shashwat");
        var dataSection = new BluetoothLEAdvertisementDataSection();
        dataSection.Data = writer2.DetachBuffer();
        adv.DataSections.Add(dataSection);

        var publisher = new BluetoothLEAdvertisementPublisher(adv);

        publisher.Start();
    }
</code>```

This throws invalid data exception.

Please let me know if I am doing something wrong.

Any help would be appreciated.

答:
The reason of this exception is advertisement payload length exceeds the limitation(official state this value is ~20 bytes). You can check here.

Based on my tests, the maximum length of the advertisement payload is 25 bytes including BluetoothLEManufacturerData and BluetoothLEAdvertisementDataSection.

Body:
I am a BLE newbie. I am using my Raspberry Pi 3, running Windows 10 Iot Core, to send some advertisement packets.

When sending only the Manufacturer Data, it works perfectly fine. But when I try to send data in Data Section, it gives me the following error.

The data is invalid. Invalid advertisement payload detected

Here is the code

Using only Manufacturer Data

private void StartPublish()
    {
        string data = "SHASHWAT";
        DataWriter writer = new DataWriter();
        writer.WriteInt32(data.Length);
        writer.WriteString(data);
        var adv = new BluetoothLEAdvertisement();

        var manufacturerData = new BluetoothLEManufacturerData(
          0x0006, writer.DetachBuffer());

        adv.ManufacturerData.Add(manufacturerData);

        var publisher = new BluetoothLEAdvertisementPublisher(adv);

        publisher.Start();
    }

Using Data Section along with Manufacturer Data

private void StartPublishWithDataSection()
    {
        string data = "SHASHWAT";
        DataWriter writer = new DataWriter();
        writer.WriteInt32(data.Length);
        writer.WriteString(data);
        var adv = new BluetoothLEAdvertisement();

        var manufacturerData = new BluetoothLEManufacturerData(
          0x0006, writer.DetachBuffer());

        adv.ManufacturerData.Add(manufacturerData);

        DataWriter writer2 = new DataWriter();
        writer2.WriteString("Hello Shashwat");
        var dataSection = new BluetoothLEAdvertisementDataSection();
        dataSection.Data = writer2.DetachBuffer();
        adv.DataSections.Add(dataSection);

        var publisher = new BluetoothLEAdvertisementPublisher(adv);

        publisher.Start();
    }

This throws invalid data exception.

Please let me know if I am doing something wrong.

Any help would be appreciated.


问:
Validate Command in CQRS that related to other domain
I am learning to develop microservices using DDD, CQRS, and ES. It is HTTP RESTful service. The microservices is about online shop. There are several domains like products, orders, suppliers, customers, and so on. The domains built in separate services. How to do the validation if the command payload relates to other domains?

For example, here is the addOrderItemCommand payload in the order service (command-side).

```<code>{
"customerId": "CUST111",
"productId": "SKU222",
"orderId":"SO333"
}
</code>```

How to validate the command above? How to know that the customer is really exists in database (query-side customer service) and still active? How to know that the product is exists in database and the status of the product is published? How to know whether the customer eligible to get the promo price from the related product?

Is it ok to call API directly (like point-to-point / ajax / request promise) to validate this payload in order command-side service? But I think, the performance will get worse if the API called directly just for validation. Because, we have developed an event processor outside the command-service that listen from the event and apply the event to the materalized view.

Thank you.

答:
As always everything depends on the specifics of the domain but as a general principle cross domain validation should be done via the read model.

In this case, I would maintain a read model within each microservice for use in validation. Of course, that brings with it the question of eventual consistency.
How you handle that should come from your understanding of the domain. Factors such as the length of the eventual consistency compared to the frequency of updates should be considered. The cost of getting it wrong for the business compared to the cost of development to minimise the problem. In many cases, just recording the fact there has been a problem is more than adequate for the business.

I have a blog post dedicated to validation which you can find here: How To Validate Commands in a CQRS Application

Body:
I am learning to develop microservices using DDD, CQRS, and ES. It is HTTP RESTful service. The microservices is about online shop. There are several domains like products, orders, suppliers, customers, and so on. The domains built in separate services. How to do the validation if the command payload relates to other domains?

For example, here is the addOrderItemCommand payload in the order service (command-side).

{
"customerId": "CUST111",
"productId": "SKU222",
"orderId":"SO333"
}

How to validate the command above? How to know that the customer is really exists in database (query-side customer service) and still active? How to know that the product is exists in database and the status of the product is published? How to know whether the customer eligible to get the promo price from the related product?

Is it ok to call API directly (like point-to-point / ajax / request promise) to validate this payload in order command-side service? But I think, the performance will get worse if the API called directly just for validation. Because, we have developed an event processor outside the command-service that listen from the event and apply the event to the materalized view.

Thank you.


问:
Using when and done and settimeout show hide div

function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  $.when(
    setTimeout(function() {
      closecustomBox();
    }, 3000)
  ).done(function(x) {
    $('#anotherdialog').show();
  });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}</code>```

show
```

What I want to happened is after clicking show will show the red box after 3 seconds the red box will hide then the blue box should show.

I want to achieve here is to not make the 2 div appear together

答:
$.when is taking input parameters, when those resolve, then it will excute the done function. In your case setTimeout function is executed successfully, so it is calling done method instantly without waiting to upto 3sec. To make it work, you need to use Promise concept here.

function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  var $def = $.Deferred();
  $.when(
    $def
  ).done(function(x) {
    $('#anotherdialog').show();
  });
  setTimeout(function() {
    closecustomBox();
    $def.resolve(true);
  }, 3000);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}</code>```

show
```

Body:
function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  $.when(
    setTimeout(function() {
      closecustomBox();
    }, 3000)
  ).done(function(x) {
    $('#anotherdialog').show();
  });
})

#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}

show

What I want to happened is after clicking show will show the red box after 3 seconds the red box will hide then the blue box should show.

I want to achieve here is to not make the 2 div appear together

Body:
$.when is taking input parameters, when those resolve, then it will excute the done function. In your case setTimeout function is executed successfully, so it is calling done method instantly without waiting to upto 3sec. To make it work, you need to use Promise concept here.

function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  var $def = $.Deferred();
  $.when(
    $def
  ).done(function(x) {
    $('#anotherdialog').show();
  });
  setTimeout(function() {
    closecustomBox();
    $def.resolve(true);
  }, 3000);
})

#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}

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

<div id="anotherdialog"></div>

<div id="show">show</div>


问:
How get the current date and the timezone in numbers format
I want to print the current date in this format 2017/06/05 > Year/Month/Day
and next to it, the  current timezone in this format +3

I used this code

```<code>String DateToday  = DateFormat.getDateInstance().format(new Date());
String TZtoday = DateFormat.getTimeInstance().getTimeZone().getDisplayName();
txt.setText(DateToday + " | "+ TZtoday );
</code>```

But, it shows like this:

Jun 5, 2017 | Arabia Standard Time

I want it like this:

2017/06/05 | +3

答:
USe the following logic to get the desired date format.</p>

```<code>    public static void main(String[] args) {

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"

        String formatted = format1.format(cal.getTime());
        String formattedmain=formatted.replace("-","/");
        System.out.println(formatted);
        // Output "2012-09-26"
        System.out.println(formattedmain);

//Output :- 2017/06/06

    }
</code>```

Body:
I want to print the current date in this format 2017/06/05 > Year/Month/Day
and next to it, the  current timezone in this format +3

I used this code

String DateToday  = DateFormat.getDateInstance().format(new Date());
String TZtoday = DateFormat.getTimeInstance().getTimeZone().getDisplayName();
txt.setText(DateToday + " | "+ TZtoday );

But, it shows like this:

Jun 5, 2017 | Arabia Standard Time

I want it like this:

2017/06/05 | +3

Body:
USe the following logic to get the desired date format.

    public static void main(String[] args) {

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"

        String formatted = format1.format(cal.getTime());
        String formattedmain=formatted.replace("-","/");
        System.out.println(formatted);
        // Output "2012-09-26"
        System.out.println(formattedmain);

//Output :- 2017/06/06

    }


问:
How to refer to a cell outside of cellForRowAtIndexPath
I am trying to update a label in a cell outside of

```<code>override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
</code>```

by using

```<code>let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell
</code>```

in another function. However, I keep getting errors. Therefore, I tried to refer to the cell by using let cell = Cell(), but I get the error unexpectedly found nil. Lastly, I tried

```<code>let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! Cell
</code>```

that does not return an error, but the label cell.time.text is not updated.

答:
Do not use dequeueReusableCellWithIdentifier outside the cellForRowAtIndexPath method.

You should use cellForRow(at:)
https://developer.apple.com/reference/uikit/uitableview/1614983-cellforrow

Body:
I am trying to update a label in a cell outside of

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

by using

let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell

in another function. However, I keep getting errors. Therefore, I tried to refer to the cell by using let cell = Cell(), but I get the error unexpectedly found nil. Lastly, I tried

let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! Cell

that does not return an error, but the label cell.time.text is not updated.


问:
How do I keep the current tab active with twitter bootstrap after a page reload?
I'm currently using tabs with Twitter Bootstrap and want to select the same tab after a user has posted data and the page reloads.

How is this done?

My current call to inti the tabs looks like this:

```<code><script type="text/javascript">

$(document).ready(function() {

    $('#profileTabs a:first').tab('show');
});
</script>
</code>```

My tabs:

```<code><ul id="profileTabs" class="nav nav-tabs">
    <li class="active"><a href="#profile" data-toggle="tab">Profile</a></li>
    <li><a href="#about" data-toggle="tab">About Me</a></li>
    <li><a href="#match" data-toggle="tab">My Match</a></li>
</ul>
</code>```

答:
$(document).ready(function () {

```<code>        if (JSON.parse(localStorage.getItem('currentClass')) == "active")
        {
            jQuery('#supporttbl').addClass('active')
            $('.sub-menu').css({ "display": "block" });
        }

        $("#supporttbl").click(function () {
            var currentClass;
            if ($(this).attr('class')== "active") {

                currentClass = $(this).attr('class');

                localStorage.setItem('currentClass', JSON.stringify(currentClass));
                console.log(JSON.parse(localStorage.getItem('currentClass')));

                jQuery('#supporttbl').addClass('active')
                $('.sub-menu').css({ "display": "block" });

            } else {

                currentClass = "Null";

                localStorage.setItem('currentClass', JSON.stringify(currentClass));
                console.log(JSON.parse(localStorage.getItem('currentClass')));

                jQuery('#supporttbl').removeClass('active')
                $('.sub-menu').css({ "display": "none" });

            }
        });
</code>```

});

Body:
I'm currently using tabs with Twitter Bootstrap and want to select the same tab after a user has posted data and the page reloads.

How is this done?

My current call to inti the tabs looks like this:

My tabs:

Profile

About Me

My Match

Body:
$(document).ready(function () {

        if (JSON.parse(localStorage.getItem('currentClass')) == "active")
        {
            jQuery('#supporttbl').addClass('active')
            $('.sub-menu').css({ "display": "block" });
        }

        $("#supporttbl").click(function () {
            var currentClass;
            if ($(this).attr('class')== "active") {

                currentClass = $(this).attr('class');

                localStorage.setItem('currentClass', JSON.stringify(currentClass));
                console.log(JSON.parse(localStorage.getItem('currentClass')));

                jQuery('#supporttbl').addClass('active')
                $('.sub-menu').css({ "display": "block" });

            } else {

                currentClass = "Null";

                localStorage.setItem('currentClass', JSON.stringify(currentClass));
                console.log(JSON.parse(localStorage.getItem('currentClass')));

                jQuery('#supporttbl').removeClass('active')
                $('.sub-menu').css({ "display": "none" });

            }
        });

});


问:
getContentView() from android BottomSheetDialog
Is there any way to get ContentView from android BottomSheetDialog ? In PopupWindow , I can get PopupWindow 's view by popupWindow.getContentView() method. But, I cann't find any method to get ConentView from BottomSheetDialog .

答:
Please try this:  </p>

```<code>View contentView = bottomSheetDialog.findViewById(android.R.id.content);
</code>```

Body:
Please try this:

View contentView = bottomSheetDialog.findViewById(android.R.id.content);


问:
Div with text wont stay centered
I'm creating a simple image gallery. Above the images I name the place where the pictures were taken, but the second and every another row has issues - div with the name is being pushed to the right instead of staying centered. Here is how it looks: http://prntscr.com/fg10u4

@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css);
.locationName {
  text-align: center;
  padding: 0px 0px 20px 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row" id="locations">

  <div class="locationName">
    City
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="1.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>
</div></code>```

Obviously the code is doubled inside the "row" div.

答:
You can use center tag like this

        ....

```

Title: Div with text wont stay centered

Body:
I'm creating a simple image gallery. Above the images I name the place where the pictures were taken, but the second and every another row has issues - div with the name is being pushed to the right instead of staying centered. Here is how it looks: http://prntscr.com/fg10u4

@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css);
.locationName {
  text-align: center;
  padding: 0px 0px 20px 20px;
}

    City

Obviously the code is doubled inside the "row" div.

Body:
You can use center tag like this

<div class="row" id="locations">
    <center>
        ....
    </center>
</div>


问:
Chart.js - Line charts: draw points between grid lines
I'm creating line charts using Chart.js version 2.1.3.

I want to center labels and points between grid lines on the x axis (like in bar charts).

For labels, I use the option 'offsetGridLines' that offset labels from grid lines:

```<code>scales: {
    xAxes: [{
        gridLines: {
            offsetGridLines: true
        }
    }],
    ...
</code>```

Nevertheless, I can't found a convenient solution to center points.

Here is my initial example (labels placed between grid lines): https://jsfiddle.net/24aotbnc/1/.

And here is my non-elegant solution that creates an empty dataset of type 'bar' and removes it after chart creation (points are drawn between gridlines): https://jsfiddle.net/24aotbnc/2/

Can someone provide a better solution? Thanks.

答:
The position x (either with or without offset) for the Line points are calculated only on the basis of dataset length </p>

```<code> var includeOffset = (labels.length === 1 || dataset.data.length === 1) || me.chart.isCombo;
 x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex, includeOffset);
</code>```

<p>So the includeOffset decides the position of the line points to be in middle or left for the region and no way to configure it. </p>

Body:
I'm creating line charts using Chart.js version 2.1.3.

I want to center labels and points between grid lines on the x axis (like in bar charts).

For labels, I use the option 'offsetGridLines' that offset labels from grid lines:

scales: {
    xAxes: [{
        gridLines: {
            offsetGridLines: true
        }
    }],
    ...

Nevertheless, I can't found a convenient solution to center points.

Here is my initial example (labels placed between grid lines): https://jsfiddle.net/24aotbnc/1/.

And here is my non-elegant solution that creates an empty dataset of type 'bar' and removes it after chart creation (points are drawn between gridlines): https://jsfiddle.net/24aotbnc/2/

Can someone provide a better solution? Thanks.

Body:
The position x (either with or without offset) for the Line points are calculated only on the basis of dataset length

 var includeOffset = (labels.length === 1 || dataset.data.length === 1) || me.chart.isCombo;
 x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex, includeOffset);

So the includeOffset decides the position of the line points to be in middle or left for the region and no way to configure it.


问:
Cannot index file larger than 100MB in elastic search
I am trying to index a json file size of 128MB.But due to some reason, I am not able to index it and it shows no error , nothing. But if I break the file to two files size 50mb and 60mb or any size less than 100mb, the file is indexed. Since it gives me no error, I have no idea why I cannot index the file

I am using this command

```<code>curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/novcart/sales/_bulk' --data-binary @novcart2.json
</code>```

答:
By default ES is configured to handle payloads of 100MB maximum. The setting you need to change is called http.max_content_length.

You can increase this limit simply by adding this to your elasticsearch.yml configuration file and restarting ES:

```<code>http.max_content_length: 150mb
</code>```

Body:
I am trying to index a json file size of 128MB.But due to some reason, I am not able to index it and it shows no error , nothing. But if I break the file to two files size 50mb and 60mb or any size less than 100mb, the file is indexed. Since it gives me no error, I have no idea why I cannot index the file

I am using this command

curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/novcart/sales/_bulk' --data-binary @novcart2.json

Body:
By default ES is configured to handle payloads of 100MB maximum. The setting you need to change is called http.max_content_length.

You can increase this limit simply by adding this to your elasticsearch.yml configuration file and restarting ES:

http.max_content_length: 150mb


问:
Are the Oct 2010 Macbook Airs sufficiently capable to run all the tools to develop iPhone apps on?
Pretty much as the title says. I'll likely use Monotouch for some/all projects if that makes a difference (noting this still needs a Mac).

I've read this Question...

Macbook Air for iPhone Development?

...and see the related answers note performance issues and buggy/non performant screen spanning issues on previous generation models.

I'd like to know if these two issues are resolved with the new specs.

Observations on performance running Win7 and WP7 under bootcamp are welcome but not required. Related question raised here looking for specifics on WDDM1.1 compliance on this model if you care to comment there.

edit: formating/highlighting.

答: The new models will be more than capable of running all tools required to develop iPhone apps on. The most notable performance improvement will be the integrated SSD memory. This makes up for the slightly slower processor speed when compared with the 13" MacBook Pro.</p>


问:
Google plus Login and Google maps are not working after app is published on Play Store
I have the problem while sign in using Google and displaying Google Maps. Recently, I changed package names and got into this problem.
I know for the app to be work fine it has to be released in the Signed mode and then upload it to Google play. I did the same, the app is completely working in release mode but it's not working when I download it from Google play. I changed the package name in Android Manifest and build.gradle file.

Also, I create the new project on Google console and create new keys by enabling the Google Maps API and Google plus API. Now, I am not able to figure out the problem.

I created keys multiple times and try to upload build every time with updated keys but the problem does not solved.
It would be great if someone help me out.

答: Go to app Signing section under App release in Google play, here you can find a new SHA-1 key, upload that key in Firebase and everything starts working.</p>


答:
Swift 3.0  &  Swift 4

```<code>let indexPath = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: indexPath)
</code>```

Swift 2.3

```<code>let indexPath = NSIndexPath(forRow: 0, inSection: 0)
let cell = tableView.cellForRowAtIndexPath(indexPath)
</code>```

NOTE :- With help of above method you can only get visible cell of tableView except cell is nil

Title: How to refer to a cell outside of cellForRowAtIndexPath

Body:
Swift 3.0  &  Swift 4

let indexPath = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: indexPath)

Swift 2.3

let indexPath = NSIndexPath(forRow: 0, inSection: 0)
let cell = tableView.cellForRowAtIndexPath(indexPath)

NOTE :- With help of above method you can only get visible cell of tableView except cell is nil


问:
Every command is returning 'bash: <command>: command not found...'
I just installed Scala and added the path with gedit ./bashrc:

```<code>export SCALA_HOME=/home/avijit/scala-2.12.2
export PATH=$SCALA_HOME/bin:PATH
</code>```

but since then, no command is working:

```<code>[avijit@localhost-localdomain ~]$ ls
bash: ls: command not found...
</code>```

I gave the full path but:

```<code>[avijit@localhost-localdomain ~]$ /home/avijit/.bashrc
bash: /home/avijit/.bashrc: Permission denied
</code>```

Even vi is not working so that I can fix the mess in the path.

```<code>[avijit@localhost-localdomain ~]$ vi /home/avijit/.bashrc
bash: vim: command not found...
[avijit@localhost-localdomain ~]$ sudo /home/avijit/.bashrc
bash: sudo: command not found...
[avijit@localhost-localdomain ~]$ echo $path
</code>```

<- returned blank line

I tried many steps from different forums but no luck. How can I fix this?

答:
Problem is with export PATH=$SCALA_HOME/bin:PATH in this you missed $.

Update default variable as PATH=$SCALA_HOME/bin:$PATH

Body:
I just installed Scala and added the path with gedit ./bashrc:

export SCALA_HOME=/home/avijit/scala-2.12.2
export PATH=$SCALA_HOME/bin:PATH

but since then, no command is working:

[avijit@localhost-localdomain ~]$ ls
bash: ls: command not found...

I gave the full path but:

[avijit@localhost-localdomain ~]$ /home/avijit/.bashrc
bash: /home/avijit/.bashrc: Permission denied

Even vi is not working so that I can fix the mess in the path.

[avijit@localhost-localdomain ~]$ vi /home/avijit/.bashrc
bash: vim: command not found...
[avijit@localhost-localdomain ~]$ sudo /home/avijit/.bashrc
bash: sudo: command not found...
[avijit@localhost-localdomain ~]$ echo $path

<- returned blank line

I tried many steps from different forums but no luck. How can I fix this?


问:
Hot-deploy Liferay 7 webapp resource (JavaScript/CSS/HTML)
I am developing a Liferay 7 portlet with bundled Tomcat 7.

To deploying a portlet, I copy the war file into deploy folder under Liferay home folder, and then I have to wait a lot of minutes to see my file modified.

Usually I work only on javascript, css and html, I want to see immediately what I changed, then, is there a way to have hot deploy for webapp resource?

Thanks

答: You should use the Liferay workspaces and modules. If it is a theme, the gulp watch task will help.</p>


问:
I want to add some images in my apps by android studio
I want to add some images in my apps by android studio. but its not working, please help me how can i add more images.

deign and XML Screenshot uploaded.

Please help me,

Thanks
Miraz

Screenshots:
design
xml code

答:
You can change your layout type to Linear Layout or Relative Layout and "YES" you can set value in parentage like this:-

```<code>ImageView image_view = (ImageView) findViewById(R.id.image_view);
calulate(image_view);

private void calulate(View v)
{
    int imgWidth = this.getResources().getDisplayMetrics().widthPixels;
    int imgHeight = this.getResources().getDisplayMetrics().heightPixels;
    v.getLayoutParams().height = (int) (0.25*imgHeight);//You can change 0.25 with your value
    v.getLayoutParams().width = (int) (0.25*imgWidth);
}
</code>```

Body:
You can change your layout type to Linear Layout or Relative Layout and "YES" you can set value in parentage like this:-

ImageView image_view = (ImageView) findViewById(R.id.image_view);
calulate(image_view);

private void calulate(View v)
{
    int imgWidth = this.getResources().getDisplayMetrics().widthPixels;
    int imgHeight = this.getResources().getDisplayMetrics().heightPixels;
    v.getLayoutParams().height = (int) (0.25*imgHeight);//You can change 0.25 with your value
    v.getLayoutParams().width = (int) (0.25*imgWidth);
}


问:
device descriptor read/64, error -110
I have a storage server running openmediavault which is based on debian.
The OS is in a USB 3.0 Stick pluged directly on the motherboard (no USB-Hub or sth).
The system was running fine for about 3 Months and 2 days ago I got this errors:

```<code>usb 1-3: device descriptor read/64, error -110
usb 1-3: device not accepting address 33, error -110
usb 1-3: device not accepting address 34, error -110
hub 1-0:1.0: unable to enumerate USB device on port 3
</code>```

When I restart the server, everything is fine again.
The next day I face the same error...

What can I do to fix this. I dont want to loose 3TB of data...

答:
I had the same error, but with no USB device plugged in. I have a Suse 13.2 and 42.2 installed on an internal ssd drive in a HP ProBook 430. When I booted into 42.2, I got that error

device descriptor read/64, error -110

and booting simply stopped there. Weird enough with 13.2 on the same hard disk I could boot with no problems.
Following Johnsters advice to unplug any power supply including battery removal finally did it, so loads of thanks go there.
And to all running into this post without any obvious interaction of USB devices in their problems: Try making your system voltage free, it still might do the trick.

Title: device descriptor read/64, error -110

Body:
I have a storage server running openmediavault which is based on debian.
The OS is in a USB 3.0 Stick pluged directly on the motherboard (no USB-Hub or sth).
The system was running fine for about 3 Months and 2 days ago I got this errors:

usb 1-3: device descriptor read/64, error -110
usb 1-3: device not accepting address 33, error -110
usb 1-3: device not accepting address 34, error -110
hub 1-0:1.0: unable to enumerate USB device on port 3

When I restart the server, everything is fine again.
The next day I face the same error...

What can I do to fix this. I dont want to loose 3TB of data...