问:
Java Spring Hibernate Saving Duplicate Values to MySQL table is throwing error
I am trying to save some values to a MYSQL database using CrudRepository but doesnt seem to work. I have tried the following guide https://spring.io/guides/gs/accessing-data-mysql/ and it works fine but when iam trying to follow the same principle for my program it doesnt seem to work for some reason.

Here is the class iam creating a database for, The table gets created properly:

```<code> @Entity
 public class MeasurementPoint {

 @Id

 @JsonProperty("f1")
 private double f1;

 @JsonProperty("precison")
 private double precison;

 @JsonProperty("recall")
 private double recall;

 private String date;

 public MeasurementPoint(double f1, double precison, double recall, String
 date)  {
     this.f1 = f1;
     this.precison = precison;
     this.recall = recall;
     this.date=date;
 }

 public double getF1() {
     return f1;
 }

 public double getPrecison() {
     return precison;
 }

 public String getDate() {
     return date;
 }
 public double getRecall() {
     return recall;
 }
}
</code>```

Here is the MSQL terminal outputting the columns for the entity created:

```<code>+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| f1       | double       | NO   | PRI | NULL    | auto_increment |
| date     | varchar(255) | YES  |     | NULL    |                |
| precison | double       | NO   |     | NULL    |                |
| recall   | double       | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
</code>```

Here is the class iam trying to add values to the database from:

```<code>@Controller
public class DataChart {

private static final Logger logger= LoggerFactory.getLogger(DataChart.class);

@Autowired
private static MeasurementRepository measurementRepository;

@GetMapping(value = "/statementchart")
@ResponseBody
public List<Measurement> scoreChartData() {

    List<MeasurementPoint> needDataPoints = new ArrayList<>();
    List<MeasurementPoint> backgroundDataPoints = new ArrayList<>();
    List<MeasurementPoint> goalDataPoints=new ArrayList<>();
    needDataPoints.add(new MeasurementPoint(0.3, 0.5, 0.2,  "2017-11-19"));
    needDataPoints.add(new MeasurementPoint(0.7, 0.4, 0.15, "2017-11-12"));
    needDataPoints.add(new MeasurementPoint(0.5, 0.3, 0.10, "2017-11-15"));
    needDataPoints.add(new MeasurementPoint(0.6, 0.2, 0.05, "2017-11-18"));
    measurementRepository.save(needDataPoints);

    backgroundDataPoints.add(new MeasurementPoint(0.2, 0.4, 0.2, "2017-11-19"));
    backgroundDataPoints.add(new MeasurementPoint(0.4, 0.3, 0.15, "2017-11-12"));
    measurementRepository.save(backgroundDataPoints);
   //backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
   //measurementRepository.save(backgroundDataPoints);
</code>```

Here is the output from saving these points:

```<code>+-----+------------+----------+--------+
| f1  | date       | precison | recall |
+-----+------------+----------+--------+
| 0.2 | 2017-11-19 |      0.4 |    0.2 |
| 0.3 | 2017-11-19 |      0.5 |    0.2 |
| 0.4 | 2017-11-12 |      0.3 |   0.15 |
| 0.5 | 2017-11-15 |      0.3 |    0.1 |
| 0.6 | 2017-11-18 |      0.2 |   0.05 |
| 0.7 | 2017-11-12 |      0.4 |   0.15 |
+-----+------------+----------+--------+
6 rows in set (0.00 sec)
</code>```

Here is my CrudRepository class:

```<code>public interface MeasurementRepository extends CrudRepository<MeasurementPoint,Long> {
}
</code>```

SOLVED

saving these points works fine but as soon i save that out-commented new MeasurementPoint

```<code>//backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
//measurementRepository.save(backgroundDataPoints);
</code>```

i get a error saying: I guess it has to do with duplicate values but how do i fix this?

```<code>javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session :
</code>```

I solved it by creating a field of type long called id with annotation @Id because apparently every object created should get a unique id, the error thrown is because objects had some id. @GeneratedValue makes sure that everytime a new object is created a unqiue Id is given to that object.

```<code>    @Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
</code>```

答:
I think data is not saved because of errors. You just need to check logs. Enable Hibernate SQL logs and check insert statement there.

You have f1 as autogenerated column, but set value to it. Also I am not sure that double column can be autogenerated.

Hibernate needs a default constructor. MeasurementPoint doesn't have one.

This means java.lang.NullPointerException: null(DataChart.java:30)
that Spring doesn't set measurementRepository field. Try to remove the static modifier.

This  org.hibernate.PersistentObjectException: detached entity passed to persist: means that you shouldn't specify f1 using the save method.

Body:
I am trying to save some values to a MYSQL database using CrudRepository but doesnt seem to work. I have tried the following guide https://spring.io/guides/gs/accessing-data-mysql/ and it works fine but when iam trying to follow the same principle for my program it doesnt seem to work for some reason.

Here is the class iam creating a database for, The table gets created properly:

 @Entity
 public class MeasurementPoint {

 @Id

 @JsonProperty("f1")
 private double f1;

 @JsonProperty("precison")
 private double precison;

 @JsonProperty("recall")
 private double recall;

 private String date;

 public MeasurementPoint(double f1, double precison, double recall, String
 date)  {
     this.f1 = f1;
     this.precison = precison;
     this.recall = recall;
     this.date=date;
 }

 public double getF1() {
     return f1;
 }

 public double getPrecison() {
     return precison;
 }

 public String getDate() {
     return date;
 }
 public double getRecall() {
     return recall;
 }
}

Here is the MSQL terminal outputting the columns for the entity created:

+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| f1       | double       | NO   | PRI | NULL    | auto_increment |
| date     | varchar(255) | YES  |     | NULL    |                |
| precison | double       | NO   |     | NULL    |                |
| recall   | double       | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

Here is the class iam trying to add values to the database from:

