问:
Page refreshes even after e.preventDefault() jquery
```<code>$('#btn-add-skills').on('click', function(e) {
        e.preventDefault();
        // function call goes here
    });
</code>```

Even after calling e.preventDefault()the page still gets refreshed on clicking the button.
Any suggestion what I might have missed?

Below is the JADE code for above on click function.

```<code>.modal-add-skills.modal.fade
  .modal-dialog
    .modal-content
      .modal-header
        h4(style='color: black !important;')
      .modal-body
        form#addSkills
          .form-group
            label.col-form-label(for='Skill') Skill
            input#skill_input.form-control.required(type='text', name='Skill', placeholder='Start typing to select skill', style="width: 300px;")
          .modal-footer
            button#add-skill-data.btn.btn-primary(type='submit') Add
</code>```

答:
You may need to also add e.stopPropagation(); to stop the event from bubbling up the DOM tree.

```<code>$(document).ready(function(){
    $('#btn-add-skills').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();

        alert("Stopped Redirecting");

        // function call goes here

        return false;
  });
});
</code>```

Demo

Body:
$('#btn-add-skills').on('click', function(e) {
        e.preventDefault();
        // function call goes here
    });

Even after calling e.preventDefault()the page still gets refreshed on clicking the button.
Any suggestion what I might have missed?

Below is the JADE code for above on click function.

.modal-add-skills.modal.fade
  .modal-dialog
    .modal-content
      .modal-header
        h4(style='color: black !important;')
      .modal-body
        form#addSkills
          .form-group
            label.col-form-label(for='Skill') Skill
            input#skill_input.form-control.required(type='text', name='Skill', placeholder='Start typing to select skill', style="width: 300px;")
          .modal-footer
            button#add-skill-data.btn.btn-primary(type='submit') Add

Body:
You may need to also add e.stopPropagation(); to stop the event from bubbling up the DOM tree.

$(document).ready(function(){
    $('#btn-add-skills').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();

        alert("Stopped Redirecting");

        // function call goes here

        return false;
  });
});

Demo


来源: stackexchange

问:
Logic behind selecting number of peers for an organization in hyperledger

Hi I am looking to find what is the logic behind selecting number of peers in Hyperledger fabric for an organization

答:
The more peers you have, the more transaction simulations you can do per second.

Since in fabric not all peers run the smart contracts but only the minimum number needed to satisfy the endorsement policy, if you have i.e 10 peers but you only need 1 of them to sign an endorsement, that means you can endorse 10 transactions "in the same time" as 1 transaction and this would increase the throughput of the system, provided that the validation and commit can withhold such a rate of transactions.

ContentLicense: CC BY-SA 3.0


问:
how to add removefile option in dropzone plugin?
I have used dropzone.js (http://www.dropzonejs.com/). I am trying to add delete button to delete the image. but i am getting javascript undefined error</p>

```<code> <script>
  Dropzone.options.myDropzone = {
init: function() {
 addRemoveLinks: true,
thisDropzone = this;
 $.get('photo-add.php', function(data) {
 $.each(data, function(key,value){
var mockFile = { name: value.name, size: value.size };
  thisDropzone.options.addedfile.call(thisDropzone, mockFile);
 thisDropzone.options.thumbnail.call(thisDropzone, mockFile,      "upload/"+value.name);

});
 });

 this.on("removedfile", function(file) {
alert(file.name);
console.log(file);
     // Create the remove button
  var removeButton = Dropzone.createElement("<button>Remove file</button>");

 /    / Capture the Dropzone instance as closure.
  var _this = this;

 // Listen to the click event
 removeButton.addEventListener();

   // Add the button to the file preview element.
  file.previewElement.appendChild(removeButton);
    });
  }
  };
     </script>
</code>```

答:
"Every your events" Like : success - error - sending - removedfile or addedfile and etc.

http://www.dropzonejs.com/#event-list

```<code>init : function () {
    self.on('Every your events', function (file, response) {
        this.removeFile(file);
    }
}
</code>```

for remove file from out of this function can do this :

```<code>Dropzone.forElement("#YourDropBoxId").removeAllFiles(true);
</code>```

Body:
"Every your events" Like : success - error - sending - removedfile or addedfile and etc.

http://www.dropzonejs.com/#event-list

init : function () {
    self.on('Every your events', function (file, response) {
        this.removeFile(file);
    }
}

for remove file from out of this function can do this :

Dropzone.forElement("#YourDropBoxId").removeAllFiles(true);


问:
jquery : why these two lines' execution are executed at the same time?
This is my code snippet

```<code>$(function() {

  $(".red-box").fadeOut(2000); //1
  $(".green-box").fadeOut(2000); //2
  $(".red-box").fadeIn(2000);//3

});
</code>```

index.html is shown below

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <script src="js/jquery-3.2.1.min.js"></script>
  <script src="js/script.js"></script>
  <link rel="stylesheet" href="css/style.css">
  <title>TProject Structure</title>
</head>
<body>
  <div id="content">
    <h1>Project Structure</h1>

    <div class="red-box">Red</div>
    <div class="green-box">Green</div>
    <div class="blue-box">Blue</div>
    <div class="clear"></div>

    <h2>Hi, I'm the Base Project!</h2>
    <p>Add elements here as you like to try out jQuery. This is your playground to test out anything that comes into your mind.</p>
    <p><strong>OR:</strong> Copy this project structure into a new directory first to create separate playgrounds for animations, manipulations, event handlers etc.</p>
  </div>
</body>
</html>
</code>```

When I open the HTML page I did notice that

a) First both the red and green box fades out together.
b) Then the red box fades back in.

My Qs

a) How does jQuery know that line 1 and line 2 are to be executed together followed by line 3 ?

If the execution is "line by line" then jQuery should have executed line 1 (i.e wait for 2s before fading out) AND AFTER THAT only should have executed line 2 and so on...

Can someone explain as to why line1 and line2's execution are clubbed together by jQuery ?

答: Use call-backs. This should explain: http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/</p>

Body:
This is my code snippet

$(function() {

  $(".red-box").fadeOut(2000); //1
  $(".green-box").fadeOut(2000); //2
  $(".red-box").fadeIn(2000);//3

});

index.html is shown below

<!DOCTYPE html>

  <meta charset="UTF-8">

  <link rel="stylesheet" href="css/style.css">
  <title>TProject Structure</title>

Project Structure

Red

Green

Blue

Hi, I'm the Base Project!

Add elements here as you like to try out jQuery. This is your playground to test out anything that comes into your mind.

OR: Copy this project structure into a new directory first to create separate playgrounds for animations, manipulations, event handlers etc.

When I open the HTML page I did notice that

a) First both the red and green box fades out together.
b) Then the red box fades back in.

My Qs

a) How does jQuery know that line 1 and line 2 are to be executed together followed by line 3 ?

If the execution is "line by line" then jQuery should have executed line 1 (i.e wait for 2s before fading out) AND AFTER THAT only should have executed line 2 and so on...

Can someone explain as to why line1 and line2's execution are clubbed together by jQuery ?


问:
What generic collections in C# are IXmlSerializable?
Are any of the .NET generic collections marked as IXmlSerializable? I've tried List<T> and Collection<T> but neither work out of the box.

Before I roll my own collection<T>, list<T>, or dictionary<T> class, I thought I'd check to see whether Microsoft had included something that does this already. It seems like basic functionality.

EDIT: By "rolling my own" I mean creating a class that inherits from a generic collection class and also implements IXmlSerializable. Here's one example: http://www.codeproject.com/KB/XML/IXmlSerializable.aspx. And here's another example: http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx.

I'm using the DataContractSerializer within a method whose signature looks like this:

```<code>public static Stream GetXmlStream(IXmlSerializable item)
</code>```

The problem is that while there are many classes in the .NET framework that are serializable, not all of them have explicitly implement the IXmlSerializable interface.

答:
As far as I know, there aren't any. You could take a look at the attached link, though. I think you'll find it useful.

Serialize and deserialize objects as Xml using generic types in C# 2.0

OwnerDisplayName: dthrasher

ContentLicense: CC BY-SA 2.5

Body:
Are any of the .NET generic collections marked as IXmlSerializable? I've tried List<T> and Collection<T> but neither work out of the box.

Before I roll my own collection<T>, list<T>, or dictionary<T> class, I thought I'd check to see whether Microsoft had included something that does this already. It seems like basic functionality.

EDIT: By "rolling my own" I mean creating a class that inherits from a generic collection class and also implements IXmlSerializable. Here's one example: http://www.codeproject.com/KB/XML/IXmlSerializable.aspx. And here's another example: http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx.

I'm using the DataContractSerializer within a method whose signature looks like this:

public static Stream GetXmlStream(IXmlSerializable item)

The problem is that while there are many classes in the .NET framework that are serializable, not all of them have explicitly implement the IXmlSerializable interface.

LastEditorDisplayName: dthrasher

OwnerDisplayName: noroom

ContentLicense: CC BY-SA 4.0


问:
Object creation with interface
In C# we can inherit multiple interfaces. In such scenario if an object is created will it just hide the properties or methods or will the compiler avoids creation and memory allocation to those from other interface? For example, I have two interfaces and a class like below

```<code>    interface IExample1
    {
        void E1Test1();
        void E1Test2();
    }

    interface IExample2
    {
        void E2Test1();
        void E2Test2();
    }

    class Example : IExample1, IExample2
    {
        public void E1Test1()
        {
            throw new NotImplementedException();
        }

        public void E1Test2()
        {
            throw new NotImplementedException();
        }

        public void E2Test1()
        {
            throw new NotImplementedException();
        }

        public void E2Test2()
        {
            throw new NotImplementedException();
        }
    }
</code>```

When I create objects like,

```<code>IExample1 IE1 = new Example();
IExample2 IE2 = new Example();
</code>```

Will the compiler creates the complete object for both interfaces including all methods and hide it for one which don't have access? or it just creates with the methods which are available for a particular interface?

答:
You are creating an Example object on the heap. It has everything that an Example has. For instance you can do this.

```<code>IExample1 IE1 = new Example();
IExample2 IE2 = new Example();
IExample2 casted = (IExample1)IE1;
</code>```

You can also debug and see that IE1 and IE2 are in fact Example instances.

Title: Object creation with interface

Body:
In C# we can inherit multiple interfaces. In such scenario if an object is created will it just hide the properties or methods or will the compiler avoids creation and memory allocation to those from other interface? For example, I have two interfaces and a class like below

    interface IExample1
    {
        void E1Test1();
        void E1Test2();
    }

    interface IExample2
    {
        void E2Test1();
        void E2Test2();
    }

    class Example : IExample1, IExample2
    {
        public void E1Test1()
        {
            throw new NotImplementedException();
        }

        public void E1Test2()
        {
            throw new NotImplementedException();
        }

        public void E2Test1()
        {
            throw new NotImplementedException();
        }

        public void E2Test2()
        {
            throw new NotImplementedException();
        }
    }

When I create objects like,

IExample1 IE1 = new Example();
IExample2 IE2 = new Example();

Will the compiler creates the complete object for both interfaces including all methods and hide it for one which don't have access? or it just creates with the methods which are available for a particular interface?

Body:
You are creating an Example object on the heap. It has everything that an Example has. For instance you can do this.

IExample1 IE1 = new Example();
IExample2 IE2 = new Example();
IExample2 casted = (IExample1)IE1;

You can also debug and see that IE1 and IE2 are in fact Example instances.


问:
manipulate data set using R
I have a data set which has for example the following column entries

```<code>Data: 05.12.2017   |   Acceleration: 0,0042414...

Data: 05.12.2017   |   Acceleration: 0,004235235...

Data: 05.12.2017   |   Acceleration: 0,04235235...

Data: 05.12.2017   |   Acceleration: 0,0023414...
</code>```

I want to manipulate the data, such that the name before the ":" is the name of the column.

In other words I want this:

```<code>Data         |  Acceleration

05.12.2017   |  0,0042414...

05.12.2017   |  0,004235235...

05.12.2017   |  0,04235235...

05.12.2017   |  0,0023414...
</code>```

Is there a possibility to do that?

答:
<pre class="lang-r prettyprint-override"><code>#column header
names(df) <- sapply(df[1,], function(x) gsub(":.*","", x))
#column values
df <- sapply(df, function(x) trimws(gsub(".*:","", x)))
#now you can easily format columns as date and numeric
</code>```
<br>
```<code>> #sample data
> dput(df)
structure(list(V1 = structure(c(2L, 1L, 1L, 1L), .Label = c("                 Data: 05.12.2017",
"Data: 05.12.2017"), class = "factor"), V2 = structure(c(3L,
2L, 4L, 1L), .Label = c(" Acceleration: 0,0023414", " Acceleration: 0,004235235",
" Acceleration: 0,0042414", " Acceleration: 0,04235235"), class = "factor")), .Names = c("V1",
"V2"), class = "data.frame", row.names = c(NA, -4L))
</code>```

Title: manipulate data set using R

Body:
I have a data set which has for example the following column entries

Data: 05.12.2017   |   Acceleration: 0,0042414...

Data: 05.12.2017   |   Acceleration: 0,004235235...

Data: 05.12.2017   |   Acceleration: 0,04235235...

Data: 05.12.2017   |   Acceleration: 0,0023414...

I want to manipulate the data, such that the name before the ":" is the name of the column.

In other words I want this:

Data         |  Acceleration

05.12.2017   |  0,0042414...

05.12.2017   |  0,004235235...

05.12.2017   |  0,04235235...

05.12.2017   |  0,0023414...

Is there a possibility to do that?

Body:
#column header
names(df) <- sapply(df[1,], function(x) gsub(":.*","", x))
#column values
df <- sapply(df, function(x) trimws(gsub(".*:","", x)))
#now you can easily format columns as date and numeric

> #sample data
> dput(df)
structure(list(V1 = structure(c(2L, 1L, 1L, 1L), .Label = c("                 Data: 05.12.2017",
"Data: 05.12.2017"), class = "factor"), V2 = structure(c(3L,
2L, 4L, 1L), .Label = c(" Acceleration: 0,0023414", " Acceleration: 0,004235235",
" Acceleration: 0,0042414", " Acceleration: 0,04235235"), class = "factor")), .Names = c("V1",
"V2"), class = "data.frame", row.names = c(NA, -4L))


问:
Enum values depending on controller site in thymeleaf
My enum:

```<code>public enum ADD_OR_EDIT {

    ADD("/user/add", "addForm"), EDIT("/user/edit", "editForm");

    private String thAction;
    private String thObject;

    ADD_OR_EDIT(String thAction, String thObject) {
        this.thAction = thAction;
        this.thObject = thObject;
    }
    //getters and setters ommited to clear view
}
</code>```

My controller line for edit

```<code>addAttribute("addOrEdit", ADD_OR_EDIT.EDIT);
</code>```

My controller line for add:

```<code>addAttribute("addOrEdit", ADD_OR_EDIT.ADD);
</code>```

The question is how to fix my thymeleaf form to get value depending on that.

For example:

```<code>   <form action="#" th:action="(@{addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="${addOrEdit.thObject}"
      method="post">
</code>```

(This one doesn't work)

UPDATE:

The problem is with the second parameter of enum - thObject.

in add:

```<code>model.addAttribute("basicForm", basicForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.ADD);
</code>```

in edit:

```<code>model.addAttribute("editForm", editForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.EDIT);
</code>```

Maybe the value of th:object is "addForm" instead of addForm and this cause an error.

UPDATE2:

This one works:

```<code><form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${basicForm})"
      method="post">
</code>```

This one works also:

```<code><form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${editForm})"
      method="post">
</code>```

So the case now is to connect them by enum like we did on thAction:
This doesnt work:

```<code><form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${{addOrEdit.thObject})"
      method="post">
</code>```

答:
It really depends on what kind of info you want to POST. if it is some User pojo, then you will have to include every field in your form. The basic case would look something like this:</p>

```<code><form action="#" th:action="@{${addOrEdit.thAction}}"
      class="form-horizontal form-narrow" th:object="${__${addOrEdit.thObject}__}"
      method="post">

    <!--FIELDS YOU WANT TO SUBMIT-->
    <input name="id" type="text" th:value="*{id}" hidden="hidden"/>
    <input name="name" type="text" th:value="*{name}" hidden="hidden"/>
    <input name="gender" type="text" th:value="*{gender}" hidden="hidden"/>
    <button type="submit">Submit</button>
</form>
</code>```

Body:
My enum:

public enum ADD_OR_EDIT {

    ADD("/user/add", "addForm"), EDIT("/user/edit", "editForm");

    private String thAction;
    private String thObject;

    ADD_OR_EDIT(String thAction, String thObject) {
        this.thAction = thAction;
        this.thObject = thObject;
    }
    //getters and setters ommited to clear view
}

My controller line for edit

addAttribute("addOrEdit", ADD_OR_EDIT.EDIT);

My controller line for add:

addAttribute("addOrEdit", ADD_OR_EDIT.ADD);

The question is how to fix my thymeleaf form to get value depending on that.

For example:

   <form action="#" th:action="(@{addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="${addOrEdit.thObject}"
      method="post">

(This one doesn't work)

UPDATE:

The problem is with the second parameter of enum - thObject.

in add:

model.addAttribute("basicForm", basicForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.ADD);

in edit:

model.addAttribute("editForm", editForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.EDIT);

Maybe the value of th:object is "addForm" instead of addForm and this cause an error.

UPDATE2:

This one works:

<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${basicForm})"
      method="post">

This one works also:

<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${editForm})"
      method="post">

So the case now is to connect them by enum like we did on thAction:
This doesnt work:

<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${{addOrEdit.thObject})"
      method="post">

Body:
It really depends on what kind of info you want to POST. if it is some User pojo, then you will have to include every field in your form. The basic case would look something like this:

<form action="#" th:action="@{${addOrEdit.thAction}}"
      class="form-horizontal form-narrow" th:object="${__${addOrEdit.thObject}__}"
      method="post">

    <!--FIELDS YOU WANT TO SUBMIT-->
    <input name="id" type="text" th:value="*{id}" hidden="hidden"/>
    <input name="name" type="text" th:value="*{name}" hidden="hidden"/>
    <input name="gender" type="text" th:value="*{gender}" hidden="hidden"/>
    <button type="submit">Submit</button>
</form>


问:
Order the items inside an array from nearest to fairest (from my position)
I created two functions to calculate the distance from me to a point on the map

```<code>func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
        let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
        let to = CLLocation(latitude: to.latitude, longitude: to.longitude)

        return from.distance(from: to)

    }

    func choSed(car:Car) {

        guard let coordinates = car.location  else {
            return
        }
        self.destination = coordinates

        if currentLocation != nil {
        let dis = distance(from: currentLocation!, to: coordinates)

        }
    }
</code>```

and they work well. Now what i need to do (in another function) is to order the items inside an array carsArray from nearest to fairest (from my position)  . I don't know how can i do, maybe i have to calculate the distance of all the items of the array with a cycle and than use a filter to order the position of them, for now i tried to build something like this

```<code>for car in carsArray {
 for di in distance(from: currentLocation!, to: car.location!) {

               }
             }
</code>```

but i get the error (Type 'CLLocationDistance' (aka 'Double') does not conform to protocol 'Sequence') and i also don't know if this could be the correct way to do it. Someone can help me?  (car.location! location in my custom class Car is var location: CLLocationCoordinate2D? and the array carsArray is a vector of my custom class Car i can add to this class all the parameters that it could be useful)

答:
CLLocationDistance is a typealias of a Double.

As already mentioned in one of  your previous questions the in parameter in a for loop must be an array or a range.

To order the items sort them

```<code>let sortedArray = carsArray.sorted {
    distance(from: currentLocation!, to: $0.location!) < distance(from: currentLocation!, to: $1.location!)
}
</code>```

Body:
I created two functions to calculate the distance from me to a point on the map

func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
        let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
        let to = CLLocation(latitude: to.latitude, longitude: to.longitude)

        return from.distance(from: to)

    }

    func choSed(car:Car) {

        guard let coordinates = car.location  else {
            return
        }
        self.destination = coordinates

        if currentLocation != nil {
        let dis = distance(from: currentLocation!, to: coordinates)

        }
    }

and they work well. Now what i need to do (in another function) is to order the items inside an array carsArray from nearest to fairest (from my position)  . I don't know how can i do, maybe i have to calculate the distance of all the items of the array with a cycle and than use a filter to order the position of them, for now i tried to build something like this

for car in carsArray {
 for di in distance(from: currentLocation!, to: car.location!) {

               }
             }

but i get the error (Type 'CLLocationDistance' (aka 'Double') does not conform to protocol 'Sequence') and i also don't know if this could be the correct way to do it. Someone can help me?  (car.location! location in my custom class Car is var location: CLLocationCoordinate2D? and the array carsArray is a vector of my custom class Car i can add to this class all the parameters that it could be useful)

Body:
CLLocationDistance is a typealias of a Double.

As already mentioned in one of  your previous questions the in parameter in a for loop must be an array or a range.

To order the items sort them

let sortedArray = carsArray.sorted {
    distance(from: currentLocation!, to: $0.location!) < distance(from: currentLocation!, to: $1.location!)
}


问:
TypeScript 2.6.1 error TS2554: Expected 2-3 arguments, but got 1
I have this error in angularjs5,

src/app/search/job.search.ts(17,10): error TS2554: Expected 2-3 arguments, but got 1.
src/app/search/job.search.ts(21,10): error TS2554: Expected 2-3 arguments, but got 1.

This is my code:

```<code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import 'rxjs/add/operator/map';

@Injectable()

export class JobSearch{

constructor(private _http: Http){}

private _jobListUrl = 'https://api.shiftjobapp.com/api/v3/job_list?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIzMjQsImlzcyI6Imh0dHA6XC9cL2FwaS5zaGlmdGpvYmFwcC5jb21cL2FwaVwvdjNcL2F1dGhlbnRpY2F0ZV9qb2Jfc2Vla2VyIiwiaWF0IjoxNTEyMzY3OTg1LCJleHAiOjE1MTMyMzE5ODUsIm5iZiI6MTUxMjM2Nzk4NSwianRpIjoiMWQ4NmZkZDYzZDI3YmFiODE0NjA5OTRjOGZhYjI4NTUifQ.3EzNsu154q7a6xFuhQSakBlC-rj1D0HZqLiuwHblNao';

private _jobDetailsUrl = 'https://api.shiftjobapp.com/api/v3/job_detailed?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIzMjQsImlzcyI6Imh0dHA6XC9cL2FwaS5zaGlmdGpvYmFwcC5jb21cL2FwaVwvdjNcL2F1dGhlbnRpY2F0ZV9qb2Jfc2Vla2VyIiwiaWF0IjoxNTEyMzY3OTg1LCJleHAiOjE1MTMyMzE5ODUsIm5iZiI6MTUxMjM2Nzk4NSwianRpIjoiMWQ4NmZkZDYzZDI3YmFiODE0NjA5OTRjOGZhYjI4NTUifQ.3EzNsu154q7a6xFuhQSakBlC-rj1D0HZqLiuwHblNao';

getJobs(){
    return this._http.post(this._jobListUrl)
        .map((response:Response) => response.json());
}
getJobDetails(){
    return this._http.post(this._jobDetailsUrl)
        .map((response:Response) => response.json());
}

}
</code>```

答:
A POST request requires data

See for example

```<code>  addHero (hero: Hero): Observable<Hero> {
    return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
      tap((hero: Hero) => this.log(`added hero w/ id=${hero.id}`)),
      catchError(this.handleError<Hero>('addHero'))
    );
  }
</code>```

from https://angular.io/tutorial/toh-pt6

Body:
I have this error in angularjs5,

src/app/search/job.search.ts(17,10): error TS2554: Expected 2-3 arguments, but got 1.
src/app/search/job.search.ts(21,10): error TS2554: Expected 2-3 arguments, but got 1.

This is my code:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import 'rxjs/add/operator/map';

@Injectable()

export class JobSearch{

constructor(private _http: Http){}

private _jobListUrl = 'https://api.shiftjobapp.com/api/v3/job_list?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIzMjQsImlzcyI6Imh0dHA6XC9cL2FwaS5zaGlmdGpvYmFwcC5jb21cL2FwaVwvdjNcL2F1dGhlbnRpY2F0ZV9qb2Jfc2Vla2VyIiwiaWF0IjoxNTEyMzY3OTg1LCJleHAiOjE1MTMyMzE5ODUsIm5iZiI6MTUxMjM2Nzk4NSwianRpIjoiMWQ4NmZkZDYzZDI3YmFiODE0NjA5OTRjOGZhYjI4NTUifQ.3EzNsu154q7a6xFuhQSakBlC-rj1D0HZqLiuwHblNao';

private _jobDetailsUrl = 'https://api.shiftjobapp.com/api/v3/job_detailed?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIzMjQsImlzcyI6Imh0dHA6XC9cL2FwaS5zaGlmdGpvYmFwcC5jb21cL2FwaVwvdjNcL2F1dGhlbnRpY2F0ZV9qb2Jfc2Vla2VyIiwiaWF0IjoxNTEyMzY3OTg1LCJleHAiOjE1MTMyMzE5ODUsIm5iZiI6MTUxMjM2Nzk4NSwianRpIjoiMWQ4NmZkZDYzZDI3YmFiODE0NjA5OTRjOGZhYjI4NTUifQ.3EzNsu154q7a6xFuhQSakBlC-rj1D0HZqLiuwHblNao';

getJobs(){
    return this._http.post(this._jobListUrl)
        .map((response:Response) => response.json());
}
getJobDetails(){
    return this._http.post(this._jobDetailsUrl)
        .map((response:Response) => response.json());
}

}

Body:
A POST request requires data

See for example

  addHero (hero: Hero): Observable<Hero> {
    return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
      tap((hero: Hero) => this.log(`added hero w/ id=${hero.id}`)),
      catchError(this.handleError<Hero>('addHero'))
    );
  }