@Controller
public class DataChart {

private static final Logger logger= LoggerFactory.getLogger(DataChart.class);

@Autowired
private static MeasurementRepository measurementRepository;

@GetMapping(value = "/statementchart")
@ResponseBody
public List<Measurement> scoreChartData() {

    List<MeasurementPoint> needDataPoints = new ArrayList<>();
    List<MeasurementPoint> backgroundDataPoints = new ArrayList<>();
    List<MeasurementPoint> goalDataPoints=new ArrayList<>();
    needDataPoints.add(new MeasurementPoint(0.3, 0.5, 0.2,  "2017-11-19"));
    needDataPoints.add(new MeasurementPoint(0.7, 0.4, 0.15, "2017-11-12"));
    needDataPoints.add(new MeasurementPoint(0.5, 0.3, 0.10, "2017-11-15"));
    needDataPoints.add(new MeasurementPoint(0.6, 0.2, 0.05, "2017-11-18"));
    measurementRepository.save(needDataPoints);

    backgroundDataPoints.add(new MeasurementPoint(0.2, 0.4, 0.2, "2017-11-19"));
    backgroundDataPoints.add(new MeasurementPoint(0.4, 0.3, 0.15, "2017-11-12"));
    measurementRepository.save(backgroundDataPoints);
   //backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
   //measurementRepository.save(backgroundDataPoints);

Here is the output from saving these points:

+-----+------------+----------+--------+
| f1  | date       | precison | recall |
+-----+------------+----------+--------+
| 0.2 | 2017-11-19 |      0.4 |    0.2 |
| 0.3 | 2017-11-19 |      0.5 |    0.2 |
| 0.4 | 2017-11-12 |      0.3 |   0.15 |
| 0.5 | 2017-11-15 |      0.3 |    0.1 |
| 0.6 | 2017-11-18 |      0.2 |   0.05 |
| 0.7 | 2017-11-12 |      0.4 |   0.15 |
+-----+------------+----------+--------+
6 rows in set (0.00 sec)

Here is my CrudRepository class:

public interface MeasurementRepository extends CrudRepository<MeasurementPoint,Long> {
}

SOLVED

saving these points works fine but as soon i save that out-commented new MeasurementPoint

//backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
//measurementRepository.save(backgroundDataPoints);

i get a error saying: I guess it has to do with duplicate values but how do i fix this?

javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session :

I solved it by creating a field of type long called id with annotation @Id because apparently every object created should get a unique id, the error thrown is because objects had some id. @GeneratedValue makes sure that everytime a new object is created a unqiue Id is given to that object.

    @Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;


来源: stackexchange

问:
Run large sql script
I have just reloaded my laptop and am now trying to setup my localhost again.

Currently I am trying to re-setup the database.

the issue is,

The script is 169,328 KB.

This keeps crashing whatever I use to run the query and I get the error: The mysql Server has gone away.

Seems everyone is suggesting splitting the script. Instead as this is only me setting my localhost back up, I have temporarily increased the max_packet_size.

答:
If you're looking to avoid the err message, consider one of these remedies:

ensure that your environment or commands aren't causing this issue. Causes for MySQL gone-away.

split your large script into smaller scripts. You could then run those in sequence.

ContentLicense: CC BY-SA 2.5

Title: Run large sql script


问:
How to sort Integer digits in ascending order without Strings or Arrays?
I'm trying to sort the digits of an integer of any length in ascending order without using Strings, arrays or recursion.

Example:

```<code>Input: 451467
Output: 144567
</code>```

I have already figured out how to get each digit of the integer with modulus division:

```<code>int number = 4214;

while (number > 0) {
    IO.println(number % 10);
    number = number / 10;
}
</code>```

but I don't know how to order the digits without an array.

Don't worry about the IO class; it's a custom class our professor gave us.

答:
Since the possible elements (i. e. digits) in a number are known (0 to 9) and few (10 in total), you can do this:

Print a 0 for every 0 in the number.

Print a 1 for every 1 in the number.

```<code>    int number = 451467;

    // the possible elements are known, 0 to 9
    for (int i = 0; i <= 9; i++) {
        int tempNumber = number;

        while (tempNumber > 0) {
            int digit = tempNumber % 10;
            if (digit == i) {
                IO.print(digit);
            }
            tempNumber = tempNumber / 10;
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to sort the digits of an integer of any length in ascending order without using Strings, arrays or recursion.

Example:

Input: 451467
Output: 144567

I have already figured out how to get each digit of the integer with modulus division:

int number = 4214;

while (number > 0) {
    IO.println(number % 10);
    number = number / 10;
}

but I don't know how to order the digits without an array.

Don't worry about the IO class; it's a custom class our professor gave us.

Body:
Since the possible elements (i. e. digits) in a number are known (0 to 9) and few (10 in total), you can do this:

Print a 0 for every 0 in the number.

Print a 1 for every 1 in the number.

    int number = 451467;

    // the possible elements are known, 0 to 9
    for (int i = 0; i <= 9; i++) {
        int tempNumber = number;

        while (tempNumber > 0) {
            int digit = tempNumber % 10;
            if (digit == i) {
                IO.print(digit);
            }
            tempNumber = tempNumber / 10;
        }
    }

ContentLicense: CC BY-SA 4.0


问:
Write Fortran-like format to file in Python
In Fortran, I can use:

```<code>open(10, file = 'output')
write(10, '(5A10)') 'apple', 'banana', 'orange', 'grape', 'berry'
</code>```

Is there a similar way in Python of writing the output?

I know I can use:

```<code>f.write('%5s\t%5s\t%5s\t%5s\t%5s' % ('apple', 'banana', 'orange', 'grape', 'berry'))
</code>```

But how can I make it more compact? Using a similar way of '(5A10)', instead of the lengthy '%5s\t%5s\t%5s\t%5s\t%5s'.

答:
You can use fortranformat:
https://pypi.python.org/pypi/fortranformat

Works great!

```<code>>>> import fortranformat as ff
>>> header_line = ff.FortranRecordWriter('(A15, A15, A15)')
>>> header_line.write(['x', 'y', 'z'])
  '              x              y              z'
>>> line = FortranRecordWriter('(3F15.3)')
>>> line.write([1.0, 0.0, 0.5])
  '          1.000          0.000          0.500'
>>> line.write([1.1, 0.1, 0.6])
  '          1.100          0.100          0.600'
</code>```

Body:
In Fortran, I can use:

open(10, file = 'output')
write(10, '(5A10)') 'apple', 'banana', 'orange', 'grape', 'berry'

Is there a similar way in Python of writing the output?

I know I can use:

f.write('%5s\t%5s\t%5s\t%5s\t%5s' % ('apple', 'banana', 'orange', 'grape', 'berry'))

But how can I make it more compact? Using a similar way of '(5A10)', instead of the lengthy '%5s\t%5s\t%5s\t%5s\t%5s'.

Body:
You can use fortranformat:
https://pypi.python.org/pypi/fortranformat

Works great!

>>> import fortranformat as ff
>>> header_line = ff.FortranRecordWriter('(A15, A15, A15)')
>>> header_line.write(['x', 'y', 'z'])
  '              x              y              z'
>>> line = FortranRecordWriter('(3F15.3)')
>>> line.write([1.0, 0.0, 0.5])
  '          1.000          0.000          0.500'
>>> line.write([1.1, 0.1, 0.6])
  '          1.100          0.100          0.600'


问:
How to append element with angular material2 style?
I'm making a template that if button is clicked then append elements that I want to.
I could append it exactly with following codes but I couldn't add style, angular-material2.
If you have any idea, leave your tip, please.

make-template.component.ts

```<code>@ViewChild('tContent') content: ElementRef;

  addTbody() {
    let content = document.getElementById('tContent');
    console.log(this.content.nativeElement);
    this.renderer.invokeElementMethod(this.content.nativeElement, 'insertAdjacentHTML', [`beforeend`,
  `
  <tr>
    <td>
      <input type="file">
    </td>
    <td>
      <input type="file">
    </td>
  </tr>
  <tr>
    <td>
      <mat-input-container>
        <input matInput placeholder="image Info" type="text">
      </mat-input-container>
    </td>
    <td>
      <mat-input-container>
        <input matInput placeholder="image Info" type="text">
      </mat-input-container>
    </td>
  </tr>
`]);
</code>```

}

make-template.component.html

```<code>...
<tbody #tContent>
          // add here
</tbody>
<button type="button" mat-raised-button color="primary" (click)="addTbody()">click here</button>
</code>```

答:
I wouldn't use renderer and @Viewchild, and this is not an issue that is linked to your use of material2 but is a basic Angular pattern.

I personally would do this :

```<code><tbody #tContent>
    <tr *ngFor="let item of items">
        // Your content here
    </tr>
</tbody>
</code>```

And in your ts file :

```<code>items: any[]
addTbody() {
    this.items.push('your new item here')
}
</code>```

So every time the user clicks you call addTbody and the items array will grow, appending your content to your dom.

You can add styles normally to your html via class or ngClass or ngStyle depending on your needs.

Body:
I'm making a template that if button is clicked then append elements that I want to.
I could append it exactly with following codes but I couldn't add style, angular-material2.
If you have any idea, leave your tip, please.

make-template.component.ts

@ViewChild('tContent') content: ElementRef;

  addTbody() {
    let content = document.getElementById('tContent');
    console.log(this.content.nativeElement);
    this.renderer.invokeElementMethod(this.content.nativeElement, 'insertAdjacentHTML', [`beforeend`,
  `

      <input type="file">

      <input type="file">

      <mat-input-container>
        <input matInput placeholder="image Info" type="text">
      </mat-input-container>

      <mat-input-container>
        <input matInput placeholder="image Info" type="text">
      </mat-input-container>

`]);

}

make-template.component.html

...

          // add here

<button type="button" mat-raised-button color="primary" (click)="addTbody()">click here</button>

Body:
I wouldn't use renderer and @Viewchild, and this is not an issue that is linked to your use of material2 but is a basic Angular pattern.

I personally would do this :

<tbody #tContent>
    <tr *ngFor="let item of items">
        // Your content here
    </tr>
</tbody>

And in your ts file :

items: any[]
addTbody() {
    this.items.push('your new item here')
}

So every time the user clicks you call addTbody and the items array will grow, appending your content to your dom.

You can add styles normally to your html via class or ngClass or ngStyle depending on your needs.


问:
I use jquery blinking functionality to parent div.but that effects chaild div.please help how to solve
I am using multiple div tags.for the parent div I used jquery blinking functionality.but that effecting my chaild div tags.
I want to blink only parent div.please help me.

Here is the screenshot

答: You can't do it like that. If you hide the parent all it's children will hide as well, and the same goes for opacity. You might be able to simulate it depending on what you want to do, but you will have to provide the html code.</p>


问:
Applescript Display Dialog User Input
I'm running an applescript program where I am asking for the user to type in their name.  If the user clicks "OK", then the name gets stored to the variable I want.  However, if the user clicks "Cancel", then the program just quits.  How do I set this up to either hide the "Cancel" button, so it's not an option to click, or to set up a loop so that if cancel is clicked, it just continues to ask the user for his/her name until it's entered?

Thanks in advance.

```<code>display dialog "Please Enter Your Name." default answer " " with title "Enter Name"
</code>```

答:
The way that you hide the cancel button is like this:

```<code>display dialog "Please Enter Your Name." default answer " " buttons {"ok"} with title "Enter Name"
set a to the text returned of the result
</code>```

But if you wanted the repeat then use this (I have made it so they have to enter something too instead of just pressing ok to end it:

```<code>repeat
 display dialog "Please Enter Your Name." default answer "" buttons {"ok", "cancel"} default button 1 with title "Enter Name"
set a to the text returned of the result
if the button returned of a is "ok" then
    if the text returned of a ≠ "" then
        exit repeat
    end if
 end if
end repeat
</code>```

Title: Applescript Display Dialog User Input

Body:
I'm running an applescript program where I am asking for the user to type in their name.  If the user clicks "OK", then the name gets stored to the variable I want.  However, if the user clicks "Cancel", then the program just quits.  How do I set this up to either hide the "Cancel" button, so it's not an option to click, or to set up a loop so that if cancel is clicked, it just continues to ask the user for his/her name until it's entered?

Thanks in advance.

display dialog "Please Enter Your Name." default answer " " with title "Enter Name"

Body:
The way that you hide the cancel button is like this:

display dialog "Please Enter Your Name." default answer " " buttons {"ok"} with title "Enter Name"
set a to the text returned of the result

But if you wanted the repeat then use this (I have made it so they have to enter something too instead of just pressing ok to end it:

repeat
 display dialog "Please Enter Your Name." default answer "" buttons {"ok", "cancel"} default button 1 with title "Enter Name"
set a to the text returned of the result
if the button returned of a is "ok" then
    if the text returned of a ≠ "" then
        exit repeat
    end if
 end if
end repeat


问:
How do I write and read data in txt file in the form of rows and columns?
How do I write and read data in txt file in the form of rows and columns?  Also, how do I store many files like this in a folder for a particular name? The idea is just like a Table for a particular person who has many rows and columns.</p>

答: You'll want to look into comma-separated value files.</p>


问:
Python 3.0 Calling a value from a class function to print
Trying to call the total hours from the class/function down to the instance of the class I created below. (hope i worded that correctly)

```<code>class Employee:
  def __init__(self):
    self.wage = 0
    self.hours = 0
    if self.hours > 40:
      self.ot = self.hours - 40                 #overtime hours
      self.earned_ot = self.wage * 1.5          #overtime wage rate
      self.ot_total = self.ot * self.earned_ot  #pay for overtime hours
      self.pay = self.wage * 40                 #standard hour wage
      self.total = self.pay + self.ot_total     #standard wage + ot hour wage
    else:
      self.total = self.wage * self.hours

alice = Employee()
alice.wage = 20
alice.hours = 40
#alice.total =

bob = Employee()
bob.wage = 15
bob.hours = 50
#bob.total =

print("Alice: \n Net pay: ${} \nBob: \n Net pay: ${}" .format(alice.total,
bob.total))
</code>```

Issue I'm having seems simple enough but I can't for the life of me figure it out. I commented out the alice.total and bob.total for now, but those are what I need to get the print to work correctly.

I feel like i'm forgetting something simple, but browsing back through my notes/texts I can't figure it out. Does anyone who sees the issue that I'm having, have a link to something that might explain this? I'm not looking for an outright answer, just a point in the right direction.

Thanks.

答:
You could either change your constructor

```<code>class Employee:
    def init(self, wage=0, hours=0):
    self.wage = wage
    self.hours = hours
</code>```

And instantiate your employee

```<code>alice = Employee(20, 40)
</code>```

The rest of your code can be left unchanged.
However I'll advise to use something like properties so you can change wage/hours without creating a new Employee and still get a accurate value

```<code>class Employee:
     def init(self):
         self._wage = 0
         self._hours = 0

     @property
     def wage(self):
         return self._wage

     @wage.setter
     def wage(self, value):
         self._wage = value

     @property
     def hours(self):
         return self._hours

     @hours.setter
     def hours(self, value):
         self._hours = value

     @property
     def total(self):
         if self.hours > 40:
             self.ot = self.hours - 40                 #overtime hours
             self.earned_ot = self.wage * 1.5          #overtime wage rate
             self.ot_total = self.ot * self.earned_ot  #pay for overtime hours
             self.pay = self.wage * 40                 #standard hour wage
             return self.pay + self.ot_total     #standard wage + ot hour wage
         else:
             return self.wage * self.hours
</code>```

Your code to instantiate and get/set wage/hours on an Employee can stay the same
More details on property : https://www.programiz.com/python-programming/property

Edit: Modified my answer based on comments made

Body:
Trying to call the total hours from the class/function down to the instance of the class I created below. (hope i worded that correctly)

class Employee:
  def __init__(self):
    self.wage = 0
    self.hours = 0
    if self.hours > 40:
      self.ot = self.hours - 40                 #overtime hours
      self.earned_ot = self.wage * 1.5          #overtime wage rate
      self.ot_total = self.ot * self.earned_ot  #pay for overtime hours
      self.pay = self.wage * 40                 #standard hour wage
      self.total = self.pay + self.ot_total     #standard wage + ot hour wage
    else:
      self.total = self.wage * self.hours

alice = Employee()
alice.wage = 20
alice.hours = 40
#alice.total =

bob = Employee()
bob.wage = 15
bob.hours = 50
#bob.total =

print("Alice: \n Net pay: ${} \nBob: \n Net pay: ${}" .format(alice.total,
bob.total))

Issue I'm having seems simple enough but I can't for the life of me figure it out. I commented out the alice.total and bob.total for now, but those are what I need to get the print to work correctly.

I feel like i'm forgetting something simple, but browsing back through my notes/texts I can't figure it out. Does anyone who sees the issue that I'm having, have a link to something that might explain this? I'm not looking for an outright answer, just a point in the right direction.

Thanks.

Body:
You could either change your constructor

class Employee:
    def init(self, wage=0, hours=0):
    self.wage = wage
    self.hours = hours

And instantiate your employee

alice = Employee(20, 40)

The rest of your code can be left unchanged.
However I'll advise to use something like properties so you can change wage/hours without creating a new Employee and still get a accurate value

class Employee:
     def init(self):
         self._wage = 0
         self._hours = 0

     @property
     def wage(self):
         return self._wage

     @wage.setter
     def wage(self, value):
         self._wage = value

     @property
     def hours(self):
         return self._hours

     @hours.setter
     def hours(self, value):
         self._hours = value

     @property
     def total(self):
         if self.hours > 40:
             self.ot = self.hours - 40                 #overtime hours
             self.earned_ot = self.wage * 1.5          #overtime wage rate
             self.ot_total = self.ot * self.earned_ot  #pay for overtime hours
             self.pay = self.wage * 40                 #standard hour wage
             return self.pay + self.ot_total     #standard wage + ot hour wage
         else:
             return self.wage * self.hours

Your code to instantiate and get/set wage/hours on an Employee can stay the same
More details on property : https://www.programiz.com/python-programming/property

Edit: Modified my answer based on comments made


问:
How to count the number of occurrences of an element in a List
I have an ArrayList, a Collection class of Java, as follows:

```<code>ArrayList<String> animals = new ArrayList<String>();
animals.add("bat");
animals.add("owl");
animals.add("bat");
animals.add("bat");
</code>```

As you can see, the animals ArrayList consists of 3 bat elements and one owl element. I was wondering if there is any API in the Collection framework that returns the number of bat occurrences or if there is another way to determine the number of occurrences.

I found that Google's Collection Multiset does have an API that returns the total number of occurrences of an element. But that is compatible only with JDK 1.5. Our product is currently in JDK 1.6, so I cannot use it.

答:
Simple Way to find the occurrence of string value in an array using Java 8 features.

```<code>public void checkDuplicateOccurance() {
        List<String> duplicateList = new ArrayList<String>();
        duplicateList.add("Cat");
        duplicateList.add("Dog");
        duplicateList.add("Cat");
        duplicateList.add("cow");
        duplicateList.add("Cow");
        duplicateList.add("Goat");
        Map<String, Long> couterMap = duplicateList.stream().collect(Collectors.groupingBy(e -> e.toString(),Collectors.counting()));
        System.out.println(couterMap);
    }
</code>```

Output : {Cat=2, Goat=1, Cow=1, cow=1, Dog=1}

You can notice "Cow" and cow are not considered as same string, in case you required it under same count, use .toLowerCase(). Please find the snippet below for the same.

```<code>Map<String, Long> couterMap = duplicateList.stream().collect(Collectors.groupingBy(e -> e.toString().toLowerCase(),Collectors.counting()));
</code>```

Output : {cat=2, cow=2, goat=1, dog=1}

OwnerDisplayName: MM

Body:
I have an ArrayList, a Collection class of Java, as follows:

ArrayList<String> animals = new ArrayList<String>();
animals.add("bat");
animals.add("owl");
animals.add("bat");
animals.add("bat");

As you can see, the animals ArrayList consists of 3 bat elements and one owl element. I was wondering if there is any API in the Collection framework that returns the number of bat occurrences or if there is another way to determine the number of occurrences.

I found that Google's Collection Multiset does have an API that returns the total number of occurrences of an element. But that is compatible only with JDK 1.5. Our product is currently in JDK 1.6, so I cannot use it.

LastEditorDisplayName: MM

Body:
Simple Way to find the occurrence of string value in an array using Java 8 features.

public void checkDuplicateOccurance() {
        List<String> duplicateList = new ArrayList<String>();
        duplicateList.add("Cat");
        duplicateList.add("Dog");
        duplicateList.add("Cat");
        duplicateList.add("cow");
        duplicateList.add("Cow");
        duplicateList.add("Goat");
        Map<String, Long> couterMap = duplicateList.stream().collect(Collectors.groupingBy(e -> e.toString(),Collectors.counting()));
        System.out.println(couterMap);
    }

Output : {Cat=2, Goat=1, Cow=1, cow=1, Dog=1}

You can notice "Cow" and cow are not considered as same string, in case you required it under same count, use .toLowerCase(). Please find the snippet below for the same.

Map<String, Long> couterMap = duplicateList.stream().collect(Collectors.groupingBy(e -> e.toString().toLowerCase(),Collectors.counting()));

Output : {cat=2, cow=2, goat=1, dog=1}


问:
Vertically aling form with bootstrap 4
I am using bootstrap 4 beta 2 and I am not able to center a form on the page...

This is the link with my code

https://codepen.io/davidrodri/pen/jawpeJ

```<code><div class="container">
  <div class="row justify-content-center h-100 align-middle">
    <div class="align-self-center">
        <form>
          <h2 class="text-center">Benvenuto</h2>
            <div class="form-group">
                <label for="username">Utente</label>
                <input type="text"  class="form-control"  id="username" >
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control"  id="password" >
            </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
        </form>
    </div>
  </div>
</div>
</code>```

答:
you need to set your html and body height to 100% first

```<code>html,
body {
    height: 100%;
}
</code>```

then set the container height 100%

```<code><div class="container h-100">
  <div class="row justify-content-center h-100 align-middle">
    <div class="align-self-center">
        <form>
          <h2 class="text-center">Benvenuto</h2>
            <div class="form-group">
                <label for="username">Utente</label>
                <input type="text"  class="form-control"  id="username" >
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control"  id="password" >
           </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
        </form>
    </div>
  </div>
</code>```

now align-self-center will get space to fit vertically.

Title: Vertically aling form with bootstrap 4

Body:
I am using bootstrap 4 beta 2 and I am not able to center a form on the page...

This is the link with my code

https://codepen.io/davidrodri/pen/jawpeJ

        <form>

Benvenuto

                Utente
                <input type="text"  class="form-control"  id="username" >

                Password
                <input type="password" class="form-control"  id="password" >

            <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
        </form>

Body:
you need to set your html and body height to 100% first

html,
body {
    height: 100%;
}

then set the container height 100%

<div class="container h-100">
  <div class="row justify-content-center h-100 align-middle">
    <div class="align-self-center">
        <form>
          <h2 class="text-center">Benvenuto</h2>
            <div class="form-group">
                <label for="username">Utente</label>
                <input type="text"  class="form-control"  id="username" >
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control"  id="password" >
           </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
        </form>
    </div>
  </div>

now align-self-center will get space to fit vertically.


问:
convert time stamp to time ago in php?
I know this question has been asked several times and I found so many tutorials, blog posts about converting timestamp to ago time in php..

I have tried countless codes and nothing seems to work for me...

I either get a blank page with no errors (i have error rerposting on my php page), or I get some strange numbers in my page..

so I thought someone here could shed a light on this for me..

Basically I am saving date like so:

```<code>$date = date('Y-m-d H:i:s');
</code>```

I simply save it in mysql database...

and I echo it like so:

```<code> echo $date;
</code>```

so now what I need to know is how I can convert the echo $date; to something like 1 minutes ago, 10 minutes ago, 1 hour ago etc etc every time the page closes and reopens?

I did try so many functions that I found on google and noon seem to do anything!

could someone please advise on this issue?

Thanks

EDIT:

I used this code as stated in the answer but I still get the $date echo-ed exactly the same way as its stored in the database which is this format: 2014-10-06 22:54:54

```<code>$date = date('Y-m-d H:i:s');

$time1 = new DateTime($date);
$now = new DateTime();
$interval = $time1->diff($now);

if ($interval->y) $date = $interval->y . ' years';
elseif ($interval->m) $date = $interval->m . ' months';
elseif ($interval->d) $date = $interval->d . ' days';
elseif ($interval->h) $date = $interval->h . ' hours';
elseif ($interval->i) $date = $interval->i . ' minutes';

echo $date;
</code>```

答:
Check this function intval() - http://php.net/manual/en/function.intval.php
The following code should help you out </p>

```<code>$seconds_ago = (time() - strtotime('2014-01-06 15:25:08'));

if ($seconds_ago >= 31536000) {
    echo "Seen " . intval($seconds_ago / 31536000) . " years ago";
} elseif ($seconds_ago >= 2419200) {
    echo "Seen " . intval($seconds_ago / 2419200) . " months ago";
} elseif ($seconds_ago >= 86400) {
    echo "Seen " . intval($seconds_ago / 86400) . " days ago";
} elseif ($seconds_ago >= 3600) {
    echo "Seen " . intval($seconds_ago / 3600) . " hours ago";
} elseif ($seconds_ago >= 60) {
    echo "Seen " . intval($seconds_ago / 60) . " minutes ago";
} else {
    echo "Seen less than a minute ago";
}
</code>```

Title: convert time stamp to time ago in php?

Body:
I know this question has been asked several times and I found so many tutorials, blog posts about converting timestamp to ago time in php..

I have tried countless codes and nothing seems to work for me...

I either get a blank page with no errors (i have error rerposting on my php page), or I get some strange numbers in my page..

so I thought someone here could shed a light on this for me..

Basically I am saving date like so:

$date = date('Y-m-d H:i:s');

I simply save it in mysql database...

and I echo it like so:

 echo $date;

so now what I need to know is how I can convert the echo $date; to something like 1 minutes ago, 10 minutes ago, 1 hour ago etc etc every time the page closes and reopens?

I did try so many functions that I found on google and noon seem to do anything!

could someone please advise on this issue?

Thanks

EDIT:

I used this code as stated in the answer but I still get the $date echo-ed exactly the same way as its stored in the database which is this format: 2014-10-06 22:54:54

$date = date('Y-m-d H:i:s');

$time1 = new DateTime($date);
$now = new DateTime();
$interval = $time1->diff($now);

if ($interval->y) $date = $interval->y . ' years';
elseif ($interval->m) $date = $interval->m . ' months';
elseif ($interval->d) $date = $interval->d . ' days';
elseif ($interval->h) $date = $interval->h . ' hours';
elseif ($interval->i) $date = $interval->i . ' minutes';

echo $date;

Body:
Check this function intval() - http://php.net/manual/en/function.intval.php
The following code should help you out

$seconds_ago = (time() - strtotime('2014-01-06 15:25:08'));

if ($seconds_ago >= 31536000) {
    echo "Seen " . intval($seconds_ago / 31536000) . " years ago";
} elseif ($seconds_ago >= 2419200) {
    echo "Seen " . intval($seconds_ago / 2419200) . " months ago";
} elseif ($seconds_ago >= 86400) {
    echo "Seen " . intval($seconds_ago / 86400) . " days ago";
} elseif ($seconds_ago >= 3600) {
    echo "Seen " . intval($seconds_ago / 3600) . " hours ago";
} elseif ($seconds_ago >= 60) {
    echo "Seen " . intval($seconds_ago / 60) . " minutes ago";
} else {
    echo "Seen less than a minute ago";
}


问:
ASP.NET Web API handled exception return wrong status code
I have project using ASP.NET Web API 2.0 and have a method in this API throwing an exception:

```<code>    public void TestMethod()
    {
        throw new Exception("Error40001");
    }
</code>```

When this exception is thrown I have made a handler to handle these sort of things:

```<code>public class APIExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        var rm = Language.Error.ResourceManager;
        string message = rm.GetString(context.Exception.Message);
        string detailed = "";
        try
        {
            detailed = rm.GetString(context.Exception.Message + "Detailed");
        }
        catch
        {
            if (String.IsNullOrEmpty(detailed))
            {
                detailed = message;
            }
        }
        HttpStatusCode code = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), context.Exception.Message.Replace("Error", "").Substring(0, 3));