from https://angular.io/tutorial/toh-pt6


问:
Good architecture for drawing shapes
For my software engineering object-oriented design class, we are tasked with implementing a simple "Paint" application that can draw simple things like Ellipses, Rectangles, Lines, Free-form curves, and Text.

I am really trying to go for the gold here, and come up with a really clean and elegant architecture, because we need to support things like printing, saving, and exporting to an image, and I want to be able to do so with minimal effort.

So far, I have three "tiers" of classes:

Shape classes: Ellipse, Rectangle, Line, Textbox and Freeform, all inheriting from my custom Shape class

Style classes, each of which implements GraphicsModifier, which allows the class to change the Graphics2D object

StrokeStyle describes how the shape's stroke should be drawn, with Stroke and Paint objects

FillStyle describes the fill , with a Paint object

TextStyle is basically a wrapper for AWT's font classes, allowing easy modification of font sizes, styles, and faces.

Drawing classes

Right now, I am stuck on how my drawing classes should be implemented.

My initial thoughts were to have something like

```<code>class DrawingObject {
    StrokeStyle stroke;
    FillStyle fill;
    TextStyle text;
    Shape shape;

    void draw(Graphics2D g) {
        //????
    }
}
</code>```

The issue is that, if shape is a Freeform, I need to apply only stroke and loop through each point in the curve and draw it separately. If shape is a Rectangle, Line, or Ellipse, I need to apply only stroke and fill, and use g.draw(Shape). If shape is a Textbox, I need to apply all three stroke, fill, and text, and use g.drawString().

It occurred to me that this might be a good place to apply a Strategy pattern, switched on the subclass of shape:

```<code>if (shape instanceof Freeform) {
    strategy = new FreeformDrawer(shape);
} else if (shape instanceof Rectangle || ... ) {
    strategy = new NormalDrawer(shape);
} else if (shape instanceof Textbox) {
    strategy = new TextboxDrawer(shape);
}
strategy.draw(g);
</code>```