        context.Result = new ResponseMessageResult(context.Request.CreateResponse(code,
            new ErrorInformation() { Message = message, DetailedMessage = detailed }));
    }
}

public class ErrorInformation
{
    public string Message { get; set; }
    public string DetailedMessage { get; set; }
}
</code>```

The problem I have is that when I receive this error back it is no longer the same status code that I set it to. The handler picks it up and creates a response message result with error code 400.

Here you see the result that is returned with status code 400

But when I receive the error in the browser the status code has changed

Here you see the status code that is returned

And the content

As can be seen in the last picture the content from the handled exception is at the start, but a default error message has been included and the status code has been overwritten.

The problem I am having is even if i remove the custom error messages from the webconfig the message is the same. Is this some default behavior that can be overridden? Am I missing something important?

答:
Instead of setting context.Result use following code

```<code>throw new HttpResponseException(context.Request.CreateResponse(code,
            new ErrorInformation() { Message = message, DetailedMessage = detailed }));
</code>```

Body:
I have project using ASP.NET Web API 2.0 and have a method in this API throwing an exception:

    public void TestMethod()
    {
        throw new Exception("Error40001");
    }

When this exception is thrown I have made a handler to handle these sort of things:

public class APIExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        var rm = Language.Error.ResourceManager;
        string message = rm.GetString(context.Exception.Message);
        string detailed = "";
        try
        {
            detailed = rm.GetString(context.Exception.Message + "Detailed");
        }
        catch
        {
            if (String.IsNullOrEmpty(detailed))
            {
                detailed = message;
            }
        }
        HttpStatusCode code = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), context.Exception.Message.Replace("Error", "").Substring(0, 3));

        context.Result = new ResponseMessageResult(context.Request.CreateResponse(code,
            new ErrorInformation() { Message = message, DetailedMessage = detailed }));
    }
}

public class ErrorInformation
{
    public string Message { get; set; }
    public string DetailedMessage { get; set; }
}

The problem I have is that when I receive this error back it is no longer the same status code that I set it to. The handler picks it up and creates a response message result with error code 400.

Here you see the result that is returned with status code 400

But when I receive the error in the browser the status code has changed

Here you see the status code that is returned

And the content

As can be seen in the last picture the content from the handled exception is at the start, but a default error message has been included and the status code has been overwritten.

The problem I am having is even if i remove the custom error messages from the webconfig the message is the same. Is this some default behavior that can be overridden? Am I missing something important?

Body:
Instead of setting context.Result use following code

throw new HttpResponseException(context.Request.CreateResponse(code,
            new ErrorInformation() { Message = message, DetailedMessage = detailed }));


问:
Dynamic Html.ActionLink parameters with Areas
I'm having a problem generating dynamic links to items from my code.

Code that I'm using:

```<code>Html.ActionLink("View Checklist Summary", "Details", "Product",
     new { Area = "Reporting" }, new { Item = 478})
</code>```

What I need:
URL -- localhost:58412/Reporting/Product/Details?Item=478

What I'm getting:
URL -- localhost:58412/Reporting/Product/Details

I've been working on this for way too long, and I can't seem to find any reason why the "Item=478" is not being added to the URL created by the ActionLink.

Any help would be much appreciated.

答:
Try this:

```<code>Html.ActionLink("View Checklist Summary", "Details", "Product", new { Area = "Reporting", Item = 478 }, new { })
</code>```

The Area and the Item must be specified in the routevalues object. The last empty object, if I recall, is the HtmlAttributes object.

Body:
I'm having a problem generating dynamic links to items from my code.

Code that I'm using:

Html.ActionLink("View Checklist Summary", "Details", "Product",
     new { Area = "Reporting" }, new { Item = 478})

What I need:
URL -- localhost:58412/Reporting/Product/Details?Item=478

What I'm getting:
URL -- localhost:58412/Reporting/Product/Details

I've been working on this for way too long, and I can't seem to find any reason why the "Item=478" is not being added to the URL created by the ActionLink.

Any help would be much appreciated.

Body:
Try this:

Html.ActionLink("View Checklist Summary", "Details", "Product", new { Area = "Reporting", Item = 478 }, new { })

The Area and the Item must be specified in the routevalues object. The last empty object, if I recall, is the HtmlAttributes object.


问:
Statement-level trigger in Oracle
I can't fully understand how a statement-level trigger works. It executes once for each transaction right? If I have this AFTER INSERT trigger and what it does inside is that it updates one specific column if it meets the condition (ex for column status, UPDATE table_name SET STATUS = "Single" WHERE COLUMN is null).

Are the newly inserted data only the ones get to be affected? Or every data in the table that has this null value in column status. I'll be glad hearing your knowledge about this.

答:
A statement level trigger will fire once after the triggering statement has run, unlike a row level trigger which fires for each affected row.

After statement triggers are generally used to do processing of the set of data - e.g. logging into a table, or running some post-statement processing (usually a procedure).

If you're wanting to update a value in every affected row, then I would advise using a before row level trigger. The update statement in your question would affect all rows where the COLUMN column is null.

Whether a trigger is actually the right thing to use is debatable. However, I would recommend you look at the documentation and also this Oracle-base article to gain a better understanding of how triggers work and when you might use them.

Title: Statement-level trigger in Oracle


问:
Run kafka connect distributed mode on many nodes
I'm resiliency testing a kafka connector and I'd like to kill off a worker while it's running, thus killing the connector instance. The easiest way is probably going to be to force distributed mode to run over more than one node, then just kill the worker process on that node (right?). How can I make Kafka connect spawn workers on more than just the node it's started on? Is this something which is defined in worker config?</p>

答:
So in the end what I did was:

Copied all the jars I needed for Kafka Connect distributed mode to the two nodes I wanted to run it on (in HDP 2.5.3 you only get those jars on one node).

On both nodes, I ran the start script with properties file pointing to my jars.

Using the REST interface I posted my connector with a task, and I could see that one worker had the connector instance and another had its task.

I killed off the task worker node (using ps -ef | grep connect), and saw that it had respawned on the remaining node.

I reset the test and tried killing off the connector instance node, and to my amazement, the connector instance restarted on the other node.

In summary of my resiliency testing, Kafka Connect seems to be like playing whack-a-mole; you can kill off tasks or connectors wherever they are, and they will just respawn somewhere else.


问:
How to center a div (CSS loader)
JS Fiddle: fiddle and here is the code:

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader"></div></code>```