(I guess I could use a little reflection magic to switch on the class name too, but that's beside the point)

But somehow this feels a little dirty.

How would you tackle this problem? Am I going about this wrong? Is Strategy a good idea here?

If it matters, I'm using Java and Swing to implement this, but in theory it should be applicable to any OO language/framework.

tl;dr:

Given a bunch of objects to be drawn in different ways, and styles that get applied to them in differing capacities, how would you draw them, using good object-oriented design?

答:
You're right - it does feel a little dirty :)

The reason is that if you were to really use the strategy pattern you would need to replace your existing subclasses. So there would be no Rectangle class anymore, there would just be a Shape with its strategy set to RectangleDrawer. Then there's no need for that ugly set of ifs, because there's no need to map anything.

In this case though, I don't think strategy would be your best option. Strategy is great for when you need to change behaviors dynamically, and I'm guessing in your program once a square is drawn it's never going to change to a circle.

Title: Good architecture for drawing shapes

Body:
For my software engineering object-oriented design class, we are tasked with implementing a simple "Paint" application that can draw simple things like Ellipses, Rectangles, Lines, Free-form curves, and Text.

I am really trying to go for the gold here, and come up with a really clean and elegant architecture, because we need to support things like printing, saving, and exporting to an image, and I want to be able to do so with minimal effort.

So far, I have three "tiers" of classes:

Shape classes: Ellipse, Rectangle, Line, Textbox and Freeform, all inheriting from my custom Shape class

Style classes, each of which implements GraphicsModifier, which allows the class to change the Graphics2D object

StrokeStyle describes how the shape's stroke should be drawn, with Stroke and Paint objects

FillStyle describes the fill , with a Paint object

TextStyle is basically a wrapper for AWT's font classes, allowing easy modification of font sizes, styles, and faces.

Drawing classes

Right now, I am stuck on how my drawing classes should be implemented.

My initial thoughts were to have something like

class DrawingObject {
    StrokeStyle stroke;
    FillStyle fill;
    TextStyle text;
    Shape shape;

    void draw(Graphics2D g) {
        //????
    }
}

The issue is that, if shape is a Freeform, I need to apply only stroke and loop through each point in the curve and draw it separately. If shape is a Rectangle, Line, or Ellipse, I need to apply only stroke and fill, and use g.draw(Shape). If shape is a Textbox, I need to apply all three stroke, fill, and text, and use g.drawString().

It occurred to me that this might be a good place to apply a Strategy pattern, switched on the subclass of shape:

if (shape instanceof Freeform) {
    strategy = new FreeformDrawer(shape);
} else if (shape instanceof Rectangle || ... ) {
    strategy = new NormalDrawer(shape);
} else if (shape instanceof Textbox) {
    strategy = new TextboxDrawer(shape);
}
strategy.draw(g);

(I guess I could use a little reflection magic to switch on the class name too, but that's beside the point)

But somehow this feels a little dirty.

How would you tackle this problem? Am I going about this wrong? Is Strategy a good idea here?

If it matters, I'm using Java and Swing to implement this, but in theory it should be applicable to any OO language/framework.

tl;dr:

Given a bunch of objects to be drawn in different ways, and styles that get applied to them in differing capacities, how would you draw them, using good object-oriented design?


问:
mediasoup - miss match between PayloadTypes
I'm trying to use mediasoup to forward RTP streams with room.createRtpStreamer

my problem is that the payload type (for OPUS) I get from producer.rtpParameters.codecs[i].payloadType is 111,

while the one I get on the actual RTP packets is 100 (seen on Wireshark)

I tried to set preferredPayloadType in my server's config, but it seems to make no difference.

Note:
if I hardcode 100 as the Payload Type for the OPUS stream I can view/hear the stream using FFPlay

I'm using Chrome 55 (latest) and mediasoup 2.0.5 (latest)

any help will be appreciated.

答:
So I found that the payload I get on producer.rtpParameters.codecs[i].payloadType was the original payload and that room.createRtpStreamer changes the payload type.

Ended up doing the below to resolve the issue

```<code>// get the payload (type) from the room.rtpCapabilities.codecs.preferredPayloadType for the specific codec
let payload = this.room.rtpCapabilities.codecs.find((c)=>{
    return c.name === producer.rtpParameters.codecs[i].name;
}).preferredPayloadType;
</code>```

Body:
So I found that the payload I get on producer.rtpParameters.codecs[i].payloadType was the original payload and that room.createRtpStreamer changes the payload type.

Ended up doing the below to resolve the issue

// get the payload (type) from the room.rtpCapabilities.codecs.preferredPayloadType for the specific codec
let payload = this.room.rtpCapabilities.codecs.find((c)=>{
    return c.name === producer.rtpParameters.codecs[i].name;
}).preferredPayloadType;


问:
Apply softmax on a subset of neurons
I'm building a convolutional net in Keras that assigns multiple classes to an image. Given that the image has 9 points of interest that can be classified in one of the three ways I wanted to add 27 output neurons with softmax activation that would compute probability for each consecutive triple of neurons.

Is it possible to do that? I know I can simply add a big softmax layer but this would result in a probability distribution over all output neurons which is too broad for my application.

答:
In the most naive implementation, you can reshape your data and you'll get exactly what you described: "probability for each consecutive triplet".

You take the output with 27 classes, shaped like (batch_size,27) and reshape it:

```<code>model.add(Reshape((9,3)))
model.add(Activation('softmax'))
</code>```

Take care to reshape your y_true data as well. Or add yet another reshape in the model to restore the original form:

```<code>model.add(Reshape((27,))
</code>```

In more elaborate solutions, you'd probably separate the 9 points of insterest according to their locations (if they have a roughly static location) and make parallel paths. For instance, suppose your 9 locations are evenly spaced rectangles, and you want to use the same net and classes for those segments:

```<code>inputImage = Input((height,width,channels))

#supposing the width and height are multiples of 3, for easiness in this example
recHeight = height//3
recWidth = width//3

#create layers here without calling them
someConv1 = Conv2D(...)
someConv2 = Conv2D(...)
flatten = Flatten()
classificator = Dense(..., activation='softmax')

outputs = []
for i in range(3):
    for j in range(3):
        fromH = i*recHeight
        toH = fromH + recHeight
        fromW = j*recWidth
        toW = fromW + recWidth
        imagePart = Lambda(
                           lambda x: x[:,fromH:toH, fromW:toW,:],
                           output_shape=(recHeight,recWidth,channels)
                          )(inputImage)

        #using the same net and classes for all segments
        #if this is not true, create new layers here instead of using the same
        output = someConv1(imagePart)
        output = someConv2(output)
        output = flatten(output)
        output = classificator(output)
        outputs.append(output)

outputs = Concatenate()(outputs)

model = Model(inputImage,outputs)
</code>```

Title: Apply softmax on a subset of neurons

Body:
In the most naive implementation, you can reshape your data and you'll get exactly what you described: "probability for each consecutive triplet".

You take the output with 27 classes, shaped like (batch_size,27) and reshape it:

model.add(Reshape((9,3)))
model.add(Activation('softmax'))

Take care to reshape your y_true data as well. Or add yet another reshape in the model to restore the original form:

model.add(Reshape((27,))

In more elaborate solutions, you'd probably separate the 9 points of insterest according to their locations (if they have a roughly static location) and make parallel paths. For instance, suppose your 9 locations are evenly spaced rectangles, and you want to use the same net and classes for those segments:

inputImage = Input((height,width,channels))

#supposing the width and height are multiples of 3, for easiness in this example
recHeight = height//3
recWidth = width//3

#create layers here without calling them
someConv1 = Conv2D(...)
someConv2 = Conv2D(...)
flatten = Flatten()
classificator = Dense(..., activation='softmax')

outputs = []
for i in range(3):
    for j in range(3):
        fromH = i*recHeight
        toH = fromH + recHeight
        fromW = j*recWidth
        toW = fromW + recWidth
        imagePart = Lambda(
                           lambda x: x[:,fromH:toH, fromW:toW,:],
                           output_shape=(recHeight,recWidth,channels)
                          )(inputImage)

        #using the same net and classes for all segments
        #if this is not true, create new layers here instead of using the same
        output = someConv1(imagePart)
        output = someConv2(output)
        output = flatten(output)
        output = classificator(output)
        outputs.append(output)

outputs = Concatenate()(outputs)

model = Model(inputImage,outputs)


答:
When you instantiate a class using its constructor (which is after using new ...) there´s always a complete instance of that clas in memory. There´s no such thing as an instance of an interface.

An interface on the other side is just some kind of a view upon that instance. So in your example you have four methods that all exist on your instance. However you may or may not access those methods from a reference of either type IExample1 or IExample2. E.g. you cannot E2Test1 on a reference of type IExample1, although the underlying instance does have this method:

```<code>IExample1 i1 = new Example();
</code>```

Now calling i1.E1Test1() will compile just fine, while i1.E2Test1() will not, as that method is defined on another interface. However you can simply cast the instance which is referenced by i1 to the other interface and access that member this way:

```<code>IExample i2 = (IExample2) i1;
i2.E2Test1();
</code>```

EDIT as of TimSchmelters comment: If your Example-class would implement only IExample1 and not the other interface casting to that one would surely fail and produce an InvalidCastException at runtime. So in that case instances of Example-class will only have the members defined on IExample1, not on IExample2. Casting to the latter makes no sense then.

Title: Object creation with interface

Body:
When you instantiate a class using its constructor (which is after using new ...) there´s always a complete instance of that clas in memory. There´s no such thing as an instance of an interface.

An interface on the other side is just some kind of a view upon that instance. So in your example you have four methods that all exist on your instance. However you may or may not access those methods from a reference of either type IExample1 or IExample2. E.g. you cannot E2Test1 on a reference of type IExample1, although the underlying instance does have this method:

IExample1 i1 = new Example();

Now calling i1.E1Test1() will compile just fine, while i1.E2Test1() will not, as that method is defined on another interface. However you can simply cast the instance which is referenced by i1 to the other interface and access that member this way:

IExample i2 = (IExample2) i1;
i2.E2Test1();

EDIT as of TimSchmelters comment: If your Example-class would implement only IExample1 and not the other interface casting to that one would surely fail and produce an InvalidCastException at runtime. So in that case instances of Example-class will only have the members defined on IExample1, not on IExample2. Casting to the latter makes no sense then.


问:
Ajax fails when sending a data object to the NodeJs server
when pressing a button this code gets executed

```<code>function submitData() {
    $.ajax({
        type: 'GET',
        url: '/questionnaire/submit', // listen to a route
        dataType: "json",
        data: JSON.stringify({ // some test data
            satisfactory: "house",
            improvement: "bla",
            rating: "this is a text"
        })
    }).done(function () {
        $(location).attr('href', '/sendOff'); // redirect to another route
    }).fail(function () {
        console.log("Error");
    });
}
</code>```

and the server is listening on this

```<code>app.get('/questionnaire/submit', function (req, res) {
    var data = req.query; // Get the data object from the Ajax call

    console.log(data);

    res.send(null); // Send nothing back
});
</code>```

Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.

Even when writing res.send("Success"); the client will log "Error". What am I missing?

Update:
I installed the body parser middleware and use this code now

my app.js

```<code>const path = require('path');
const express = require('express');
const exphbs  = require('express-handlebars');
const bodyParser = require('body-parser');

const handlebars = exphbs.create({
    defaultLayout: 'index',
    extname: 'hbs'
});

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);

app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'Public')));

app.listen(8888, function () {
    console.log('Server running on port 8888');
});
</code>```

my route

```<code>module.exports = function (app) {

    app.get('/questionnaire', function (req, res) {
        res.render('questionnaire');
    });

    app.post('/questionnaire/submit', function (req, res) {
        var data = req.body;

        console.log(data);

        res.send(null);
    });
};
</code>```

and my client function

```<code>function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: $("#edtSatisfactory").val(),
            improvement: $("#edtImprovement").val(),
            rating: currentRating / ratingElements.length
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}
</code>```

And when executing the Ajax call the client still runs into .fail()

答:
You just have to replace

```<code>dataType: "json",
</code>```

with this:

```<code>'Content-Type': 'application/json'
</code>```

in $.ajax request

Hope this will work.. I have tried & tested.

Body:
when pressing a button this code gets executed

function submitData() {
    $.ajax({
        type: 'GET',
        url: '/questionnaire/submit', // listen to a route
        dataType: "json",
        data: JSON.stringify({ // some test data
            satisfactory: "house",
            improvement: "bla",
            rating: "this is a text"
        })
    }).done(function () {
        $(location).attr('href', '/sendOff'); // redirect to another route
    }).fail(function () {
        console.log("Error");
    });
}

and the server is listening on this

app.get('/questionnaire/submit', function (req, res) {
    var data = req.query; // Get the data object from the Ajax call

    console.log(data);

    res.send(null); // Send nothing back
});

Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.

Even when writing res.send("Success"); the client will log "Error". What am I missing?

Update:
I installed the body parser middleware and use this code now

my app.js

const path = require('path');
const express = require('express');
const exphbs  = require('express-handlebars');
const bodyParser = require('body-parser');

const handlebars = exphbs.create({
    defaultLayout: 'index',
    extname: 'hbs'
});

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);

app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'Public')));

app.listen(8888, function () {
    console.log('Server running on port 8888');
});

my route

module.exports = function (app) {

    app.get('/questionnaire', function (req, res) {
        res.render('questionnaire');
    });

    app.post('/questionnaire/submit', function (req, res) {
        var data = req.body;

        console.log(data);

        res.send(null);
    });
};

and my client function

function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: $("#edtSatisfactory").val(),
            improvement: $("#edtImprovement").val(),
            rating: currentRating / ratingElements.length
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}

And when executing the Ajax call the client still runs into .fail()

Body:
You just have to replace

dataType: "json",

with this:

'Content-Type': 'application/json'

in $.ajax request

Hope this will work.. I have tried & tested.


问:
Can I get the current action that will fire in a before filter?
In a before filter action, can I get the action that will be executed after the before filter?</p>

答: You can always access the RouteData collection(using the filter context) to check what is the action parameter.</p>


答:
You can use ROW_NUMBER here:

```<code>SELECT nr, type, ts
FROM
(
    SELECT nr, type, ts,
        ROW_NUMBER() OVER (PARTITION BY nr ORDER BY ts DESC) rn
    FROM yourTable
) t
WHERE t.rn = 1;
</code>```

If your version of SQL does not have analytic functions, then we can also join to a subquery to get the same result:

```<code>SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT nr, MAX(ts) AS max_ts
    FROM yourTable
    GROUP BY nr
) t2
    ON t1.nr = t2.nr AND
       t1.ts = t2.max_ts;
</code>```

Title: SQL last timestamp from set of data

Body:
I have a problem with getting a last timestamp for each nr in my db.