How do I centre it horizontally & vertically?

I tried:

```<code>position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
</code>```

But transform:translate(-50%,-50%); do not work

答:
You can make it position:absolute;

and give it:

```<code>top:0;
left:0;
right:0;
bottom:0;
</code>```

to make it both vertically and horizontally aligned into the middle.

body {
  overflow:hidden;
}

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
  margin:auto;
  top:0;
  left:0;
  bottom:0;
  right:0;
  position:absolute;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader"></div></code>```

Title: How to center a div (CSS loader)

Body:
JS Fiddle: fiddle and here is the code:

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

How do I centre it horizontally & vertically?

I tried:

position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);

But transform:translate(-50%,-50%); do not work

Body:
You can make it position:absolute;

and give it:

top:0;
left:0;
right:0;
bottom:0;

to make it both vertically and horizontally aligned into the middle.

body {
  overflow:hidden;
}

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
  margin:auto;
  top:0;
  left:0;
  bottom:0;
  right:0;
  position:absolute;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

<div class="loader"></div>


问:
Previous java files are being replaced by the New java file in eclipse search
I am using eclipse Kepler and Mars. I am facing a problem in eclipse like, if I search a particular file (java, jsp, or xml etc.) by using ctrl + H or File Search, a list of files related to the search is fetched in the Search tab of eclipse. When I clicked one of files to open it and then clicked another file, instead of opening 2 separate files, the previous file is getting replaced by the new one.