+--------+---------------------+------------------------------+
|  nr    |        type         |              ts              |
+--------+---------------------+------------------------------+
|        |                     |                              |
|  1002  |          RSC        |  2017-12-05 07:53:42         |
|  1002  |          RSC        |  2017-12-05 07:52:42         |
|  1004  |          RSC        |  2017-12-05 07:54:42         |
|  1004  |          RSC        |  2017-12-05 07:51:42         |
|  1004  |          RSC        |  2017-12-05 07:51:42         |
+--------+---------------------+------------------------------+

Result after select:

+-------+---------------------+-------------------------+
| 1002  |           RSC       |  2017-12-05 07:53:42    |
+-------+---------------------+-------------------------+
| 1004  |          RSC        |  2017-12-05 07:54:42    |
+-------+---------------------+-------------------------+

Thank you for help.

Body:
You can use ROW_NUMBER here:

SELECT nr, type, ts
FROM
(
    SELECT nr, type, ts,
        ROW_NUMBER() OVER (PARTITION BY nr ORDER BY ts DESC) rn
    FROM yourTable
) t
WHERE t.rn = 1;

If your version of SQL does not have analytic functions, then we can also join to a subquery to get the same result:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT nr, MAX(ts) AS max_ts
    FROM yourTable
    GROUP BY nr
) t2
    ON t1.nr = t2.nr AND
       t1.ts = t2.max_ts;


问:
$(selector, element) Native JS alternative
Hi I'm trying to remove all jQuery from my platform one line at a time.

But I'm having some trouble finding a replacement for this

```<code>$('[data-attribute="value"]', GenericHTMLElement);
</code>```

I was hoping it would be something simple like

var div = document.createElement('div');
div.innerHTML = '

';
var b = div.childNodes;

var a = b.querySelector('[data-attribute="value"]');```

But that's not working either. Does have any suggestions for me?

答:
The reason your attempt isn't working is that you're trying to call querySelector on a NodeList, which doesn't have a querySelector method.

If you try it on a single element, it works fine:

function mySelect(selector, el) {
    return el.querySelector(selector);
}

var div = document.createElement('div');
div.innerHTML = '

';
var b = div.childNodes[0];

console.log(mySelect('[data-attribute="value"]', b));```
</div>
</div>
</p>

<p>But this makes it so that <code>mySelect(selector, el)</code> is nothing more than an alias for <code>el.querySelector(selector)</code>.</p>

<p>Presumably, you'd want to be able to evaluate a selector on multiple elements at once, and return multiple results, like jQuery does. In that case, you can do so by making some adjustments:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function flatMap(values, f) {
    return Array.prototype.concat.apply([], values.map(f));
}

function mySelect(selector, els) {
    return flatMap(els.length ? Array.from(els) : [els], function (el) {
        return Array.from(el.querySelectorAll(selector));
    });
}

var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value">span 1</span><span data-something-else="1000"></span></div><div><span data-attribute="value">span 2</span></div>';

console.log(mySelect('[data-attribute="value"]', div.childNodes));

console.log(mySelect('[data-attribute="value"]', div.childNodes[0]));</code>```

Body:
Hi I'm trying to remove all jQuery from my platform one line at a time.

But I'm having some trouble finding a replacement for this

$('[data-attribute="value"]', GenericHTMLElement);

I was hoping it would be something simple like

var div = document.createElement('div');
div.innerHTML = '

';
var b = div.childNodes;

var a = b.querySelector('[data-attribute="value"]');

But that's not working either. Does have any suggestions for me?

Body:
The reason your attempt isn't working is that you're trying to call querySelector on a NodeList, which doesn't have a querySelector method.

If you try it on a single element, it works fine:

function mySelect(selector, el) {
    return el.querySelector(selector);
}

var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value"></span><span data-something-else="1000"></span></div>';
var b = div.childNodes[0];

console.log(mySelect('[data-attribute="value"]', b));

But this makes it so that mySelect(selector, el) is nothing more than an alias for el.querySelector(selector).

Presumably, you'd want to be able to evaluate a selector on multiple elements at once, and return multiple results, like jQuery does. In that case, you can do so by making some adjustments:

function flatMap(values, f) {
    return Array.prototype.concat.apply([], values.map(f));
}

function mySelect(selector, els) {
    return flatMap(els.length ? Array.from(els) : [els], function (el) {
        return Array.from(el.querySelectorAll(selector));
    });
}

var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value">span 1</span><span data-something-else="1000"></span></div><div><span data-attribute="value">span 2</span></div>';

console.log(mySelect('[data-attribute="value"]', div.childNodes));

console.log(mySelect('[data-attribute="value"]', div.childNodes[0]));


问:
Center vertically a div in Bootstrap 4
I want to center automatically a div on my paga using bootstrap 3 but I cannot achieve it. I got an image (with a fixed responsive height) and I want the text to be centered (horizontally and verticaly)

I've made a bootly : https://www.bootply.com/4AyZFwlOdE

答:
```<code><div class="image">
  <div class="container">
      <div class="row align-items-center">
        <div class="col-xs-8  col-lg-8 col-md-offset-2" >
            <div style=" border:1px solid #F00;"><img src="http://www.dm-3.com/wp-content/uploads/2013/06/example.png" stlye="margin:0 auto"></div>
          </div>
      </div>
    </div>
  </div>
</code>```

Title: Center vertically a div in Bootstrap 4


问:
SecurityException on Intent.ACTION_VIEW while trying to open PDF
I ask a user to choose a PDF document using ACTION_OPEN_DOCUMENT. The intent returns a content URI.

```<code>Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.setType("application/pdf");
    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
</code>```

The content URI is in the format -
content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2FSample%20PDF.pdf

Now, I want the user to access the same document again - later on, from a separate activity. So I write the following code -

```<code>Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                    pdfIntent.setData(document.getLocalUri());
                    pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    mContext.startActivity(pdfIntent);
</code>```

But I get the following error -

```<code>java.lang.SecurityException: UID 10197 does not have permission to content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2FSample%20PDF.pdf [user 0]; you could obtain access using ACTION_OPEN_DOCUMENT or related APIs
</code>```

What am I doing wrong?

答:
What am I doing wrong?

Most likely, your problem lies here:

I want the user to access the same document again - later on, from a separate activity

The activity that requested and received the Uri to the content has rights to that content... but nothing else of your app does. That includes other components in your current process any any components in future processes.

If this is a separate activity, but still in the same app instance (i.e., your process has not been terminated since when you got the Uri), you need to pass the rights to that content to the separate activity. Pass the Uri via the "data" facet of the Intent and use setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) as you are doing with the ACTION_VIEW Intent. See this sample app, where I use FLAG_GRANT_READ_URI_PERMISSION to grant rights to a Service to be able to read the content.

If your intention is to persist the Uri value itself (e.g., store it as a string in a database) and use it in the future, you can instead use takePersistableUriPermission() on ContentResolver to request long-term access to the content. This should succeed (I don't know of any scenario where you're immediately denied access). You should have access until something drastic happens to the content, such as the user deleting it.

Body:
I ask a user to choose a PDF document using ACTION_OPEN_DOCUMENT. The intent returns a content URI.

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.setType("application/pdf");
    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    intent.addCategory(Intent.CATEGORY_OPENABLE);

The content URI is in the format -
content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2FSample%20PDF.pdf

Now, I want the user to access the same document again - later on, from a separate activity. So I write the following code -

Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                    pdfIntent.setData(document.getLocalUri());
                    pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    mContext.startActivity(pdfIntent);

But I get the following error -

java.lang.SecurityException: UID 10197 does not have permission to content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2FSample%20PDF.pdf [user 0]; you could obtain access using ACTION_OPEN_DOCUMENT or related APIs

What am I doing wrong?


问:
CSS Units - What is the difference between vh/vw and %?
I just learned about a new and uncommon CSS unit. vh and vw measure the percentage of height and width of the viewport respectively.

I looked at this question from Stack Overflow, but it made the units look even more similar.

How does vw and vh unit works

The answer specifically says

vw and vh are a percentage of the window width and height,
  respectively: 100vw is 100% of the width, 80vw is 80%, etc.

This seems like the exact same as the % unit, which is more common.

In Developer Tools, I tried changing the values from vw/vh to % and viceversa and got the same result.

Is there a difference between the two? If not, why were these new units introduced to CSS3?

答:
I know the question is very old and @Josh Beam addressed the biggest difference, but there's still another one:

Suppose you have a
, direct child of  that you want filling the whole viewport, so you use width: 100vw; height: 100vh;. It all works just the same as width: 100%; height: 100vh; until you add more content and a vertical scrollbar shows up. Since the vw account for the scrollbar as part of the viewport, width: 100vw; will be slightly bigger than width: 100%;. This little difference ends up adding a horizontal scrollbar (required for the user to see that little extra width) and by consequence, the height would also be a little different on both cases.

That must be taken into consideration when deciding which one to use, even if the parent element size is the same as the document viewport size.

Example:

Using width:100vw;:

.fullviewport {
  width: 100vw;
  height: 100vh;
  background-color: red;
}

.extracontent {
  width: 100vw;
  height: 20vh;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
<div class="fullviewport"></div>
<div class="extracontent"></div>
</body>
</html></code>```

Using width:100%;:

.fullviewport {
  width: 100%;
  height: 100vh;
  background-color: red;
}