Then I have to copy the name of the previous file and open it again by using Open Resource or ctrl + shift + R. This problem is appearing all the time in the two eclipse IDE.

I don't know if anyone ever faced this problem, or this is being the normal nature of eclipse IDE. Please suggest an idea to overcome this issue. Is the version of the eclipse responsible for this problem?

My system's jdk version is 1.8. I also tried with jdk-1.6 environment.

答:
Open the Preferences and go to 'General > Search'.

Deselect the 'Reuse editors to show matches' option.


问:
How to enable/ disable javascript based on environment?
I am trying to put in scripts for google analytics in my code. But I want it to run only if the environment is production and not in dev or qa. This javascript runs at page load itself and I am confused how to make it run conditionally. My app is an asp.net app.

Javascript is always confusing to me. There are many other javascripts in the page and I just need to disable this one. Had it been a .net code/function I would check for the environment and conditionally run the function. But I am confused about how to accomplish this type of functionality with javascript

答: Look at the location object: http://www.w3schools.com/jsref/obj_location.asp.  You can put in a script that runs on page load: if (location.host == "yourproductionhostname"){yourfunction();}


问:
I want to Print each sentense in Next line in Center as Peom I have tried /n ,/r/n but I failed
```<code><center><p id="demo" style="color:black;"></p></center>

<script>

window.onload = function() {
  typeWriter();
};
var i =0;
var txt = "Would it be ok if I wrote you a rhyme? would it be ok if I opened my heart? Would it be ok if I took on the part Of being your man and showed you a view, One that only a real man could do? Would it be ok if I could make you smile? Would it be alright to look in your eyes? Would it be alright to never tell lies? Would it be alright to find a way? Would it be alright to long for the day To pull you close and whisper in your ear And tell you our feelings are nothing to fear? Would it be ok if I took some of your time? Would it be ok if I wrote you a rhyme? To tell you there is nothing I would rather do Than spend my whole life loving only you... ";
var txt1= '';
var speed = 100;
function typeWriter() {
  if (i < txt.length) {
    document.getElementById("demo").innerHTML += txt.charAt(i);
document.getElementById("demo").innerHTML += txt1.charAt(i);

    i++;
      setTimeout(typeWriter, speed);

  }

}
</script>
</code>```

I want to Print every sentence in next line as a Poem...! But I can't Do it Please if There is Anybody who is willing to help .! I will Appreciate Him/Her
Thanks In Advance

答:
Use your own flag for example char "#" .
I use simple check for char at index and use tag br/ .
Better solution use char "?" for new line . See in code snippet example2 .

```
</div>
</div>
</p>

<p>Example 2 : </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><center><p id="demo" style="color:black;"></p></center>

<script>

window.onload = function() {
  typeWriter();
};
var i =0;
var txt = "Would it be ok if I wrote you a rhyme? would it be ok if I opened my heart?  Would it be ok if I took on the part Of being your man and showed you a view, One that only a real man could do? Would it be ok if I could make you smile? Would it be alright to look in your eyes? Would it be alright to never tell lies?Would it be alright to find a way? Would it be alright to long for the day To pull you close and whisper in your ear And tell you our feelings are nothing to fear? Would it be ok if I took some of your time? Would it be ok if I wrote you a rhyme? To tell you there is nothing I would rather do Than spend my whole life loving only you... ";
var txt1= '';
var speed = 100;
function typeWriter() {
  if (i < txt.length) {

    if (txt.charAt(i) == "?"){

    document.getElementById("demo").innerHTML += txt.charAt(i);
    document.getElementById("demo").innerHTML += "<br/>";

    }
    else {
    document.getElementById("demo").innerHTML += txt.charAt(i);
     }
    document.getElementById("demo").innerHTML += txt1.charAt(i);

    i++;
      setTimeout(typeWriter, speed);

  }

}
</script></code>```

Example with bold ( little parser ) :
It is little complicated . We need dynamic creation element with append method also one FLAG .