.extracontent {
  width: 100%;
  height: 20vh;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
<div class="fullviewport"></div>
<div class="extracontent"></div>
</body>
</html></code>```

Body:
I know the question is very old and @Josh Beam addressed the biggest difference, but there's still another one:

Suppose you have a <div>, direct child of <body> that you want filling the whole viewport, so you use width: 100vw; height: 100vh;. It all works just the same as width: 100%; height: 100vh; until you add more content and a vertical scrollbar shows up. Since the vw account for the scrollbar as part of the viewport, width: 100vw; will be slightly bigger than width: 100%;. This little difference ends up adding a horizontal scrollbar (required for the user to see that little extra width) and by consequence, the height would also be a little different on both cases.

That must be taken into consideration when deciding which one to use, even if the parent element size is the same as the document viewport size.

Example:

Using width:100vw;:

.fullviewport {
  width: 100vw;
  height: 100vh;
  background-color: red;
}

.extracontent {
  width: 100vw;
  height: 20vh;
  background-color: blue;
}

<html>
<body>
<div class="fullviewport"></div>
<div class="extracontent"></div>
</body>
</html>

Using width:100%;:

.fullviewport {
  width: 100%;
  height: 100vh;
  background-color: red;
}

.extracontent {
  width: 100%;
  height: 20vh;
  background-color: blue;
}

<html>
<body>
<div class="fullviewport"></div>
<div class="extracontent"></div>
</body>
</html>


问:
What is the point of printf's length modifier flags?
printf has a series of "length modifier" flags you can pass in the format specifications, for example %d is for an int argument, but %hhd is for a signed char (8-bit) and %lld is a long long (64-bit).

I can see why this is necessary for larger-than-int types, but smaller types are implicitly promoted to int anyway.

In what situation would %hhd give a different output to %d, assuming you actually do pass a signed char?

答:
The promotion will preserve the signedness. The compiler knows the type of the variable, but the printf does not. If you try to print a signed variable with an unsigned conversation specifier, it'll treat the variable differently (i.e, printing out sign-extended F's). The length modifier hh says you explicitly want to print the signed char with an unsigned format. Live example:

```<code>#include <stdio.h>
int main(void) {
  char* s = "\u00d1"; /* Ñ */
  for (char* p = s; *p; ++p) printf("%02X (%02hhX)\n", *p, *p);
  return 0;
}
</code>```

Output:

```<code>FFFFFFC3 (C3)
FFFFFF91 (91)
</code>```

Body:
The promotion will preserve the signedness. The compiler knows the type of the variable, but the printf does not. If you try to print a signed variable with an unsigned conversation specifier, it'll treat the variable differently (i.e, printing out sign-extended F's). The length modifier hh says you explicitly want to print the signed char with an unsigned format. Live example:

#include <stdio.h>
int main(void) {
  char* s = "\u00d1"; /* Ñ */
  for (char* p = s; *p; ++p) printf("%02X (%02hhX)\n", *p, *p);
  return 0;
}

Output:

FFFFFFC3 (C3)
FFFFFF91 (91)


问:
Get information from an ObjectJson without Array
I have the class below and I can fetch information from a JSONArray in this format:

{"cliente":[{"id":"1334","nome":"Bruno"}]}

```<code>TextView nome_usuario;

private static final String TAG_CLIENTE = "cliente";
private static final String TAG_NOME = "nome";

JSONArray cliente = null;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View grafico = inflater.inflate(R.layout.fragment_fragment_perfil, container, false);
nome_usuario = (TextView ) grafico.findViewById(R.id.txtNome);
new JSONParse().execute();
return grafico;
}

private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Atualizando");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();

}

@Override
protected JSONObject doInBackground(String... args) {
    JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl("url do json");
        return json;

}
@Override
protected void onPostExecute(JSONObject json) {
    pDialog.dismiss();
    try {
        cliente = json.getJSONArray(TAG_CLIENTE);
        JSONObject c = cliente.getJSONObject(0);
        String nome = c.getString(TAG_NOME);
        nome_usuario.setText(nome);
    } catch (JSONException e) {
        e.printStackTrace();
    }

}
}

}
</code>```

But now I would like to work with a json in the following format:

{"name": "Bruno"}

I found a question similar to my How to parse JSON Object Android Studio, but I could not apply it to my example.

答:
Try using this, you should replace aJsonResponse with the response from the server</p>

```<code>JSONObject aJsonObject = new JSONObject(aJsonResponse);

String aId = aJsonObject.getString("id");
String aNome = aJsonObject.getString("name");
</code>```

Body:
I have the class below and I can fetch information from a JSONArray in this format:

{"cliente":[{"id":"1334","nome":"Bruno"}]}

TextView nome_usuario;

private static final String TAG_CLIENTE = "cliente";
private static final String TAG_NOME = "nome";

JSONArray cliente = null;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View grafico = inflater.inflate(R.layout.fragment_fragment_perfil, container, false);
nome_usuario = (TextView ) grafico.findViewById(R.id.txtNome);
new JSONParse().execute();
return grafico;
}

private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Atualizando");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();

}

@Override
protected JSONObject doInBackground(String... args) {
    JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl("url do json");
        return json;

}
@Override
protected void onPostExecute(JSONObject json) {
    pDialog.dismiss();
    try {
        cliente = json.getJSONArray(TAG_CLIENTE);
        JSONObject c = cliente.getJSONObject(0);
        String nome = c.getString(TAG_NOME);
        nome_usuario.setText(nome);
    } catch (JSONException e) {
        e.printStackTrace();
    }

}
}

}

But now I would like to work with a json in the following format:

{"name": "Bruno"}

I found a question similar to my How to parse JSON Object Android Studio, but I could not apply it to my example.

Body:
Try using this, you should replace aJsonResponse with the response from the server

JSONObject aJsonObject = new JSONObject(aJsonResponse);

String aId = aJsonObject.getString("id");
String aNome = aJsonObject.getString("name");


答:
You can use group by as well:</p>

```<code>SELECT nr, type, MAX(ts) FROM TABLE
group by nr, type
</code>```

Title: SQL last timestamp from set of data

Body:
You can use group by as well:

SELECT nr, type, MAX(ts) FROM TABLE
group by nr, type


答:
in a sense you need to group by nr and then use min or max on the timestamp if the timestamp is determining the order. otherwise you're looking into something more complex like in this answer: Select first row in each GROUP BY group?
The actual syntax varies a bit depending on the database but the first answer is about right in plain ANSI SQL</p>

```<code>SELECT nr, type, MAX(ts) FROM t
GROUP BY nr, type
</code>```

Title: SQL last timestamp from set of data

Body:
in a sense you need to group by nr and then use min or max on the timestamp if the timestamp is determining the order. otherwise you're looking into something more complex like in this answer: Select first row in each GROUP BY group?
The actual syntax varies a bit depending on the database but the first answer is about right in plain ANSI SQL

SELECT nr, type, MAX(ts) FROM t
GROUP BY nr, type


问:
How to pass dynamic json request body in postman
I have a POST request where i need to pass some parameters dynamically since my code is checking for a duplicate entry. I tried writing a pre request script and then setting the global variables and tried to access it in my request. It is not working. PFB, the details

Pre-request Script

postman.setGlobalVariable("firstname", (text + parseInt(Math.random()*10000)).toString());
postman.setGlobalVariable("lastname", text + parseInt(Math.random()*10000));

Body

{
  "request":
    {
        "firstName":"{{firstname}}",
        "middleName":"mani",
        "lastName":"{{lastname}}"
}
}

Here firstName is getting passed as {{firstname}} instead of random string.

答:
```<code>{
 "request": {
   "firstName":"{{$randomInt}}",
   "middleName":"mani",
   "lastName":"{{$randomInt}}"
  }
}
</code>```

No need to add global variables.
Postman have dynamic variable {{$randomInt}} which Adds a random integer between 0 and 1000

Body:
{
 "request": {
   "firstName":"{{$randomInt}}",
   "middleName":"mani",
   "lastName":"{{$randomInt}}"
  }
}

No need to add global variables.
Postman have dynamic variable {{$randomInt}} which Adds a random integer between 0 and 1000


答:
Here is a solution as I suggested in comment:

```<code>SELECT
    nr
    ,type
    ,MAX(ts) AS [Last Timestamp]
FROM <your_table>
GROUP BY nr, type
</code>```

Summarizing Values: GROUP BY Clause and Aggregate Functions this link will help you understand better the GROUP BY clause and Aggregate Functions.

Title: SQL last timestamp from set of data

Body:
Here is a solution as I suggested in comment:

SELECT
    nr
    ,type
    ,MAX(ts) AS [Last Timestamp]
FROM <your_table>
GROUP BY nr, type

Summarizing Values: GROUP BY Clause and Aggregate Functions this link will help you understand better the GROUP BY clause and Aggregate Functions.


问:
BeanIO - how to assign null to empty list
So I'm using BeanIO and I have to write a type handler, which will assigned null to list if the generic list is empty. For example I'm importing addresses from xml file.

If there is full information about address, xml looks like this:

```<code><Address>
<Street1>aaaaaa</Street1>
  <PostCode>00-000</PostCode>
  <City>bbbbb</City>
  <CountryCode>AA</CountryCode>
  <PhoneNo>+00 00 00000000</PhoneNo>
  <Email>aaa@aaa.aaa</Email>
</Address>
</code>```

If there is no informations of address in xml file, it looks like this:

```<code><Address />
</code>```

Mapping in java class looks like this - with BeanIO @segment annotation:

```<code>@Segment(xmlName = "Address", minOccurs = 0, maxOccurs = -1)
private List<Address> address;
</code>```

Basically, the test class expects that if above list is empty, the type handler should assign null to it. Without any type handler for the list, the empty brackets are assigned:

```<code>address=[]
</code>```

And here is my question, does anyone know how the handler should looks for Collections types, in this case List? Previously I wrote some handlers for strings, ints and so on - things with @Field annotation and everything work well. Now I'm struggling to write for the things with @Segment annotations.
Any hints? From which class to inherit from?

答:
Since version 2.1 you can use lazy="true" on collections. From the migrating to 2.1 documentation

Prior to 2.1, repeating segments designated lazy="true" were unmarshalled as an empty collection. Going forward, a collection will no longer be created if designated lazy and all items are null or the empty String.

Instead of trying to write a TypeHandler, I would first try this:

```<code>@Segment(xmlName = "Address", minOccurs = 0, maxOccurs = -1, lazy="true")
private List<Address> address;
</code>```

I think the "empty brackets" as you called it, is just the way a toString() method was implemented to show that the list is empty.

Body:
So I'm using BeanIO and I have to write a type handler, which will assigned null to list if the generic list is empty. For example I'm importing addresses from xml file.

If there is full information about address, xml looks like this:

<Address>
<Street1>aaaaaa</Street1>
  <PostCode>00-000</PostCode>
  <City>bbbbb</City>
  <CountryCode>AA</CountryCode>
  <PhoneNo>+00 00 00000000</PhoneNo>
  <Email>aaa@aaa.aaa</Email>
</Address>

If there is no informations of address in xml file, it looks like this:

<Address />

Mapping in java class looks like this - with BeanIO @segment annotation:

@Segment(xmlName = "Address", minOccurs = 0, maxOccurs = -1)
private List<Address> address;

Basically, the test class expects that if above list is empty, the type handler should assign null to it. Without any type handler for the list, the empty brackets are assigned:

address=[]

And here is my question, does anyone know how the handler should looks for Collections types, in this case List? Previously I wrote some handlers for strings, ints and so on - things with @Field annotation and everything work well. Now I'm struggling to write for the things with @Segment annotations.
Any hints? From which class to inherit from?

Body:
Since version 2.1 you can use lazy="true" on collections. From the migrating to 2.1 documentation

Prior to 2.1, repeating segments designated lazy="true" were unmarshalled as an empty collection. Going forward, a collection will no longer be created if designated lazy and all items are null or the empty String.

Instead of trying to write a TypeHandler, I would first try this:

@Segment(xmlName = "Address", minOccurs = 0, maxOccurs = -1, lazy="true")
private List<Address> address;

I think the "empty brackets" as you called it, is just the way a toString() method was implemented to show that the list is empty.


答:
CSS

```<code>.vcenter {
    display: inline-block;
    vertical-align: middle;
    float: none;
    line-height: 3em;
    text-align:center;
    height:3em;
    border:1px solid #F00;
}

.image {
    height:500px;
    background:yellow;
}
</code>```

https://www.bootply.com/uAp4vN69nk

Title: Center vertically a div in Bootstrap 4

Body:
I want to center automatically a div on my paga using bootstrap 3 but I cannot achieve it. I got an image (with a fixed responsive height) and I want the text to be centered (horizontally and verticaly)

I've made a bootly : https://www.bootply.com/4AyZFwlOdE

Body:
CSS

.vcenter {
    display: inline-block;
    vertical-align: middle;
    float: none;
    line-height: 3em;
    text-align:center;
    height:3em;
    border:1px solid #F00;
}

.image {
    height:500px;
    background:yellow;
}

https://www.bootply.com/uAp4vN69nk


问:
Remove/delete Firebase dynamic links
I have created the dynamic links using Firebase console. But there are no option to remove or delete or edit options.

I want to delete dynamic links from the console. Any help appreciate.

答: Google just added the edit and archive feature. You can check that out in the Firebase console</p>

Title: Remove/delete Firebase dynamic links


问:
Ajax - send button value to php
I have a problem with send data to php. I want to send button value via jquery ajax. This is my code:
HTML

```<code>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
$(document).ready(function(){
    $.ajax({
        url: "try.php",
        type: "POST",
        data: {
            data: val    // removed ; after val.
        }
    });
});

</script>

    <body>

      <button id="1" name="1"  value="some_value">1</button>
      <button id="2" name="2"  value="some_value">2</button>

    </body>
</code>```

PHP:

```<code><?php

$name = $_POST['data'];
echo $name;

?>
</code>```

It doesn't working...

答:
try this out, i just did and worked fine

here's my js file

```<code><html>
<head>
</head>
<body>
    <button id="1" name="1" value="some_value">1</button>
    <button id="2" name="2" value="some_value">2</button>
</body>
<footer>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('button').click(function() {
                var val = $(this).val();
                $.ajax({
                    // your uri, pay attention if the post is going to the right place
                    url: "try.php",
                    type: "POST",
                    // myVar = name of the var that you will be able to call in php
                    // val = your data
                    data: {'myVar': val}
                });
            });
        });
    </script>
</footer>
</html>
</code>```

and here's my php

```<code><?php
$name = $_POST['myVar']; //the var you put in your ajax data:{}
print_r($name);
</code>```

in google chrome you can press f12 and go to Network Tab, you will be able to see the requisitions that your browser made and theirs responses

Title: Ajax - send button value to php

Body:
I have a problem with send data to php. I want to send button value via jquery ajax. This is my code:
HTML

      <button id="1" name="1"  value="some_value">1</button>
      <button id="2" name="2"  value="some_value">2</button>

PHP:

<?php

$name = $_POST['data'];
echo $name;

?>

It doesn't working...

Body:
try this out, i just did and worked fine

here's my js file

<html>
<head>
</head>
<body>
    <button id="1" name="1" value="some_value">1</button>
    <button id="2" name="2" value="some_value">2</button>
</body>
<footer>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('button').click(function() {
                var val = $(this).val();
                $.ajax({
                    // your uri, pay attention if the post is going to the right place
                    url: "try.php",
                    type: "POST",
                    // myVar = name of the var that you will be able to call in php
                    // val = your data
                    data: {'myVar': val}
                });
            });
        });
    </script>
</footer>
</html>

and here's my php

<?php
$name = $_POST['myVar']; //the var you put in your ajax data:{}
print_r($name);

in google chrome you can press f12 and go to Network Tab, you will be able to see the requisitions that your browser made and theirs responses


问:
Rails 5 pdf preview with Shrine Gem
I am using Shrine Gem for image uploads and was wondering how, if possible, can I show a 1st page preview in my template like showing an image per-say.  I am ok with using jQuery or other library.  Below is my code for the file upload, including my Shrine initializer and uploader file.

view

```<code>...
<div class="col-md-4 upload-block">
    <%= f.label :spec_sheet, 'Spec Sheet' %>
      <% if @product.spec_sheet.present? %>
        <div class="product-image">
          <%= image_tag(@product.spec_sheet_url(:thumb)) %>
            <div class="input-checkbox input-checkbox--switch">
              <input name="product[remove_spec_sheet]" type="hidden" value="0">
              <input id="checkbox-switch" type="checkbox" name="product[remove_spec_sheet]">
              <label for="checkbox-switch"></label>
            </div>
            <span>Remove Spec Sheet</span>
        </div>
        <% end %>
          <%= f.hidden_field :spec_sheet, value: @product.cached_spec_sheet_data %>
            <%= f.file_field :spec_sheet %>
  </div>
...
</code>```

initializer

```<code>require 'shrine'
require 'shrine/storage/file_system'

Shrine.storages = {
    cache: Shrine::Storage::FileSystem.new('public', prefix: 'uploads/cache'),
    store: Shrine::Storage::FileSystem.new('public', prefix: 'uploads/store'),
}

Shrine.plugin :activerecord
Shrine.plugin :remove_attachment
Shrine.plugin :delete_raw
Shrine.plugin :cached_attachment_data # for forms
</code>```

uploader

```<code>require 'image_processing/mini_magick'
class ImageUploader < Shrine
  MAX_IMAGE_SIZE_MB = 5
  include ImageProcessing::MiniMagick

  plugin :determine_mime_type
  plugin :remove_attachment
  plugin :store_dimensions
  plugin :validation_helpers
  plugin :processing
  plugin :versions
  plugin(:default_url) { |_|  '/img/preview-not-available.jpg' }

  Attacher.validate do
    validate_max_size MAX_IMAGE_SIZE_MB.megabytes, message: "is too large (max is #{MAX_IMAGE_SIZE_MB} MB)"
    validate_mime_type_inclusion %w[image/jpeg image/jpg image/png image/gif]
  end

  process(:store) do |io|
    original = io.download

    size_1500 = resize_to_limit!(original, 1500, 600)
    size_500 = resize_to_limit(size_1500,  500, 500)
    size_300 = resize_to_limit(size_500,  300, 300)

    {original: size_1500, medium: size_500, thumb: size_300 }
  end
end
</code>```

答:
If you want to show PDF previews, you'll need to generate them on the server side. In that case it's best to use direct uploads (see the demo for an example of a client side implementation).

You can then generate PDFs preview on direct upload:

```<code># config/initializers/shrine.rb
Shrine.plugin :determine_mime_type