```

Body:
Use your own flag for example char "#" .
I use simple check for char at index and use tag br/ .
Better solution use char "?" for new line . See in code snippet example2 .

<center><p id="demo" style="color:black;"></p></center>

<script>

window.onload = function() {
  typeWriter();
};
var i =0;
var txt = "Would it be ok if I wrote you a rhyme?# would it be ok if I opened my heart? # Would it be ok if I took on the part Of being your man and showed you a view, One that only a real man could do?# Would it be ok if I could make you smile?# Would it be alright to look in your eyes? Would it be alright to never tell lies?# Would it be alright to find a way?# Would it be alright to long for the day To pull you close and whisper in your ear And tell you our feelings are nothing to fear? Would it be ok if I took some of your time?# Would it be ok if I wrote you a rhyme?# To tell you there is nothing I would rather do Than spend my whole life loving only you... ";
var txt1= '';
var speed = 100;
function typeWriter() {
  if (i < txt.length) {

    if (txt.charAt(i) == "#"){
    document.getElementById("demo").innerHTML += "<br/>";
    }
    else {
    document.getElementById("demo").innerHTML += txt.charAt(i);
     }
    document.getElementById("demo").innerHTML += txt1.charAt(i);

    i++;
      setTimeout(typeWriter, speed);

  }

}
</script>

Example 2 :

<center><p id="demo" style="color:black;"></p></center>

<script>

window.onload = function() {
  typeWriter();
};
var i =0;
var txt = "Would it be ok if I wrote you a rhyme? would it be ok if I opened my heart?  Would it be ok if I took on the part Of being your man and showed you a view, One that only a real man could do? Would it be ok if I could make you smile? Would it be alright to look in your eyes? Would it be alright to never tell lies?Would it be alright to find a way? Would it be alright to long for the day To pull you close and whisper in your ear And tell you our feelings are nothing to fear? Would it be ok if I took some of your time? Would it be ok if I wrote you a rhyme? To tell you there is nothing I would rather do Than spend my whole life loving only you... ";
var txt1= '';
var speed = 100;
function typeWriter() {
  if (i < txt.length) {

    if (txt.charAt(i) == "?"){

    document.getElementById("demo").innerHTML += txt.charAt(i);
    document.getElementById("demo").innerHTML += "<br/>";

    }
    else {
    document.getElementById("demo").innerHTML += txt.charAt(i);
     }
    document.getElementById("demo").innerHTML += txt1.charAt(i);

    i++;
      setTimeout(typeWriter, speed);

  }

}
</script>

Example with bold ( little parser ) :
It is little complicated . We need dynamic creation element with append method also one FLAG .

<center><p id="demo" style="color:black;"></p></center>

<script>

window.onload = function() {
  typeWriter();
};
var i =0;
var txt = "Would it be ok if I wrote you a #rhyme#? would it be ok if I opened my #heart#?  Would it be ok if I took on the part Of being your man and showed you a view, One that only a real man could do? Would it be ok if I could make you smile? Would it be alright to look in your eyes? Would it be alright to never tell lies?Would it be alright to find a way? Would it be alright to long for the day To pull you close and whisper in your ear And tell you our feelings are nothing to fear? Would it be ok if I took some of your time? Would it be ok if I wrote you a rhyme? To tell you there is nothing I would rather do Than spend my whole life loving only you... ";
var txt1= '';
var speed = 100;

var BOLD_ELE = null;
var isBold = false;

function typeWriter() {
  if (i < txt.length) {

     if (isBold == true ){

     var BOLD_ELE = document.createElement('B');
     document.getElementById("demo").appendChild(BOLD_ELE);

     }

    if (txt.charAt(i) == "?"){

    document.getElementById("demo").innerHTML += txt.charAt(i);
    document.getElementById("demo").innerHTML += "<br/>";

    }
    else if (txt.charAt(i) == "#"){
       if (isBold == false) {
        isBold = true
       }
       else {
        isBold = false
       }

    }
    else {

    if (isBold == false){
     document.getElementById("demo").innerHTML += txt.charAt(i);
    }
    else {
     BOLD_ELE.innerHTML += txt.charAt(i);
    }

    }

    document.getElementById("demo").innerHTML += txt1.charAt(i);

    i++;
      setTimeout(typeWriter, speed);

  }

}
</script>


问:
read html from c#, '' is not a supported encoding name error
i'm triying to read a html from c# like this:

```<code>      public string getHTMLIcon() {
            string url = @"http://ddragon.leagueoflegends.com/cdn/7.5.1/img/profileicon/1258.png";
            string data = string.Empty;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream receiveStream = response.GetResponseStream();
                StreamReader readStream = null;

                if (response.CharacterSet == null)
                {
                    readStream = new StreamReader(receiveStream);
                }
                else
                {
                    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                }

                data = readStream.ReadToEnd();

                response.Close();
                readStream.Close();
            }
            return data;
        }
</code>```

But is getting me the next error: '' is not a supported encoding name.

If i try get the html without the encoding i get the next: ‰PNG  IHDR€€L\öœgAMA± ...

答:
Here you have my methods for downloading an image:</p>

```<code>        public static Stream DownloadImage(string url, string referer)
        {
            try
            {
                var u = new Uri(url);
                HttpWebRequest request;

                request = (HttpWebRequest)WebRequest.Create(u);

                request.Referer = referer;
                request.UserAgent = "userAgent";

                var response = (HttpWebResponse)request.GetResponse();
                if (response != null)
                {
                    return response.GetResponseStream();
                }
            }
            catch (WebException wex)
            {
                Logging.Write($"WEB ERROR {url} \n" + wex.Message);
                throw;
            }

            return null;
        }

    public static void DownloadImage(string url, string referer, string localFilePath)
    {
        Stream stream = DownloadImage(url, referer);

        using(FileStream file = File.Create(localFilePath))
        {
            stream.CopyTo(file);
        }
    }
</code>```

Body:
i'm triying to read a html from c# like this:

      public string getHTMLIcon() {
            string url = @"http://ddragon.leagueoflegends.com/cdn/7.5.1/img/profileicon/1258.png";
            string data = string.Empty;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream receiveStream = response.GetResponseStream();
                StreamReader readStream = null;

                if (response.CharacterSet == null)
                {
                    readStream = new StreamReader(receiveStream);
                }
                else
                {
                    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                }

                data = readStream.ReadToEnd();

                response.Close();
                readStream.Close();
            }
            return data;
        }

But is getting me the next error: '' is not a supported encoding name.

If i try get the html without the encoding i get the next: ‰PNG  IHDR€€L\öœgAMA± ...

Body:
Here you have my methods for downloading an image:

        public static Stream DownloadImage(string url, string referer)
        {
            try
            {
                var u = new Uri(url);
                HttpWebRequest request;

                request = (HttpWebRequest)WebRequest.Create(u);

                request.Referer = referer;
                request.UserAgent = "userAgent";

                var response = (HttpWebResponse)request.GetResponse();
                if (response != null)
                {
                    return response.GetResponseStream();
                }
            }
            catch (WebException wex)
            {
                Logging.Write($"WEB ERROR {url} \n" + wex.Message);
                throw;
            }

            return null;
        }

    public static void DownloadImage(string url, string referer, string localFilePath)
    {
        Stream stream = DownloadImage(url, referer);

        using(FileStream file = File.Create(localFilePath))
        {
            stream.CopyTo(file);
        }
    }


问:
ActivityCompat.requestPermissions not showing dialog box
```<code>if (ContextCompat.checkSelfPermission(RegisterActivity.this,      Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE_PERMISSION);
</code>```

i'm trying to use this function on nexus 5 api 23 and its just not showing me the dialog box like its supposed to do, it's just not doing anything.
what could cause the problem? (this code is in the java activity)
i tried changing my minimum api to 23 and use the requestPermissions() without the ActivityCompat but still not working.

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "com.example.idanayzen.photomap"
    minSdkVersion 23
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.android.support:design:23.1.1'
}
</code>```

and the Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.idanayzen.photomap">

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_SMS" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps" />
    <activity android:name=".RegisterActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".WrongPhoneNum"></activity>
</application>

</manifest>
</code>```

答:
I had a need to request permission for WRITE_EXTERNAL_STORAGE but was not getting a pop-up despite trying all of the different suggestions mentioned.

The culprit in the end was HockeyApp. It uses manifest merging to include its own permission for WRITE_EXTERNAL_STORAGE except it applies a max sdk version onto it.

The way to get around this problem is to include it in your Manifest file but with a replace against it, to override the HockeyApp's version and success!

4.7.2 Other dependencies requesting the external storage permission (SDK version 5.0.0 and later) To be ready for Android O,
  HockeySDK-Android 5.0.0 and later limit the WRITE_EXTERNAL_STORAGE
  permission with the maxSdkVersion filter. In some use cases, e.g.
  where an app contains a dependency that requires this permission,
  maxSdkVersion makes it impossible for those dependencies to grant or
  request the permission. The solution for those cases is as follows:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="replace"/>
</code>```

It will cause that other attributes from low
  priority manifests will be replaced instead of being merged.

https://support.hockeyapp.net/kb/client-integration-android/hockeyapp-for-android-sdk#permissions-advanced

Body:
if (ContextCompat.checkSelfPermission(RegisterActivity.this,      Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE_PERMISSION);

i'm trying to use this function on nexus 5 api 23 and its just not showing me the dialog box like its supposed to do, it's just not doing anything.
what could cause the problem? (this code is in the java activity)
i tried changing my minimum api to 23 and use the requestPermissions() without the ActivityCompat but still not working.

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "com.example.idanayzen.photomap"
    minSdkVersion 23
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.android.support:design:23.1.1'
}

and the Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.idanayzen.photomap">

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_SMS" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps" />
    <activity android:name=".RegisterActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".WrongPhoneNum"></activity>
</application>

</manifest>

Body:
I had a need to request permission for WRITE_EXTERNAL_STORAGE but was not getting a pop-up despite trying all of the different suggestions mentioned.

The culprit in the end was HockeyApp. It uses manifest merging to include its own permission for WRITE_EXTERNAL_STORAGE except it applies a max sdk version onto it.

The way to get around this problem is to include it in your Manifest file but with a replace against it, to override the HockeyApp's version and success!

4.7.2 Other dependencies requesting the external storage permission (SDK version 5.0.0 and later) To be ready for Android O,
  HockeySDK-Android 5.0.0 and later limit the WRITE_EXTERNAL_STORAGE
  permission with the maxSdkVersion filter. In some use cases, e.g.
  where an app contains a dependency that requires this permission,
  maxSdkVersion makes it impossible for those dependencies to grant or
  request the permission. The solution for those cases is as follows:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="replace"/>

It will cause that other attributes from low
  priority manifests will be replaced instead of being merged.

https://support.hockeyapp.net/kb/client-integration-android/hockeyapp-for-android-sdk#permissions-advanced


问:
Using Grafana templates for Prometheus data sources
Grafana 4.3.1, Prometheus 1.8.0

We have 3 Prometheus data sources which represent different data centers.  I have created a dashboard in Prometheus using the "Mixed" data source option to allow a view across the data centers by default.  I would like to include a "template" which essentially provides a drop down that will allow the selection of data source 1..3 or ALL.  Is there anyway to include something like an "IF" statement in the promql which will essentially hide certain panel metrics if this drop down is set to certain values?

Grafana repeat row/panel - I realize this is an option but it would introduce new panels and rows for each data center(data source) selected.  I am trying to find out if I can keep the panels static and update the contents based on the selected value.

OBJECTIVE - Have a dashboard which can either view across all data sources or isolate to 1 with a simple selection of a drop down (Template).

答:
Instead of using "Query" option in templating, you can go for "datasource" which will give you all the datasources in the drop down list.

But for this, your datasources should already be created.

I have 4 datasources and I used the same kind of templating.


问:
Modifying the javascript array and pushing it into array is copying to every element in array
I am not able to understand why it is copying the modified value to every element in the javascript array. Can somebody please explain the concept why?

```<code>var obj = {x:12};

var arr =[];

for(var i=0;i<5;i++){
    obj["x"] = i;
    arr.push(obj);
    println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));
</code>```

Output of the above code returns -

```<code>Inside -> [{"x":0}]
Inside -> [{"x":1},{"x":1}]
Inside -> [{"x":2},{"x":2},{"x":2}]
Inside -> [{"x":3},{"x":3},{"x":3},{"x":3}]
Inside -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Output -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]
</code>```

答:
instead of

```<code>obj.x = i;
arr.push(obj);
</code>```

do

```<code>var objCopy = Object.assign({}, obj, {x: i})
arr.push(objCopy);
</code>```

Body:
I am not able to understand why it is copying the modified value to every element in the javascript array. Can somebody please explain the concept why?

var obj = {x:12};

var arr =[];

for(var i=0;i<5;i++){
    obj["x"] = i;
    arr.push(obj);
    println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));