# app/models/image_uploader.rb
class ImageUploader < Shrine
  plugin :processing
  plugin :versions

  process(:upload) do |io, context|
    if Shrine.determine_mime_type(io) == "application/pdf"
      preview = Tempfile.new(["shrine-pdf-preview", ".pdf"], binmode: true)
      begin
        IO.popen *%W[mutool draw -F png -o - #{io.path} 1], "rb" do |command|
          IO.copy_stream(command, preview)
        end
      rescue Errno::ENOENT
        fail "mutool is not installed"
      end

      preview.open # flush & rewind
    end

    versions = { original: io }
    versions[:preview] = preview if preview && preview.size > 0
    versions
  end
end
</code>```

the upload_endpoint sets the :upload processing action, so that's the meaning of process(:upload)

we use rb for IO.popen so that Ruby uses binary encoding, which is more safe and cross-platform

Kernel#spawn and any methods that use spawn (system, IO.popen etc.) will raise Errno::ENOENT when shell command was not found

we use *%W[] instead of just "" so that Ruby avoids the shell (and with that any possible shell escaping issues) and passes the command directly to the OS

we check whether the preview file is nonempty because it will be empty in case the mutool command failed (in this case we probably want to fall back to not displaying a preview)

The result of the POST request to the upload_endpoint will now contain the uploaded file ID of the preview, which you can use to generate the URL to the preview. In your case that would be "/uploads/cache" + id.

Note that this means you'll have to slightly modify the processing code that is called when cached file is promoted to permanent storage. In the process(:store) do |io, context| block the io will now be a hash of versions, so you can access the original cached file via io[:original]. And be sure to also include the preview file in the result of that block, as you'll likely want to keep it.

```<code>process(:store) do |io, context|
  original = io[:original].download

  # processing...

  versions = io.dup
  versions[:small] = small
  versions[:medium] = medium
  # ...
  versions
end
</code>```

Title: Rails 5 pdf preview with Shrine Gem

Body:
I am using Shrine Gem for image uploads and was wondering how, if possible, can I show a 1st page preview in my template like showing an image per-say.  I am ok with using jQuery or other library.  Below is my code for the file upload, including my Shrine initializer and uploader file.

view

...

    <%= f.label :spec_sheet, 'Spec Sheet' %>
      <% if @product.spec_sheet.present? %>

          <%= image_tag(@product.spec_sheet_url(:thumb)) %>

              <input name="product[remove_spec_sheet]" type="hidden" value="0">
              <input id="checkbox-switch" type="checkbox" name="product[remove_spec_sheet]">

            Remove Spec Sheet

        <% end %>
          <%= f.hidden_field :spec_sheet, value: @product.cached_spec_sheet_data %>
            <%= f.file_field :spec_sheet %>

...

initializer

require 'shrine'
require 'shrine/storage/file_system'

Shrine.storages = {
    cache: Shrine::Storage::FileSystem.new('public', prefix: 'uploads/cache'),
    store: Shrine::Storage::FileSystem.new('public', prefix: 'uploads/store'),
}

Shrine.plugin :activerecord
Shrine.plugin :remove_attachment
Shrine.plugin :delete_raw
Shrine.plugin :cached_attachment_data # for forms

uploader

require 'image_processing/mini_magick'
class ImageUploader < Shrine
  MAX_IMAGE_SIZE_MB = 5
  include ImageProcessing::MiniMagick

  plugin :determine_mime_type
  plugin :remove_attachment
  plugin :store_dimensions
  plugin :validation_helpers
  plugin :processing
  plugin :versions
  plugin(:default_url) { |_|  '/img/preview-not-available.jpg' }

  Attacher.validate do
    validate_max_size MAX_IMAGE_SIZE_MB.megabytes, message: "is too large (max is #{MAX_IMAGE_SIZE_MB} MB)"
    validate_mime_type_inclusion %w[image/jpeg image/jpg image/png image/gif]
  end

  process(:store) do |io|
    original = io.download

    size_1500 = resize_to_limit!(original, 1500, 600)
    size_500 = resize_to_limit(size_1500,  500, 500)
    size_300 = resize_to_limit(size_500,  300, 300)

    {original: size_1500, medium: size_500, thumb: size_300 }
  end
end

Body:
If you want to show PDF previews, you'll need to generate them on the server side. In that case it's best to use direct uploads (see the demo for an example of a client side implementation).

You can then generate PDFs preview on direct upload:

# config/initializers/shrine.rb
Shrine.plugin :determine_mime_type

# app/models/image_uploader.rb
class ImageUploader < Shrine
  plugin :processing
  plugin :versions

  process(:upload) do |io, context|
    if Shrine.determine_mime_type(io) == "application/pdf"
      preview = Tempfile.new(["shrine-pdf-preview", ".pdf"], binmode: true)
      begin
        IO.popen *%W[mutool draw -F png -o - #{io.path} 1], "rb" do |command|
          IO.copy_stream(command, preview)
        end
      rescue Errno::ENOENT
        fail "mutool is not installed"
      end

      preview.open # flush & rewind
    end

    versions = { original: io }
    versions[:preview] = preview if preview && preview.size > 0
    versions
  end
end

the upload_endpoint sets the :upload processing action, so that's the meaning of process(:upload)

we use rb for IO.popen so that Ruby uses binary encoding, which is more safe and cross-platform

Kernel#spawn and any methods that use spawn (system, IO.popen etc.) will raise Errno::ENOENT when shell command was not found

we use *%W[] instead of just "" so that Ruby avoids the shell (and with that any possible shell escaping issues) and passes the command directly to the OS

we check whether the preview file is nonempty because it will be empty in case the mutool command failed (in this case we probably want to fall back to not displaying a preview)

The result of the POST request to the upload_endpoint will now contain the uploaded file ID of the preview, which you can use to generate the URL to the preview. In your case that would be "/uploads/cache" + id.

Note that this means you'll have to slightly modify the processing code that is called when cached file is promoted to permanent storage. In the process(:store) do |io, context| block the io will now be a hash of versions, so you can access the original cached file via io[:original]. And be sure to also include the preview file in the result of that block, as you'll likely want to keep it.

process(:store) do |io, context|
  original = io[:original].download

  # processing...

  versions = io.dup
  versions[:small] = small
  versions[:medium] = medium
  # ...
  versions
end


问:
Missing artifact org.springframework.boot:spring-boot-starter-parent:pom:2.0.0.M5
I am trying to add jpa dependency in my spring boot pom.xml file

I am getting red underline under dependency. When I hover over it shows

Missing artifact org.springframework.boot:spring-boot-starter-parent:pom:2.0.0.M5

What to do?

答: Did you try maven update, it shall download the missing artifact.</p>


问:
filter json array php by string
I have a JSON array that uses json_decode() to setup the data.

I'm looking to match a certain item in the array and if it matches i need to return the entire "row" of the array, not just a single field like all of the filter_array() snippets i'm finding.

Can anyone point me in the right direction?

Data looks like this before calling json_decode():

```<code>[
    {
        "format": "default",
        "media_url": "http://cpe.delvenetworks.com/000337/011911_redzonefull.mp3",
        "title": "RZ - Jim Trotter",
        "thumb_url": "",
        "date_posted": "2011-01-19 14:58:45",
        "media_type": "audio"
    },
    {
        "format": "default",
        "media_url": "http://cpe.delvenetworks.com/000337/f10bestof2010offense.mp4",
        "title": "Best of O - 2010",
        "thumb_url": "http://img.delvenetworks.com/bV7.120x66.jpeg",
        "date_posted": "2011-01-18 16:01:45",
        "media_type": "video"
    },
    {
        "format": "default",
        "media_url": "http://cpe.delvenetworks.com/000337\f10bestof2010defense.mp4",
        "title": "Best od D - 2010",
        "thumb_url": "http://img.delvenetworks.com/UqK.120x66.jpeg",
        "date_posted": "2011-01-18 16:01:45",
        "media_type": "video"
    }
</code>```

I need to match media_type.

答:
Something like this?</p>

```<code>function filter($filter, $array){
    $filtered_array = array();
    for($i = 0; i < count(array); i++){
        if($array[i].media_type == $filter)
            $filtered_array[] = array[i]
    }
    return $filtered_array
}
</code>```

Title: filter json array php by string

Body:
I have a JSON array that uses json_decode() to setup the data.

I'm looking to match a certain item in the array and if it matches i need to return the entire "row" of the array, not just a single field like all of the filter_array() snippets i'm finding.

Can anyone point me in the right direction?

Data looks like this before calling json_decode():

[
    {
        "format": "default",
        "media_url": "http://cpe.delvenetworks.com/000337/011911_redzonefull.mp3",
        "title": "RZ - Jim Trotter",
        "thumb_url": "",
        "date_posted": "2011-01-19 14:58:45",
        "media_type": "audio"
    },
    {
        "format": "default",
        "media_url": "http://cpe.delvenetworks.com/000337/f10bestof2010offense.mp4",
        "title": "Best of O - 2010",
        "thumb_url": "http://img.delvenetworks.com/bV7.120x66.jpeg",
        "date_posted": "2011-01-18 16:01:45",
        "media_type": "video"
    },
    {
        "format": "default",
        "media_url": "http://cpe.delvenetworks.com/000337\f10bestof2010defense.mp4",
        "title": "Best od D - 2010",
        "thumb_url": "http://img.delvenetworks.com/UqK.120x66.jpeg",
        "date_posted": "2011-01-18 16:01:45",
        "media_type": "video"
    }

I need to match media_type.

Body:
Something like this?

function filter($filter, $array){
    $filtered_array = array();
    for($i = 0; i < count(array); i++){
        if($array[i].media_type == $filter)
            $filtered_array[] = array[i]
    }
    return $filtered_array
}


问:
Symfony Twig: Get kernel root dir
I have setup the following configuration over my Symfony project:

```<code>twig:
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    globals:
      web_dir: "%kernel.root_dir%/../web"
</code>```

And I have done the following twig symnfony function (as seen in Symfony generate cdn friendly asset url):

```<code>namespace AppBundle\Twig;

class AllExtentions extends \Twig_Extension
{
  public function getFunctions()
  {
      return array(
          new \Twig_SimpleFunction('versionedAsset',array($this,'versionedAsset'))
      );
  }

  /**
     * Gebnerate a cdn friendly url for the assets.
     * @param string $path The url of the path RELATIVE to the css.
     * @return string
     */
    public function versionedWebAsset($path)
    {
        // Set the value of the web_dir global
        // $webDir=
        $hash=hash_file("sha512",$path);
        return $path."?v=".$hash;
    }

}
</code>```

My problem is on how I will get the value of the web_dir global into the versionedAsset function?

Edit 1

I use the Symfony's autowire and I autowire/autoconfigure the AllExtentions class:

```<code>use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

// To use as default template
$definition = new Definition();

$definition
->setAutowired(true)
->setAutoconfigured(true)
->setPublic(false);

$this->registerClasses($definition, 'AppBundle\\', '../../src/AppBundle/*', '../../src/AppBundle/{Entity,Repository,Resources,Tests}');
</code>```

答:
You can achieve this by declaring your extension as a service and then passing a service container to it:

```<code>twig.all.extensions:
    class: AppBundle\Twig\AllExtentions
    arguments:
        - @service_container
    tags:
        - { name: twig.extension }
</code>```

After this add a __construct() method to your Extension and use it to get a your web_dir variable:

```<code>/**
* ContainerInterface $container
*/
public function __construct($container)
{
  $this->container = $container;
}

/**
 * Gebnerate a cdn friendly url for the assets.
 * @param string $path The url of the path RELATIVE to the css.
 * @return string
 */
public function versionedWebAsset($path)
{
    $webDir=$this->container->get('twig')->getGlobals()['web_dir'];
    $hash=hash_file("sha512",$path);
    return $path."?v=".$hash;
}
</code>```

Title: Symfony Twig: Get kernel root dir

Body:
I have setup the following configuration over my Symfony project:

twig:
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    globals:
      web_dir: "%kernel.root_dir%/../web"

And I have done the following twig symnfony function (as seen in Symfony generate cdn friendly asset url):

namespace AppBundle\Twig;

class AllExtentions extends \Twig_Extension
{
  public function getFunctions()
  {
      return array(
          new \Twig_SimpleFunction('versionedAsset',array($this,'versionedAsset'))
      );
  }

  /**
     * Gebnerate a cdn friendly url for the assets.
     * @param string $path The url of the path RELATIVE to the css.
     * @return string
     */
    public function versionedWebAsset($path)
    {
        // Set the value of the web_dir global
        // $webDir=
        $hash=hash_file("sha512",$path);
        return $path."?v=".$hash;
    }

}

My problem is on how I will get the value of the web_dir global into the versionedAsset function?

Edit 1

I use the Symfony's autowire and I autowire/autoconfigure the AllExtentions class:

use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

// To use as default template
$definition = new Definition();

$definition
->setAutowired(true)
->setAutoconfigured(true)
->setPublic(false);

$this->registerClasses($definition, 'AppBundle\\', '../../src/AppBundle/*', '../../src/AppBundle/{Entity,Repository,Resources,Tests}');

Body:
You can achieve this by declaring your extension as a service and then passing a service container to it:

twig.all.extensions:
    class: AppBundle\Twig\AllExtentions
    arguments:
        - @service_container
    tags:
        - { name: twig.extension }

After this add a __construct() method to your Extension and use it to get a your web_dir variable:

/**
* ContainerInterface $container
*/
public function __construct($container)
{
  $this->container = $container;
}

/**
 * Gebnerate a cdn friendly url for the assets.
 * @param string $path The url of the path RELATIVE to the css.
 * @return string
 */
public function versionedWebAsset($path)
{
    $webDir=$this->container->get('twig')->getGlobals()['web_dir'];
    $hash=hash_file("sha512",$path);
    return $path."?v=".$hash;
}


问:
Function with return value not error when you just call the function
For function with return value, why does it not error when we just call it like we call a void function?
For example, printf function is for output. But we see here, printf function have a return value.

```<code>int printf(const char* format, ...) // printf function

#include<string.h>

int main(){
    printf("Hello");
    return 0;
}
</code>```

Why when we have a return value in a function, we could just call the function without specify what the return value saved to? And what happen to the return value?

答:
And what happen to the return value?

It's discarded, ignored.

Why when we have a return value in a function, we could just call the function without specify what the return value saved to?

Because that's what the language designers deemed appropriate. Seems foolish to you, but that return value isn't always guaranteed to be useful. In the case of printf the value indicates how many characters were written. And we may care about it to detect any errors. But if we do any printing as part of error handling itself, what good is that value? Are we going to fail even harder now?
 We should be able to ignore it without introducing an unused variable.

And just in case you want your compiler to warn you about ignoring the value, most have compilation switches to that effect. For example, GCC's -Wunused-result.

In that case, you can make the discarding explicit by casting the result to void. Some say it expresses intent better, but YMMV.

Body:
For function with return value, why does it not error when we just call it like we call a void function?
For example, printf function is for output. But we see here, printf function have a return value.

int printf(const char* format, ...) // printf function

#include<string.h>

int main(){
    printf("Hello");
    return 0;
}

Why when we have a return value in a function, we could just call the function without specify what the return value saved to? And what happen to the return value?