Output of the above code returns -

Inside -> [{"x":0}]
Inside -> [{"x":1},{"x":1}]
Inside -> [{"x":2},{"x":2},{"x":2}]
Inside -> [{"x":3},{"x":3},{"x":3},{"x":3}]
Inside -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Output -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Body:
instead of

obj.x = i;
arr.push(obj);

do

var objCopy = Object.assign({}, obj, {x: i})
arr.push(objCopy);


问:
Error installing tizen studio on windows 10
No matter which of the three tizen studio 2.0 installers I try they all don't work as they won't accept any path. The CLI installer gives the most detailed description:

** The directory you specify is not allowed to install the Tizen Studio. Some tools of the Tizen Studio will not properly work in the directory with administrator privilege or read-only access rights for your account.=> path

I have tried starting the installer with admin rights and owning the destination folders. Additionally, I switched from JDK 9 to 8.

Still, there seems no way to get the installer running. Any ideas what the reason could be? Thanks!

答:
I managed to install tizen studio and the SDK using the %appdata% path.
If anyone else has the problem, try e.g.

C:\Users\YourName\AppData\Roaming\Samsung\tizen-studio

This is definitely a flaw Samsung should take care of!


问:
Two controllers for one shared view in Ruby on Rails
I have two controllers for two respective models, by example, photos and categories. index and show methods are very similar in each controller, and the views are identical. What is the best method for share the view by the two models?

I've though two options:

Use a helper. In the helper will put the code for the view, and will call the helper from each view (photos/views and categories/views)

Use a partial in each views. I think it's a more clean solution, but I see huge DRY's in my mind when going to code this solution.

So, I have two controllers from two models, each one at and exposes a @photo object (photos controller with all the photos, and categories controller with just the selected categorie's photos) and I need one view to show both.

I'm looking for an elegant solution for this, complaining REST and DRY principes. Any idea?

Thanks in advance.

答: I'd use an helper because they are shared among views.  For the HTML part, I'd use partials so it would be a mix of both ways.</p>

OwnerDisplayName: ARemesal

LastEditorDisplayName: Beds

OwnerDisplayName: Keltia

LastEditorDisplayName: Keltia


问:
How to make a variable private to a trait?

I'd like to reuse a functionality several times in a single class. This functionality relies on a private variable:

trait Address {
    private $address;

    public function getAddress() {
        return $this->address;
    }

    public function setAddress($address) {
        $this->address = $address;
    }
}
```

<p>The only way I've found to use the trait twice, is the following:</p>

<pre class="lang-php prettyprint-override"><code>class User  {
    use Address {
        getAddress as getHomeAddress;
        setAddress as setHomeAddress;

        getAddress as getWorkAddress;
        setAddress as setWorkAddress;
    }
}
</code>```

The problem is, by doing this, the private variable $address is shared across the different methods, and the code will not work as expected:

$user = new User();
$user->setHomeAddress('21 Jump Street');
echo $user->getWorkAddress(); // 21 Jump Street
```

Is there a solution to really use the trait twice, while not sharing its private variables?

答:
i may be a little late for the party, but the behavior you are trying to create is not something that should be covered by a trait, but by simple object composition.</p>

```<code><?php
class Adddress {
    private $street;
    private $number;
    public function __construct(string $street, ?string $number) {}
    public function street() : string {}
    public function number() : string {}
}
class User {
    private $homeAddress;
    private $workAddress;
    public function getHomeAddress() : Address {}
    public function setHomeAddress(Address $homeAddress) : self {}
    public function getWorkAddress() : Address {}
    public function setWorkAddress(Address $workAddress) : self {}
}
</code>```

Body:
I'd like to reuse a functionality several times in a single class. This functionality relies on a private variable:

trait Address {
    private $address;

    public function getAddress() {
        return $this->address;
    }

    public function setAddress($address) {
        $this->address = $address;
    }
}

The only way I've found to use the trait twice, is the following:

class User  {
    use Address {
        getAddress as getHomeAddress;
        setAddress as setHomeAddress;

        getAddress as getWorkAddress;
        setAddress as setWorkAddress;
    }
}

The problem is, by doing this, the private variable $address is shared across the different methods, and the code will not work as expected:

$user = new User();
$user->setHomeAddress('21 Jump Street');
echo $user->getWorkAddress(); // 21 Jump Street

Is there a solution to really use the trait twice, while not sharing its private variables?

Body:
i may be a little late for the party, but the behavior you are trying to create is not something that should be covered by a trait, but by simple object composition.

<?php
class Adddress {
    private $street;
    private $number;
    public function __construct(string $street, ?string $number) {}
    public function street() : string {}
    public function number() : string {}
}
class User {
    private $homeAddress;
    private $workAddress;
    public function getHomeAddress() : Address {}
    public function setHomeAddress(Address $homeAddress) : self {}
    public function getWorkAddress() : Address {}
    public function setWorkAddress(Address $workAddress) : self {}
}