问:
Biopython won't run
So I've been trying to work with Biopython and I'm fairly new. My code:

```<code>fasta_string = open("C:\\Users\\saeed\\Desktop\\dna2.fasta").read()
print('1')
result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)
print('2')

blast_record = NCBIXML.read(result_handle)

len(blast_record.alignments)

E_VALUE_THRESH = 0.01
for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
        if hsp.expect < E_VALUE_THRESH:
            print('*Alignment*')
            print('sequence', alignment.title)
            print('length', alignment.length)
            print(' e value', hsp.expect)
            print(hsp.query)
            print(hsp.match)
            print(hsp.sbjct)
</code>```

Whenever I run this code, It prints 1 and just stops. Not stops as in exits, but keeps running and doesn't print anything else. I tried replacing the dna2.fasta file with just "myseq.fa", but that didn't seem to work either. It just said file does not exist. I want to know what I am doing wrong, and how to fix it. Any help?

答:
This is what I have to do to qblast a sequence via BioPython:

```<code>import ssl  # monkey patch for BioPython 1.68 & 1.69
ssl._create_default_https_context = ssl._create_unverified_context

from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML
from Bio import SeqIO

E_VALUE_THRESH = 0.01

input_file_name = "C:\\Users\\saeed\\Desktop\\dna2.fasta"

fasta_object = SeqIO.read(input_file_name, format='fasta')

result_handle = NCBIWWW.qblast("blastn", "nt", fasta_object.seq)

blast_record = NCBIXML.read(result_handle)

for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
        if hsp.expect < E_VALUE_THRESH:
            print('*Alignment*')
            print('sequence', alignment.title)
            print('length', alignment.length)
            print('e value', hsp.expect)
            print(hsp.query)
            print(hsp.match)
            print(hsp.sbjct)
</code>```

I'd be interested in knowing if there's a better way to handle the SSL/certificate issue.

Title: Biopython won't run

Body:
So I've been trying to work with Biopython and I'm fairly new. My code:

fasta_string = open("C:\\Users\\saeed\\Desktop\\dna2.fasta").read()
print('1')
result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)
print('2')

blast_record = NCBIXML.read(result_handle)

len(blast_record.alignments)

E_VALUE_THRESH = 0.01
for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
        if hsp.expect < E_VALUE_THRESH:
            print('*Alignment*')
            print('sequence', alignment.title)
            print('length', alignment.length)
            print(' e value', hsp.expect)
            print(hsp.query)
            print(hsp.match)
            print(hsp.sbjct)

Whenever I run this code, It prints 1 and just stops. Not stops as in exits, but keeps running and doesn't print anything else. I tried replacing the dna2.fasta file with just "myseq.fa", but that didn't seem to work either. It just said file does not exist. I want to know what I am doing wrong, and how to fix it. Any help?

Body:
This is what I have to do to qblast a sequence via BioPython:

import ssl  # monkey patch for BioPython 1.68 & 1.69
ssl._create_default_https_context = ssl._create_unverified_context

from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML
from Bio import SeqIO

E_VALUE_THRESH = 0.01

input_file_name = "C:\\Users\\saeed\\Desktop\\dna2.fasta"

fasta_object = SeqIO.read(input_file_name, format='fasta')

result_handle = NCBIWWW.qblast("blastn", "nt", fasta_object.seq)

blast_record = NCBIXML.read(result_handle)

for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
        if hsp.expect < E_VALUE_THRESH:
            print('*Alignment*')
            print('sequence', alignment.title)
            print('length', alignment.length)
            print('e value', hsp.expect)
            print(hsp.query)
            print(hsp.match)
            print(hsp.sbjct)

I'd be interested in knowing if there's a better way to handle the SSL/certificate issue.


来源: stackexchange

问:
My code that determines if two arrays are permutations always returns false, why?
I've written this to sort two arrays and then compare the values to see if they're the same, but it always returns false, and I can't figure out why.

It is supposed to find if two arrays are permutations of each other.

```<code>public class Permutations {

    public static void main(String[] args) {
        int[] a = {1,4,6,7,8,34};
        int[] b = {34,6,8,1,4,7};

        System.out.println(arePermutations(a, b));
    }

    public static boolean arePermutations(int[] a, int[] b)
    {
        int count = 0;
        int temp = 0;
        if(a.length == b.length)
        {
            for(int i=0; i<a.length-1; i++)
                for(int j=0; j<a.length-1; j++)
                    if(a[i] > a[j+1] && i>j+1)
                    {
                        temp = a[i];
                        a[i] = a[j+1];
                        a[j+1] = temp;
                    }
            {
                for(int i=0; i<b.length-1; i++)
                    for(int j=0; j<b.length-1; j++)
                        if(b[i] > b[j+1] && i>j+1)
                        {
                            temp = b[i];
                            b[i] = b[j+1];
                            b[j+1] = temp;
                        }
            }
            for(int i=0; i<a.length; i++)
                if(a[i] == b[i])
                {
                    count++;
                }
            if (count == a.length)
            {
                return true;
            }
            else return false;
        }
        else return false;

    }
}
</code>```

答:
The problem is in the implementation of the bubble sort. Change your sorting loops to the following:

```<code>    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a.length - 1; j++) {
            if (a[j] > a[j + 1]) {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }

    for (int i = 0; i < b.length; i++) {
        for (int j = 0; j < b.length - 1; j++) {
            if (b[j] > b[j + 1]) {
                temp = b[j];
                b[j] = b[j + 1];
                b[j + 1] = temp;
            }
        }
    }
</code>```

This code works because a bubble sort just swaps adjacent elements if they need swapping, but needs to run through the entire array multiple times (up to the number of items in the array) to get all the items into the correct position.

ContentLicense: CC BY-SA 3.0

Body:
I've written this to sort two arrays and then compare the values to see if they're the same, but it always returns false, and I can't figure out why.

It is supposed to find if two arrays are permutations of each other.

public class Permutations {

    public static void main(String[] args) {
        int[] a = {1,4,6,7,8,34};
        int[] b = {34,6,8,1,4,7};

        System.out.println(arePermutations(a, b));
    }

    public static boolean arePermutations(int[] a, int[] b)
    {
        int count = 0;
        int temp = 0;
        if(a.length == b.length)
        {
            for(int i=0; i<a.length-1; i++)
                for(int j=0; j a[j+1] && i>j+1)
                    {
                        temp = a[i];
                        a[i] = a[j+1];
                        a[j+1] = temp;
                    }
            {
                for(int i=0; i<b.length-1; i++)
                    for(int j=0; j b[j+1] && i>j+1)
                        {
                            temp = b[i];
                            b[i] = b[j+1];
                            b[j+1] = temp;
                        }
            }
            for(int i=0; i<a.length; i++)
                if(a[i] == b[i])
                {
                    count++;
                }
            if (count == a.length)
            {
                return true;
            }
            else return false;
        }
        else return false;

    }
}

Body:
The problem is in the implementation of the bubble sort. Change your sorting loops to the following:

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a.length - 1; j++) {
            if (a[j] > a[j + 1]) {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }

    for (int i = 0; i < b.length; i++) {
        for (int j = 0; j < b.length - 1; j++) {
            if (b[j] > b[j + 1]) {
                temp = b[j];
                b[j] = b[j + 1];
                b[j + 1] = temp;
            }
        }
    }

This code works because a bubble sort just swaps adjacent elements if they need swapping, but needs to run through the entire array multiple times (up to the number of items in the array) to get all the items into the correct position.


问:
Adding UICollectionView inside UIView without Storyboards
I have ViewController called myVC with UITablewView - myTable.

What I want is to add some UIView as myTable's headerView from code. So inside viewDidLoad() method of myVC I added this code

```<code>    let topView = TopView()
    topView.frame.size.height = 100
    topView.frame.size.width = myTable.frame.width
    myTable.tableHeaderView = featuredEventsView
</code>```

I also created file called TopView.swift that looks something like

```<code>class TopView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .red
    }

    required init?(coder aDecoder: NSCoder) {.....}
}
</code>```

And it is working as it should. I see red UIView in headerView of myTable.

Now I want to add UICollectionView inside topView and I have problems here. I am trying to do something like

```<code>class TopView : UIView, UICollectionViewDataSource, UICollectionViewDelegate {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .red

        addSubview(myCollectionView)
    }

    required init?(coder aDecoder: NSCoder) {.....}

let myCollectionView : UICollectionView = {
        let cv = UICollectionView()
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.delegate = self as! UICollectionViewDelegate
        cv.dataSource = self as! UICollectionViewDataSource
        cv.backgroundColor = .yellow
        return cv
    }()
}
</code>```

I also created functions needed to UICollectionViewDataSource but app crashes after building. What am I doing wrong?

答:
You have two problems:

1) You initialise your UICollectionView incorrectly as you must give it a layout.  You need something like this (use whatever frame you want but if you are going on to use auto layout it doesn't matter):

```<code>let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
</code>```

2) You cannot reference 'self' inside the closure when initialising a property.  This is because if may not have been initialised (as in this case) so you can't guarantee it's safe to use it.

I think you should be ok if you use lazy initialisation like this (plus you don't even need to cast 'self'):

```<code>lazy var myCollectionView : UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
    cv.translatesAutoresizingMaskIntoConstraints = false
    cv.delegate = self
    cv.dataSource = self
    cv.backgroundColor = .yellow
    return cv
}()
</code>```

Using the lazy method should delay until self is initialised and therefore safe to use.

Body:
I have ViewController called myVC with UITablewView - myTable.

What I want is to add some UIView as myTable's headerView from code. So inside viewDidLoad() method of myVC I added this code

    let topView = TopView()
    topView.frame.size.height = 100
    topView.frame.size.width = myTable.frame.width
    myTable.tableHeaderView = featuredEventsView

I also created file called TopView.swift that looks something like

class TopView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .red
    }

    required init?(coder aDecoder: NSCoder) {.....}
}

And it is working as it should. I see red UIView in headerView of myTable.

Now I want to add UICollectionView inside topView and I have problems here. I am trying to do something like

class TopView : UIView, UICollectionViewDataSource, UICollectionViewDelegate {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .red

        addSubview(myCollectionView)
    }

    required init?(coder aDecoder: NSCoder) {.....}

let myCollectionView : UICollectionView = {
        let cv = UICollectionView()
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.delegate = self as! UICollectionViewDelegate
        cv.dataSource = self as! UICollectionViewDataSource
        cv.backgroundColor = .yellow
        return cv
    }()
}

I also created functions needed to UICollectionViewDataSource but app crashes after building. What am I doing wrong?

Body:
You have two problems:

1) You initialise your UICollectionView incorrectly as you must give it a layout.  You need something like this (use whatever frame you want but if you are going on to use auto layout it doesn't matter):

let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)

2) You cannot reference 'self' inside the closure when initialising a property.  This is because if may not have been initialised (as in this case) so you can't guarantee it's safe to use it.

I think you should be ok if you use lazy initialisation like this (plus you don't even need to cast 'self'):

lazy var myCollectionView : UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
    cv.translatesAutoresizingMaskIntoConstraints = false
    cv.delegate = self
    cv.dataSource = self
    cv.backgroundColor = .yellow
    return cv
}()

Using the lazy method should delay until self is initialised and therefore safe to use.


问:
"Conversion to Dalvik format failed with error 1" on external JAR
In my Android application in Eclipse, I get the following error.

UNEXPECTED TOP-LEVEL EXCEPTION:

java.lang.IllegalArgumentException: already added: Lorg/xmlpull/v1/XmlPullParser;

....

Conversion to Dalvik format failed with error 1

This error only appears when I add a specific external JAR file to my project. I searched for a long time for a possible solution, but none of them work.

I even tried to change to Android 1.6 instead of 1.5 (the current version I use).

答: I had this problem with Eclipse neon and JDK 1.8. After changing to JDK 1.7 the problem was solved.

ContentLicense: CC BY-SA 4.0


问:
Angular 2 http post is sent as empty object or on the key side
I'm trying to send data from angular 2 to node js on the server side
my angular code is

```<code>addCrib(data:any) {
  let bodyString = data;
   let headers      = new Headers({ 'Content-Type': 'application/json' });
      return this.http.post('http://localhost:8000/addcribs',data , {headers:headers}).map(res => res.json()).subscribe(
        data => console.log(data)
      );

  }
</code>```

and on the server side

```<code>addcribs: function(req,res){
    var x = req.body;
    console.log(x); // {} with application/json and { '{data....}':''} with application/x-www-form-urlencoded
    let crib = new Cribs({id:0, type:req.body.type,price:req.body.price,address:req.body.address,description:req.body.description,bedrooms:req.body.bedrooms,bathroom:req.body.bathroom,area: req.body.area,image:req.body.image});
    crib.save(function(err,crib){
      if(!err){
        res.json({success:true});
      }
    })
  }
</code>```

when I console.log it on the server side I get an empty object {} when I use contentType: application/json and when I use contentType: application/x-www-form-urlencoded I get all the data on the key side of the object eg. {'{type:house}':''} I tried using JSON.stringify on the data on the client side but no help

N.B. I'm using cors dependency on the server side

答:
I found the answer, I used  content-Type: application/x-www-form-urlencoded

and used:

```<code>let urlSearchParams = new URLSearchParams();
urlSearchParams.append('type', data.type);
urlSearchParams.append('bathrooms', data.bathrooms);
let body = urlSearchParams.toString()
</code>```

urlSearchParams can be imported from http library in angular 2

Body:
I'm trying to send data from angular 2 to node js on the server side
my angular code is

addCrib(data:any) {
  let bodyString = data;
   let headers      = new Headers({ 'Content-Type': 'application/json' });
      return this.http.post('http://localhost:8000/addcribs',data , {headers:headers}).map(res => res.json()).subscribe(
        data => console.log(data)
      );

  }

and on the server side

addcribs: function(req,res){
    var x = req.body;
    console.log(x); // {} with application/json and { '{data....}':''} with application/x-www-form-urlencoded
    let crib = new Cribs({id:0, type:req.body.type,price:req.body.price,address:req.body.address,description:req.body.description,bedrooms:req.body.bedrooms,bathroom:req.body.bathroom,area: req.body.area,image:req.body.image});
    crib.save(function(err,crib){
      if(!err){
        res.json({success:true});
      }
    })
  }

when I console.log it on the server side I get an empty object {} when I use contentType: application/json and when I use contentType: application/x-www-form-urlencoded I get all the data on the key side of the object eg. {'{type:house}':''} I tried using JSON.stringify on the data on the client side but no help

N.B. I'm using cors dependency on the server side

Body:
I found the answer, I used  content-Type: application/x-www-form-urlencoded

and used:

let urlSearchParams = new URLSearchParams();
urlSearchParams.append('type', data.type);
urlSearchParams.append('bathrooms', data.bathrooms);
let body = urlSearchParams.toString()

urlSearchParams can be imported from http library in angular 2


问:
javascript tables not being placed inside div
I have this HTML file which has this div and I want the javascript files I am calling which creates some tables. The tables are being created outside the div. How can I get the tables created inside the div?

here is my html file:

```<code>{%extends 'layout.html'%}

{%block body%}

<link rel="stylesheet" href="../static/style.css">

{%block content%}

    <div class="jumbotron text-center">

        <!-- TABLE DATA FOR TABLE1 -->
        <script type="text/javascript" >
            var tableData = {{ table1|safe }}
        </script>
        <script src="../static/merit_table.js"></script>

        <!-- TABLE DATA FOR TABLE2 -->
        <script type="text/javascript">
            var tableData = {{ table2|safe }}
        </script>
        <script src="../static/merit_table.js"></script>

        <!-- TABLE DATA FOR TABLE3 -->
        <script type="text/javascript">
            var tableData = {{ table3|safe }}
        </script>
        <script src="../static/merit_table.js"></script>

    </div>

{%endblock%}

{%endblock%}
</code>```

here is my css file:

```<code>table{
    table-layout: fixed;
    width: 300px;
    margin: 0 auto; /* or margin: 0 auto 0 auto */
}

th, td {
    width: 250px;
    font-size : 130%;

}
</code>```

here is my javascript file:

```<code>var table = document.createElement('table');

for (var key in tableData) {
    var tr = document.createElement('tr');

    var td1 = document.createElement('td');
    var td2 = document.createElement('td');

    var text1 = document.createTextNode(key);
    var text2 = document.createTextNode(tableData[key]);

    td1.appendChild(text1);
    td2.appendChild(text2);
    tr.appendChild(td1);
    tr.appendChild(td2);

    table.appendChild(tr);
}
document.body.appendChild(table);
</code>```

答:
You're appending the table to the document body rather than to the div. Try giving your div an id and then appending to that id instead of to the body. Something like:

html line 10:

JS last line: document.getElementByID("table-div").appendChild(table);

Body:
I have this HTML file which has this div and I want the javascript files I am calling which creates some tables. The tables are being created outside the div. How can I get the tables created inside the div?

here is my html file:

{%extends 'layout.html'%}

{%block body%}

<link rel="stylesheet" href="../static/style.css">

{%block content%}

{%endblock%}

{%endblock%}

here is my css file:

table{
    table-layout: fixed;
    width: 300px;
    margin: 0 auto; /* or margin: 0 auto 0 auto */
}

th, td {
    width: 250px;
    font-size : 130%;

}

here is my javascript file:

var table = document.createElement('table');

for (var key in tableData) {
    var tr = document.createElement('tr');

    var td1 = document.createElement('td');
    var td2 = document.createElement('td');

    var text1 = document.createTextNode(key);
    var text2 = document.createTextNode(tableData[key]);

    td1.appendChild(text1);
    td2.appendChild(text2);
    tr.appendChild(td1);
    tr.appendChild(td2);

    table.appendChild(tr);
}
document.body.appendChild(table);

Body:
You're appending the table to the document body rather than to the div. Try giving your div an id and then appending to that id instead of to the body. Something like:

html line 10: <div class="jumbotron text-center" id="table-div">

JS last line: document.getElementByID("table-div").appendChild(table);


问:
Multiple execute js script
I have a problem with js script.

I load subpage by ajax and append code to div.

```<code>$.ajax ({
    type: "POST",
    url: "load/page/",
    dataType: "json",
    success : function(data) {
        $('.content').empty();
        $('.content').append(data);
    },
    error : function(e) {
        console.log(e);
    }
});
</code>```

Subpage contains appeal to js script:

```<code><script src="//<?php echo $_SERVER['SERVER_NAME'].'/'.BASE_DIR; ?>/scripts/settings.js"></script>
</code>```

Why when i execute ajax multiple times settings.js events are executing multiple too? I want to could execute ajax code multiple times but js scripts are executing only once.

答: I replaced $(document) to $('.content') and add line $('.content').off(), now code is working great. </p>

Title: Multiple execute js script

Body:
I have a problem with js script.

I load subpage by ajax and append code to div.

$.ajax ({
    type: "POST",
    url: "load/page/",
    dataType: "json",
    success : function(data) {
        $('.content').empty();
        $('.content').append(data);
    },
    error : function(e) {
        console.log(e);
    }
});

Subpage contains appeal to js script:

Why when i execute ajax multiple times settings.js events are executing multiple too? I want to could execute ajax code multiple times but js scripts are executing only once.


问:
changing scene in javafx
what's the matter with this code?
i'm relly confused!!
i wanted to change my scene in main stage.</p>

```<code>public class SignInController {
    @FXML
    TextField SignInPassword;

    @FXML
    TextField SignInUsername;

    @FXML
    CheckBox RememberMe;

    public void signUpScene(MouseEvent mouseEvent) throws IOException {
        Timeline timeline = new Timeline();
        Scene SignUpScene = new Scene(FXMLLoader.load(getClass().getResource("sign up.fxml")),700,700);
        Main.pstage.setScene(SignUpScene);
        timeline.getKeyFrames().addAll(
                new KeyFrame(Duration.ZERO,new KeyValue(SignUpScene.getWidth(),0.0 )),
                new KeyFrame(Duration.millis(1000.0d),new KeyValue(SignUpScene.getWidth(),700.0 ) )
        );

        timeline.play();
    }
}
</code>```

答:
If you want to animate the width of the stage holding your new scene, you can use a Transition:

```<code>public void signUpScene(MouseEvent mouseEvent) throws IOException {
        Scene SignUpScene = new Scene(FXMLLoader.load(getClass().getResource("sign up.fxml")),700,700);
        Main.pstage.setScene(SignUpScene);

        Rectangle clip = new Rectangle(0, 700);

        Transition animateStage = new Transition() {
            {
                setCycleDuration(Duration.millis(1000));
            }
            @Override
            protected void interpolate(double t) {
                Main.pstage.setWidth(t * 700.0);
            }
        };
        animateStage.play();
    }
}
</code>```

Maybe a better approach would be to gradually reveal the new scene using a clip:

```<code>public void signUpScene(MouseEvent mouseEvent) throws IOException {

        Parent root = FXMLLoader.load(getClass().getResource("sign up.fxml"));

        Scene SignUpScene = new Scene(root,700,700);
        Main.pstage.setScene(SignUpScene);

        Rectangle clip = new Rectangle(0, 700);
        Timeline animate = new Timeline(
           new KeyFrame(Duration.millis(1000),
               new KeyValue(clip.widthProperty(), 700.0));
        root.setClip(clip);
        // when animation finishes, remove clip:
        animate.setOnFinished(e -> root.setClip(null));
        animate.play();
    }
}
</code>```

Title: changing scene in javafx

Body:
what's the matter with this code?
i'm relly confused!!
i wanted to change my scene in main stage.

public class SignInController {
    @FXML
    TextField SignInPassword;

    @FXML
    TextField SignInUsername;

    @FXML
    CheckBox RememberMe;

    public void signUpScene(MouseEvent mouseEvent) throws IOException {
        Timeline timeline = new Timeline();
        Scene SignUpScene = new Scene(FXMLLoader.load(getClass().getResource("sign up.fxml")),700,700);
        Main.pstage.setScene(SignUpScene);
        timeline.getKeyFrames().addAll(
                new KeyFrame(Duration.ZERO,new KeyValue(SignUpScene.getWidth(),0.0 )),
                new KeyFrame(Duration.millis(1000.0d),new KeyValue(SignUpScene.getWidth(),700.0 ) )
        );

        timeline.play();
    }
}

Body:
If you want to animate the width of the stage holding your new scene, you can use a Transition:

public void signUpScene(MouseEvent mouseEvent) throws IOException {
        Scene SignUpScene = new Scene(FXMLLoader.load(getClass().getResource("sign up.fxml")),700,700);
        Main.pstage.setScene(SignUpScene);

        Rectangle clip = new Rectangle(0, 700);

        Transition animateStage = new Transition() {
            {
                setCycleDuration(Duration.millis(1000));
            }
            @Override
            protected void interpolate(double t) {
                Main.pstage.setWidth(t * 700.0);
            }
        };
        animateStage.play();
    }
}

Maybe a better approach would be to gradually reveal the new scene using a clip:

public void signUpScene(MouseEvent mouseEvent) throws IOException {

        Parent root = FXMLLoader.load(getClass().getResource("sign up.fxml"));

        Scene SignUpScene = new Scene(root,700,700);
        Main.pstage.setScene(SignUpScene);

        Rectangle clip = new Rectangle(0, 700);
        Timeline animate = new Timeline(
           new KeyFrame(Duration.millis(1000),
               new KeyValue(clip.widthProperty(), 700.0));
        root.setClip(clip);
        // when animation finishes, remove clip:
        animate.setOnFinished(e -> root.setClip(null));
        animate.play();
    }
}


问:
Doctrine 2 join table + extra fields
I've got two tables and a join table: 'staff', 'classification' and 'staff_classification'. In the join table I've got an extra boolean field: 'showclassification'. My annotation is as follows:

```<code> /**
 * @ManyToMany(targetEntity="Staff", inversedBy="classifications")
 * @JoinTable(name="staff_classifications",
 *  joinColumns={@JoinColumn(name="staffid", referencedColumnName="id")},
 *  inverseJoinColumns={@JoinColumn(name="classificationid", referencedColumnName="id", unique=true)});
 */
</code>```

How do I add the extra field 'showclassifications' to the join table?

How do I reference the field via DQL? E.g. What query would get all of a staff's classifications that are allowed to be shown?

Do I place the above annotation in one class and a @ManyToMany annotation with no @joinTable in the other? E.g. @ManyToMany (targetEntity="Classification")?

答:
You want an entity that describes the relationship (StaffClassifications), which has OneToMany relationships with both staff and classifications.

ManyToMany doesn't allow you have any "extra" properties, because the join table is not an entity, and thus can't have any properties.

ContentLicense: CC BY-SA 2.5

Title: Doctrine 2 join table + extra fields

Body:
I've got two tables and a join table: 'staff', 'classification' and 'staff_classification'. In the join table I've got an extra boolean field: 'showclassification'. My annotation is as follows:

 /**
 * @ManyToMany(targetEntity="Staff", inversedBy="classifications")
 * @JoinTable(name="staff_classifications",
 *  joinColumns={@JoinColumn(name="staffid", referencedColumnName="id")},
 *  inverseJoinColumns={@JoinColumn(name="classificationid", referencedColumnName="id", unique=true)});
 */

How do I add the extra field 'showclassifications' to the join table?

How do I reference the field via DQL? E.g. What query would get all of a staff's classifications that are allowed to be shown?

Do I place the above annotation in one class and a @ManyToMany annotation with no @joinTable in the other? E.g. @ManyToMany (targetEntity="Classification")?


问:
How To Enable USB Debugging For The Samsung S7
I am trying to use the chrome remote debugging tools.

So I am following this doc https://developer.chrome.com/devtools/docs/remote-debugging

However once I have developer options enabled, I cannot enable USB debugging. It stays disabled(greyed out)

Please not I have done this several times with other devices. My S7 is the only device that won't let me enable USB debugging.

Device information: Samsung Galaxy S7, android 6.0.1

Thanks in advance for your time and help.

EDIT: I have tried before and after connecting my device. The USB configuration is MTP.

答:
I don't know why Samsung does these kind of things, but this worked for me:

Go to "Settings"

Select "About Device"

Select "Software Info"

Look for "Build number" and tap 7 times on it (yes, crazy right?) and you'll see a message that says “Developer mode has been enabled“.

Now when you go to Setting you will see the "Developer options" there. Make sure it is turned on and that USB debugging is turned on as well.

And that's it.


问:
How to split string using istringstream with other delimiter than whitespace?
The following trick using istringstream to split a string with white spaces.

```<code>int main() {
    string sentence("Cpp is fun");
    istringstream in(sentence);
    vector<string> vec = vector<string>(istream_iterator<string>(in), istream_iterator<string>());
    return 0;
}
</code>```

Is there a similar trick to split a string with any delimiter? For instance, | in "Cpp|is|fun".

答:
```<code>#include <iostream>
#include <string>
#include <sstream>

int main()
{
  std::istringstream iss { "Cpp|is|fun" };

  std::string s;
  while ( std::getline( iss, s, '|' ) )
    std::cout << s << std::endl;

  return 0;
}
</code>```

Demo

Body:
The following trick using istringstream to split a string with white spaces.

int main() {
    string sentence("Cpp is fun");
    istringstream in(sentence);
    vector<string> vec = vector<string>(istream_iterator<string>(in), istream_iterator<string>());
    return 0;
}

Is there a similar trick to split a string with any delimiter? For instance, | in "Cpp|is|fun".

Body:
#include <iostream>
#include <string>
#include <sstream>

int main()
{
  std::istringstream iss { "Cpp|is|fun" };

  std::string s;
  while ( std::getline( iss, s, '|' ) )
    std::cout << s << std::endl;

  return 0;
}

Demo


问:
Prevent >1 person from running VBA macro at a time (shared wkb)
What I'm aiming at is getting a list of all currently running scripts in order to check if other users aren't running the same VBA macro at the same time (and if yes, then stop the code etc., similar to what the OP of the below question wanted). This would be for a shared workbook (I learned it's not designed for this type of work, but I need to try it).

https://stackoverflow.com/a/36116091/5947935

I've been trying to make the code in the above answer work in VBA, but it seems it's a vbs thing and I would like to avoid that.

I'm not an expert to say the least, so I'm having trouble understanding how to get this to work in Excel VBA. I don't even know if it's possible at all.

I've found this as well: VBA Getting program names and task ID of running processes and it works fine but it only lists the running processes.

I've no idea however how to merge the two... or even if the WMI is the correct way to go.

I'd appreciate any sort of help.

答:
I used to create a "locking file" which was just an empty text file with the name of the workbook followed by the username and an extension of .LCK

First thing my code did on auto open was look for a locking file then report back to the user which user had it open then cancel the open.

If it didn't find a locking file then it created one and proceeded as normal. If it found one but it was the same username (ie that user had it crash on them) it proceeded with the open.

The last thing the code did was delete the file.


问:
How to set a placeholder for a Image control (while it downloads)?
I have an app that show a list of images. The image source is set to a http URL, and the images are downloaded and display automatically.

However, while the app is taking time to download, the image control shows nothing. The user experience is not good this way.

How may I display a loading placeholder image, or a loading gauge, for each of the image control?

答:
While an image is loading, it is drawn transparently. You can use this to your advantage to display an element underneath the image while it is loading. For example, you could have a stock image that is bundled with your XAP that represents a default avatar for example. Or you could display a XAML loading animation. Then when the image is finished loading, it will obscure the element behind it.

Mick's suggestion is a good one if you need to minimize your visual tree and if your scenario allows for a code solution. This suggestion is not perfect but it does make it easier to deal with the case where your placeholder image is unscaled/centered but the loaded image is scaled/stretched.


问:
play video in videoview where source is Google Drive shared link (https)
What is the right way to play video which reside on Google Drive using VideoView control ?</p>

答:
Try using the url format of the video from Drive and display it in Android WebView

```<code>Uri uri = Uri.parse("https://drive.google.com/file/d/VIDEO_ID/view");
 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
 startActivity(intent);
</code>```

You may also check this SO post for other workaround.

Body:
Try using the url format of the video from Drive and display it in Android WebView

Uri uri = Uri.parse("https://drive.google.com/file/d/VIDEO_ID/view");
 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
 startActivity(intent);

You may also check this SO post for other workaround.


问:
Parsing Map and String from JSON doesn't work
I am trying to set up my first REST webservice using the spring framework. Before even bothering with the frontend, I want to set up the Requestmapping in the Controller first and I am trying to test this out by using Postman.

I am using postman, set to POST, raw, application/JSON and then the following:

```<code>{"attendanceList" : {
    "Jane Doe": "PRESENT",
    "John MacDonald": "PRESENT",
    "Fred Flinstone": "ABSENT"},
"date":"2017-06-01"}
</code>```

In my Controller I have the following:

```<code>@RequestMapping(value = "/post", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public void setAttendence(@RequestBody Map<String, Attendence> attendenceList, String date) {
    //Implementation code
}
</code>```

However, when I send the above post request to the server, I get a map of size 4:

```<code>"attendanceList" -> ABSENT (the default value)
"Jane Doe" ->  PRESENT
"John MacDonald" -> PRESENT
"Fred Flinstone" -> ABSENT
</code>```

And my String date = null

Why is this not working the way I'm intending it to? What am I doing wrong?

答:
You're telling Spring that the request body, i.e. the whole JSON, should be parsed to a Map<String, Attendence>. The JSON is clearly not such a map.

It should instead be mapped to a class such as

```<code>public class Input {
    Map<String, Attendence> attendanceList;
    LocalDate date;

    // ...
}
</code>```

And of course, the String date argument, that Spring ignores, should be removed.

Body:
I am trying to set up my first REST webservice using the spring framework. Before even bothering with the frontend, I want to set up the Requestmapping in the Controller first and I am trying to test this out by using Postman.

I am using postman, set to POST, raw, application/JSON and then the following:

{"attendanceList" : {
    "Jane Doe": "PRESENT",
    "John MacDonald": "PRESENT",
    "Fred Flinstone": "ABSENT"},
"date":"2017-06-01"}

In my Controller I have the following:

@RequestMapping(value = "/post", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public void setAttendence(@RequestBody Map<String, Attendence> attendenceList, String date) {
    //Implementation code
}

However, when I send the above post request to the server, I get a map of size 4:

"attendanceList" -> ABSENT (the default value)
"Jane Doe" ->  PRESENT
"John MacDonald" -> PRESENT
"Fred Flinstone" -> ABSENT

And my String date = null

Why is this not working the way I'm intending it to? What am I doing wrong?

Body:
You're telling Spring that the request body, i.e. the whole JSON, should be parsed to a Map<String, Attendence>. The JSON is clearly not such a map.

It should instead be mapped to a class such as

public class Input {
    Map<String, Attendence> attendanceList;
    LocalDate date;

    // ...
}

And of course, the String date argument, that Spring ignores, should be removed.


问:
Angular 4 Typescript http post request not working
I'm trying to make a working contact form for my class project by making an http post request to a php file on the server. I know the php file works because when I route to it directly it pings my email, and when I debug in the browser I can see that it's trying to build the http request. The problem I'm having is that I don't really understand what I'm doing.. I'm hoping someone can tell me what's wrong with my code or point me in the right direction. Any help would be greatly appreciated... Here's what I have so far:</p>

```<code>headers = {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}

data = {
    name:'name',
    phone:'555-5555',
    email:'email@gmail.com',
    message:'hello'
}

constructor(private http: Http) { }

postData() {
    console.log(this.data);
    this.http.post('http://mywebsite.net/contact_me.php',
this.data, this.headers);
}
</code>```

答:
Added this to my php file:

```<code>header("Access-Control-Allow-Origin: http://localhost:4200");
</code>```

and updated my body parameter to:

```<code>JSON.stringify(this.data)
</code>```

I'm still having issues with my headers param coming back as 'undefined' but this was enough to at least ping my email with an empty message. Thanks for the help!

Body:
I'm trying to make a working contact form for my class project by making an http post request to a php file on the server. I know the php file works because when I route to it directly it pings my email, and when I debug in the browser I can see that it's trying to build the http request. The problem I'm having is that I don't really understand what I'm doing.. I'm hoping someone can tell me what's wrong with my code or point me in the right direction. Any help would be greatly appreciated... Here's what I have so far:

headers = {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}

data = {
    name:'name',
    phone:'555-5555',
    email:'email@gmail.com',
    message:'hello'
}

constructor(private http: Http) { }

postData() {
    console.log(this.data);
    this.http.post('http://mywebsite.net/contact_me.php',
this.data, this.headers);
}

Body:
Added this to my php file:

header("Access-Control-Allow-Origin: http://localhost:4200");

and updated my body parameter to:

JSON.stringify(this.data)

I'm still having issues with my headers param coming back as 'undefined' but this was enough to at least ping my email with an empty message. Thanks for the help!


问:
Difference between while i < x and for i in range(x)?
It seems to me that the two statements below do the same exact thing in python3.

```<code>while i < x:
    print("hi")
    i+=1
</code>```

and

```<code>for i in range(x):
    print("hi")
</code>```

Is there a functional difference that I'm missing here?

If so, in what cases would you use one over the other?

答:
Usually while is used when you don't know exactly when you want to stop.
For loop is used when you know how many times you want to perform something.

For example :
You have a number, every loop you do some calculation and stop only when the result smaller than a given limit, you need tu use while as you don't know how many time you have to run the function.

In the other hand if you want to go thru n-element of a list, you can use a while but a for is more logical as you know the size of the list.

In your example there is no difference (or maybe only based on performances, timeit can give you more information)

Edit 1
I tried to do the same function with while and for (10000 times the sum of integer from 0 to 15) and for loop is faster. If you can use it, you should choose this one (there is also less variable to set):

Version for

```<code>s = time.time()
for i in range(10000):
    t = 0
    for j in range(15):
        t += j
print(time.time()-s) => 0.0132s
</code>```

Version while

```<code>s = time.time()
i = 0
while i < 10000:
    t = 0
    j = 0
    i += 1
    while j < 15:
        t += j
        j += 1

print(time.time()-s) => 0.0202s
</code>```

One important point also... with a while you can have an infinite loop, with for it's impossible :p

Body:
It seems to me that the two statements below do the same exact thing in python3.

while i < x:
    print("hi")
    i+=1

and

for i in range(x):
    print("hi")

Is there a functional difference that I'm missing here?

If so, in what cases would you use one over the other?

Body:
Usually while is used when you don't know exactly when you want to stop.
For loop is used when you know how many times you want to perform something.

For example :
You have a number, every loop you do some calculation and stop only when the result smaller than a given limit, you need tu use while as you don't know how many time you have to run the function.

In the other hand if you want to go thru n-element of a list, you can use a while but a for is more logical as you know the size of the list.

In your example there is no difference (or maybe only based on performances, timeit can give you more information)

Edit 1
I tried to do the same function with while and for (10000 times the sum of integer from 0 to 15) and for loop is faster. If you can use it, you should choose this one (there is also less variable to set):

Version for

s = time.time()
for i in range(10000):
    t = 0
    for j in range(15):
        t += j
print(time.time()-s) => 0.0132s

Version while

s = time.time()
i = 0
while i < 10000:
    t = 0
    j = 0
    i += 1
    while j < 15:
        t += j
        j += 1

print(time.time()-s) => 0.0202s

One important point also... with a while you can have an infinite loop, with for it's impossible :p


问:
Mercurial seems ignoring its config .hgrc, why?
I preconfigured a login/pass to my .hgrc data, despite that the mercurial ignores it:

```<code>[auth]
becpg.prefix = https://becpg.fr/hg/becpg-community
becpg.username = read-only
becpg.password = read-only
</code>```

Trying to clone it, I get this:

```<code>$ hg clone https://becpg.fr/hg/becpg-community
http authorization required for https://www.becpg.fr/hg/becpg-community
realm: beCPG repositories
user:
</code>```

Giving him the login and the password manually, it is accepted without any problem.

Stracing the mercurial process, I find that yes, it finds my .hgrc in my home, and reads it in:

```<code>15751 open("/home/myusername/.hgrc", O_RDONLY) = 3
15751 fstat(3, {st_mode=S_IFREG|0600, st_size=112, ...}) = 0
15751 fstat(3, {st_mode=S_IFREG|0600, st_size=112, ...}) = 0
15751 lseek(3, 0, SEEK_CUR)             = 0
15751 lseek(3, 0, SEEK_CUR)             = 0
15751 fstat(3, {st_mode=S_IFREG|0600, st_size=112, ...}) = 0
15751 read(3, "[auth]\nbecpg.prefix = https://becpg.fr/hg/becpg-community\nbecpg.username = read-only\nbecpg.password = read-only\n", 4096) = 112
15751 read(3, "", 4096)                 = 0
15751 close(3)                          = 0
</code>```

What could be the reason?

答:
```<code>$ hg clone https://becpg.fr/hg/becpg-community
http authorization required for https://www.becpg.fr/hg/becpg-community
</code>```

You try to clone from becpg.fr, then the authorization asks for www.becpg.fr.

I believe you are being redirected.
Try this:

```<code>[auth]
becpg.prefix = www.becpg.fr/hg/becpg-community
becpg.username = read-only
becpg.password = read-only
</code>```

Body:
I preconfigured a login/pass to my .hgrc data, despite that the mercurial ignores it:

[auth]
becpg.prefix = https://becpg.fr/hg/becpg-community
becpg.username = read-only
becpg.password = read-only

Trying to clone it, I get this:

$ hg clone https://becpg.fr/hg/becpg-community
http authorization required for https://www.becpg.fr/hg/becpg-community
realm: beCPG repositories
user:

Giving him the login and the password manually, it is accepted without any problem.

Stracing the mercurial process, I find that yes, it finds my .hgrc in my home, and reads it in:

15751 open("/home/myusername/.hgrc", O_RDONLY) = 3
15751 fstat(3, {st_mode=S_IFREG|0600, st_size=112, ...}) = 0
15751 fstat(3, {st_mode=S_IFREG|0600, st_size=112, ...}) = 0
15751 lseek(3, 0, SEEK_CUR)             = 0
15751 lseek(3, 0, SEEK_CUR)             = 0
15751 fstat(3, {st_mode=S_IFREG|0600, st_size=112, ...}) = 0
15751 read(3, "[auth]\nbecpg.prefix = https://becpg.fr/hg/becpg-community\nbecpg.username = read-only\nbecpg.password = read-only\n", 4096) = 112
15751 read(3, "", 4096)                 = 0
15751 close(3)                          = 0

What could be the reason?

Body:
$ hg clone https://becpg.fr/hg/becpg-community
http authorization required for https://www.becpg.fr/hg/becpg-community

You try to clone from becpg.fr, then the authorization asks for www.becpg.fr.

I believe you are being redirected.
Try this:

[auth]
becpg.prefix = www.becpg.fr/hg/becpg-community
becpg.username = read-only
becpg.password = read-only


问:
How can place a imageButton inside a textfield?
How can i create a text field with a button at the left side like whatsapp's smiley button and i also want my text to start after the button.

答:
Here is the working code:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <!-- CONTENT -->

    <!-- BOTTOM INPUT SECTION -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@android:color/darker_gray"
        android:padding="8dp">

        <ImageButton
            android:id="@+id/button_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@drawable/ic_group"
            android:background="@android:color/transparent"/>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_toLeftOf="@id/button_group"
            android:layout_marginRight="8dp"
            android:background="@android:color/white"
            android:padding="8dp">

            <ImageButton
                android:id="@+id/button_emoji"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:src="@drawable/ic_smile_face"
                android:background="@android:color/transparent"/>

            <ImageButton
                android:id="@+id/button_camera"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:src="@drawable/ic_camera"
                android:background="@android:color/transparent"/>

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/button_emoji"
                android:layout_toLeftOf="@id/button_camera"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_centerVertical="true"
                android:hint="Type a message"
                android:background="@null" />

        </RelativeLayout>
    </RelativeLayout>
</RelativeLayout>
</code>```

OUTPUT:

Body:
Here is the working code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <!-- CONTENT -->

    <!-- BOTTOM INPUT SECTION -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@android:color/darker_gray"
        android:padding="8dp">

        <ImageButton
            android:id="@+id/button_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@drawable/ic_group"
            android:background="@android:color/transparent"/>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_toLeftOf="@id/button_group"
            android:layout_marginRight="8dp"
            android:background="@android:color/white"
            android:padding="8dp">

            <ImageButton
                android:id="@+id/button_emoji"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:src="@drawable/ic_smile_face"
                android:background="@android:color/transparent"/>

            <ImageButton
                android:id="@+id/button_camera"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:src="@drawable/ic_camera"
                android:background="@android:color/transparent"/>

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/button_emoji"
                android:layout_toLeftOf="@id/button_camera"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_centerVertical="true"
                android:hint="Type a message"
                android:background="@null" />

        </RelativeLayout>
    </RelativeLayout>
</RelativeLayout>

OUTPUT:


问:
best method for passing custom objects from class library to WCF to Client application and back again
here is my scenario:

i have few custom object "classes".. like: Employee, EmployeeStatus, ContactDetail....etc.. these classes will be used as return types for WCF methods.. and will also be used in the client side to be sent to WCF.. so far things are easy.. the hard part is.. i have to use the same classes in a separate class library that comes with the client.. and a class library that is supporting the WCF service.. i need to pass the same objects to all of these sides.. now how do I achieve that?? the reason i am using these class libraries is code re-usability.. for example the Employee class is used in 4 different WCFs and 4 different Clients (Win Apps, ASP.NET Pages)... also these class libraries will be handling all DB stuff to these common objects.. now how do i achieve to make these classes available in all these clients and server sides... whats in my head is one solution.. i make one more class library that holds all these custom objects and add reference to it in all these projects... Will that work?? or is there a better solution?

答: Yes, having your data transfer objects (Employee, ContactDetail) and service interfaces in their own assemblies and then deploying them with the client(s) is what you will have to do in order for the clients to create a proxy to communicate with your WCF services.</p>


问:
TypeError: Cannot read property '_id' of undefined in MEAN Stack
What I'm trying to accomplish is to write a message in a database when the user sends a message. I'm using the MEAN stack with angular-cli.

The error I am receiving is:

```<code>TypeError: Cannot read property '_id' of undefined
    at JwtStrategy._verify (/Volumes/SSD/Documents/WebProjects/MEANTest/config/passport.js:11:38)
    at /Volumes/SSD/Documents/WebProjects/MEANTest/node_modules/passport-jwt/lib/strategy.js:110:26
    at /Volumes/SSD/Documents/WebProjects/MEANTest/node_modules/jsonwebtoken/verify.js:27:18
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
</code>```

Here is every bit of code I use to see if someone can figure out what I'm doing wrong.

Node with Express located in '/users':

```<code>router.post('/newmessages', passport.authenticate('jwt', {session: false}), function(req, res, next){

var msgID = getMessageID(req.body.user.username);

  let newMessage = Message({
    createdBy:req.body.message.createdBy,
    recipients:req.body.message.recipients,
    dateCreated:getTodayDate(),
    subject:req.body.message.subject,
    message:req.body.message.message,
    read: false,
    previousMessage:req.body.message.previousMessage,
    nextMessage:req.body.message.nextMessage,
    messageID:msgID
  });

  console.log(newMessage);

  Message.checkMessageID(newMessage, function(err, isFound){
    if(err) throw err;
    if(isFound)
    {
      newMessage.messageID = getMessageID(req.body.username);
    }
    else
    {
      Message.createMessage(newMessage, function(err, isCreated){
        if(err) throw err;
        if(isCreated)
        {
          var token = jwt.sign(req.body, config.secret, {
            expiresIn: 604800 // A week worth of seconds
          });

          res.json({
            success: true,
            token: "JWT " + token,
            user: {
              id: req.body._id,
              name: req.body.name,
              username: req.body.username,
              email: req.body.email
            },
            msg: "Your password has been changed."
          });
        }
        else
        {
          var token = jwt.sign(req.body, config.secret, {
            expiresIn: 604800 // A week worth of seconds
          });

          res.json({
            success: true,
            token: "JWT " + token,
            user: {
              id: req.body._id,
              name: req.body.name,
              username: req.body.username,
              email: req.body.email
            },
            msg: "Your password has been changed."
          });
        }
      });
    }
  });
});
</code>```

PassportJS

```<code>var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var User = require('../models/user');
var config = require('./database');

module.exports = function (passport){
  let opts = {};
  opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts, function(jwt_payload, done){
    User.getUserByID(jwt_payload._doc._id, function(err, user){
      if(err) {
        return done(err, false);
      }
      if(user){
        return done(null, user);
      }
      else{
        return done(null, false);
      }
    });
  }));
};
</code>```

Mongoose schema and code:

```<code>var mongoose = require('mongoose');
var config = require('../config/messages');

// Message Schema
var messageSchema = mongoose.Schema({
  createdBy: {
    type: String,
    required: true
  },
  recipients:{
    type: String,
    required: true
  },
  dateCreated: {
    type: String,
    required: true
  },
  subject: {
    type: String,
    required: true
  },
  message: {
    type: String,
    required: true
  },
  previousMessage: {
    type: String,
    required: true
  },
  nextMessage: {
    type: String,
    required: true
  },
  read: {
    type:Boolean,
    required: true
  },
  messageID: {
    type: String,
    required: true
  }
});

var secondConn = mongoose.createConnection(config.database);

// On Connection
secondConn.on('connected', function(){
    console.log("Connected to database "+ config.database);
});

// On Error
secondConn.on('error', function(err){
    console.log("Database Error " + err);
});

var Messages = module.exports = secondConn.model('Messages', messageSchema);

module.exports.getAllUserMessages = function(user, callback){
  var query = {createdBy: user};

  Messages.find(query, callback);
};

module.exports.getAllRecpMessages = function(user, callback){
  var query = {recipients: user};

  Messages.find(query, callback);
};

module.exports.deleteMessage = function(list, callback){
  var query, i;

  for(i = 0; i < list.length; i++)
  {
      query = { messageID: list[i].messageID};
      Messages.remove(query, function(err){
      });
  }
};

module.exports.createMessage = function(message, callback){
  message.save(function(err, doc){
    if(err) throw err;
    if(doc === null)
    {
      callback(null, false);
    }
    else
    {
      callback(null, true);
    }
  });
};

// Returns false if no other message has the same ID
module.exports.checkMessageID = function(message, callback){
  var query = {messageID: message.messageID};

  Messages.findOne(query, function(err, message){
    if(err) throw err;
    if(message === null)
    {
      callback(null, false);
    }
    else
    {
      callback(null, true);
    }
  });
};
</code>```

Angular typescript for '/users/messages':

```<code>import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';

@Component({
  selector: 'app-messages',
  templateUrl: './messages.component.html',
  styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {
  createdBy: String;
  recipients: String;
  subject: String;
  message: String;
  previousMessage: String;
  nextMessage: String;
  user: Object;

  constructor(private authService: AuthService,
    private router: Router,
    private flashMessage: FlashMessagesService
    ) { }

  ngOnInit() {
    this.authService.getProfile().subscribe(profile => {
      this.user = profile.user;
      this.createdBy = profile.user.username;
    },
    err => {
      console.log(err);
      return false;
    });
  }

// Need to create Message object and pass to Back End
  newMessage(){
    const newMessage = {
      createdBy: this.createdBy,
      recipients: this.recipients,
      subject: this.subject,
      message: this.message,
      previousMessage: " ",
      nextMessage: " "
    }

    this.authService.newMessage(this.user, newMessage).subscribe(data => {
      if(data.success){
        this.authService.storeUserData(data.token, data.user);
        console.log(data);
        this.router.navigate(['profile']);
      }else{
        console.log(data);
        this.router.navigate(['dashboard']);
      }
    });
  }

  getMessages(){

    this.authService.getMessages(this.user).subscribe(data => {
      if(data.success){
        this.authService.storeUserData(data.token, data.user);
        this.router.navigate(['messages']);
        console.log(data);
      }else{
        this.router.navigate(['dashboard']);
      }
    });
  }
}
</code>```

Angular auth service:

```<code>import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { tokenNotExpired } from 'angular2-jwt';

@Injectable()
export class AuthService {
authToken: any;
user: any;
message: any;

  constructor(private http: Http) { }

// Need to pass Message object to Front End
  newMessage(user, message){
    console.log(user.username + " " + message.createdBy);
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json');
    var info = {user, message};
    return this.http.post('/users/newmessages', user, {headers: headers, body: info})
      .map(res => res.json());
  }

  getMessages(user){
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json');
    return this.http.post('/users/messages', user, {headers: headers})
      .map(res => res.json());
  }

  registerUser(user){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('/users/register', user, {headers: headers})
      .map(res => res.json());
  }

  authenticateUser(user){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('/users/authenticate', user, {headers: headers})
      .map(res => res.json());
  }

  changePassword(user){
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json');
    return this.http.post('/users/changepassword', user, {headers: headers})
      .map(res => res.json());
  }

  getProfile(){
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json');
    return this.http.get('/users/profile', {headers: headers})
      .map(res => res.json());
  }

  storeUserData(token, user){
    localStorage.setItem('id_token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

  loadToken(){
    const token = localStorage.getItem('id_token');
    this.authToken = token;
  }

  loggedIn(){
    return tokenNotExpired('id_token');
  }

  logout(){
    this.authToken = null;
    this.user = null;
    localStorage.clear();
  }
}
</code>```

Just in case, here's my partial user model from the Mongoose Schema:

```<code>var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var config = require('../config/database');

// User Schema
var userSchema = mongoose.Schema({
  name: {
    type: String
  },
  email:{
    type: String,
    required: true
  },
  username: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  verify: {
    type: Boolean,
    required: true
  }
});
</code>```

答:
Whew, fixed it!

In the Angular typescript for '/users/messages':

```<code>// Need to create Message object and pass to Back End
  newMessage(){
    const newMessage = {
      createdBy: this.createdBy,
      recipients: this.recipients,
      subject: this.subject,
      message: this.message,
      previousMessage: " ",
      nextMessage: " "
    }

    this.authService.newMessage(this.user, newMessage).subscribe(data => {
      if(data.success){
        this.authService.storeUserData(data.token, data.user); < Erased that line
        console.log(data);
        this.router.navigate(['profile']);
      }else{
        console.log(data);
        this.router.navigate(['dashboard']);
      }
    });
  }
</code>```

TL;DR Explanation, I was passing an undefined 'data' that was given from the backend. I erased the marked line to make sure I'm not storing user data after sending a message... Because I don't need to.

Thanks to everyone that helped me out!

Body:
What I'm trying to accomplish is to write a message in a database when the user sends a message. I'm using the MEAN stack with angular-cli.

The error I am receiving is:

TypeError: Cannot read property '_id' of undefined
    at JwtStrategy._verify (/Volumes/SSD/Documents/WebProjects/MEANTest/config/passport.js:11:38)
    at /Volumes/SSD/Documents/WebProjects/MEANTest/node_modules/passport-jwt/lib/strategy.js:110:26
    at /Volumes/SSD/Documents/WebProjects/MEANTest/node_modules/jsonwebtoken/verify.js:27:18
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

Here is every bit of code I use to see if someone can figure out what I'm doing wrong.

Node with Express located in '/users':

router.post('/newmessages', passport.authenticate('jwt', {session: false}), function(req, res, next){

var msgID = getMessageID(req.body.user.username);

  let newMessage = Message({
    createdBy:req.body.message.createdBy,
    recipients:req.body.message.recipients,
    dateCreated:getTodayDate(),
    subject:req.body.message.subject,
    message:req.body.message.message,
    read: false,
    previousMessage:req.body.message.previousMessage,
    nextMessage:req.body.message.nextMessage,
    messageID:msgID
  });

  console.log(newMessage);

  Message.checkMessageID(newMessage, function(err, isFound){
    if(err) throw err;
    if(isFound)
    {
      newMessage.messageID = getMessageID(req.body.username);
    }
    else
    {
      Message.createMessage(newMessage, function(err, isCreated){
        if(err) throw err;
        if(isCreated)
        {
          var token = jwt.sign(req.body, config.secret, {
            expiresIn: 604800 // A week worth of seconds
          });

          res.json({
            success: true,
            token: "JWT " + token,
            user: {
              id: req.body._id,
              name: req.body.name,
              username: req.body.username,
              email: req.body.email
            },
            msg: "Your password has been changed."
          });
        }
        else
        {
          var token = jwt.sign(req.body, config.secret, {
            expiresIn: 604800 // A week worth of seconds
          });

          res.json({
            success: true,
            token: "JWT " + token,
            user: {
              id: req.body._id,
              name: req.body.name,
              username: req.body.username,
              email: req.body.email
            },
            msg: "Your password has been changed."
          });
        }
      });
    }
  });
});

PassportJS

var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var User = require('../models/user');
var config = require('./database');

module.exports = function (passport){
  let opts = {};
  opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts, function(jwt_payload, done){
    User.getUserByID(jwt_payload._doc._id, function(err, user){
      if(err) {
        return done(err, false);
      }
      if(user){
        return done(null, user);
      }
      else{
        return done(null, false);
      }
    });
  }));
};

Mongoose schema and code:

var mongoose = require('mongoose');
var config = require('../config/messages');

// Message Schema
var messageSchema = mongoose.Schema({
  createdBy: {
    type: String,
    required: true
  },
  recipients:{
    type: String,
    required: true
  },
  dateCreated: {
    type: String,
    required: true
  },
  subject: {
    type: String,
    required: true
  },
  message: {
    type: String,
    required: true
  },
  previousMessage: {
    type: String,
    required: true
  },
  nextMessage: {
    type: String,
    required: true
  },
  read: {
    type:Boolean,
    required: true
  },
  messageID: {
    type: String,
    required: true
  }
});

var secondConn = mongoose.createConnection(config.database);

// On Connection
secondConn.on('connected', function(){
    console.log("Connected to database "+ config.database);
});

// On Error
secondConn.on('error', function(err){
    console.log("Database Error " + err);
});

var Messages = module.exports = secondConn.model('Messages', messageSchema);

module.exports.getAllUserMessages = function(user, callback){
  var query = {createdBy: user};

  Messages.find(query, callback);
};

module.exports.getAllRecpMessages = function(user, callback){
  var query = {recipients: user};

  Messages.find(query, callback);
};

module.exports.deleteMessage = function(list, callback){
  var query, i;

  for(i = 0; i < list.length; i++)
  {
      query = { messageID: list[i].messageID};
      Messages.remove(query, function(err){
      });
  }
};

module.exports.createMessage = function(message, callback){
  message.save(function(err, doc){
    if(err) throw err;
    if(doc === null)
    {
      callback(null, false);
    }
    else
    {
      callback(null, true);
    }
  });
};

// Returns false if no other message has the same ID
module.exports.checkMessageID = function(message, callback){
  var query = {messageID: message.messageID};

  Messages.findOne(query, function(err, message){
    if(err) throw err;
    if(message === null)
    {
      callback(null, false);
    }
    else
    {
      callback(null, true);
    }
  });
};

Angular typescript for '/users/messages':

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';

@Component({
  selector: 'app-messages',
  templateUrl: './messages.component.html',
  styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {
  createdBy: String;
  recipients: String;
  subject: String;
  message: String;
  previousMessage: String;
  nextMessage: String;
  user: Object;

  constructor(private authService: AuthService,
    private router: Router,
    private flashMessage: FlashMessagesService
    ) { }

  ngOnInit() {
    this.authService.getProfile().subscribe(profile => {
      this.user = profile.user;
      this.createdBy = profile.user.username;
    },
    err => {
      console.log(err);
      return false;
    });
  }

// Need to create Message object and pass to Back End
  newMessage(){
    const newMessage = {
      createdBy: this.createdBy,
      recipients: this.recipients,
      subject: this.subject,
      message: this.message,
      previousMessage: " ",
      nextMessage: " "
    }

    this.authService.newMessage(this.user, newMessage).subscribe(data => {
      if(data.success){
        this.authService.storeUserData(data.token, data.user);
        console.log(data);
        this.router.navigate(['profile']);
      }else{
        console.log(data);
        this.router.navigate(['dashboard']);
      }
    });
  }

  getMessages(){

    this.authService.getMessages(this.user).subscribe(data => {
      if(data.success){
        this.authService.storeUserData(data.token, data.user);
        this.router.navigate(['messages']);
        console.log(data);
      }else{
        this.router.navigate(['dashboard']);
      }
    });
  }
}

Angular auth service:

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { tokenNotExpired } from 'angular2-jwt';

@Injectable()
export class AuthService {
authToken: any;
user: any;
message: any;

  constructor(private http: Http) { }

// Need to pass Message object to Front End
  newMessage(user, message){
    console.log(user.username + " " + message.createdBy);
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json');
    var info = {user, message};
    return this.http.post('/users/newmessages', user, {headers: headers, body: info})
      .map(res => res.json());
  }

  getMessages(user){
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json');
    return this.http.post('/users/messages', user, {headers: headers})
      .map(res => res.json());
  }

  registerUser(user){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('/users/register', user, {headers: headers})
      .map(res => res.json());
  }

  authenticateUser(user){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('/users/authenticate', user, {headers: headers})
      .map(res => res.json());
  }

  changePassword(user){
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json');
    return this.http.post('/users/changepassword', user, {headers: headers})
      .map(res => res.json());
  }

  getProfile(){
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json');
    return this.http.get('/users/profile', {headers: headers})
      .map(res => res.json());
  }

  storeUserData(token, user){
    localStorage.setItem('id_token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

  loadToken(){
    const token = localStorage.getItem('id_token');
    this.authToken = token;
  }

  loggedIn(){
    return tokenNotExpired('id_token');
  }

  logout(){
    this.authToken = null;
    this.user = null;
    localStorage.clear();
  }
}

Just in case, here's my partial user model from the Mongoose Schema:

var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var config = require('../config/database');

// User Schema
var userSchema = mongoose.Schema({
  name: {
    type: String
  },
  email:{
    type: String,
    required: true
  },
  username: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  verify: {
    type: Boolean,
    required: true
  }
});

Body:
Whew, fixed it!

In the Angular typescript for '/users/messages':

// Need to create Message object and pass to Back End
  newMessage(){
    const newMessage = {
      createdBy: this.createdBy,
      recipients: this.recipients,
      subject: this.subject,
      message: this.message,
      previousMessage: " ",
      nextMessage: " "
    }

    this.authService.newMessage(this.user, newMessage).subscribe(data => {
      if(data.success){
        this.authService.storeUserData(data.token, data.user); < Erased that line
        console.log(data);
        this.router.navigate(['profile']);
      }else{
        console.log(data);
        this.router.navigate(['dashboard']);
      }
    });
  }

TL;DR Explanation, I was passing an undefined 'data' that was given from the backend. I erased the marked line to make sure I'm not storing user data after sending a message... Because I don't need to.

Thanks to everyone that helped me out!


问:
node.js / google drive sdk v3: access to webContentLink (and all image metadata)
I'm creating an image file in drive v3 successfully, but cannot retrieve the URI for the file; I'm expecting to find it in the success response_object.

I do find the file ID in the response_object and I can use that to construct a URI that displays the image:

https://drive.google.com/file/d/0Bw4DMtLCtPMkNERiTnpVNDdQV2c/view

I would like to have 'an official/correct' URI to hand to the google Cloud Vision API as an image source. I think I'm looking for the webContentLink v3-file metadata. I guess, more generally, I can't see how to get all the metadata (as described on https://developers.google.com/drive/v3/reference/files) for the file that I have just created.

```<code>        var newFileMetadata = {
          'name': unique_file_name,
          description: options.multipart,
          useContentAsIndexableText: false,
          parents: [ file.id ]
        };

        var media = {
          mimeType: 'image/jpg',
          body: fs.createReadStream(options.src_dir + '/' + sourceFile),
          viewersCanCopyContent: true,
          writersCanShare: true
        };

        var request_object = drive.files.create({
            auth: auth,
            resource: newFileMetadata,
            media: media,
            fields: ['id']
            },
            function(err, response) {
              if (err) {
                console.log('drive.files.create error: %s %s', err, response);
                return;
              } else {
                // file create success; get response
                console.log('dump the response\n %s', JSON.stringify(response));
              }
            }
          );  // end of drive.files.create()
</code>```

and the console output is (with cr for readability):

dump the request_object

{"uri":
 {"protocol":"https:",
 "slashes":true,
 "auth":null,
 "host":"www.googleapis.com",
 "port":null,
 "hostname":"www.googleapis.com",
 "hash":null,
 "search":"?fields=id&uploadType=multipart",
 "query":"fields=id&uploadType=multipart",
 "pathname":"/upload/drive/v3/files",
 "path":"/upload/drive/v3/files?fields=id&uploadType=multipart",
 "href":"https://www.googleapis.com/upload/drive/v3/files?fields=id&uploadType=multipart"},
 "method":"POST",
 "headers":{"Authorization":"Bearer ya29.GlxfB18oVtG6A3j7cXzSq17-RSmj9-2BlQm4zHD5sPzKkfhRM1FxlxUHc9mxWaka1N2fBiTJun-SYLB8ewuc63XVbUo01q0bS2FiS6iJTq9O1h9FQWfoO5r8E6z_6Q",
 "User-Agent":"google-api-nodejs-client/0.10.0","host":"www.googleapis.com",
 "transfer-encoding":"chunked",
 "content-type":"multipart/related;
 boundary=d6cef3f5-2246-5654-ac1f-d00561be5e8a"}
 }

dump the response
 {"id":"0Bw4DMtLCtPMkNERiTnpVNDdQV2c"}

to recap:

how do I get (in Node.js) a google Cloud Vision appropriate URI for a newly created google Drive v3 image file?

how do I get (in Node.js) the metadata for a newly created google Drive v3 image file?

Many thanks.

new information: I have tried a separate drive.files.get()

```<code>                drive.files.get({
                  auth: auth,
                  fileId: response.id
                },
                function(err, response) {
                  if (err) {
                  console.log('drive.files.get error: %s %s', err, response);
                  return;
                  } else {
                  // file create success; get properties
                  console.log('get properties\n %s', JSON.stringify(response));
                  }
                });
</code>```

and I do receive some metadata (but not the big picture), console output, new upload:

get properties
 {"kind":"drive#file","id":"0Bw4DMtLCtPMkWFdTMUVwY2tRZ2c","name":"2017-06-04T17:57:42.189Zlovelock.png","mimeType":"image/png"}

答:
Use Files.get and specify in the 'field' parameter that you want to get webContentLink. It will return just that. Use the Try-it from the docs.

The complete list of metadata you can obtain is found in Files resource.

For testing purposes, pass your fileId here and run Execute.

Body:
I'm creating an image file in drive v3 successfully, but cannot retrieve the URI for the file; I'm expecting to find it in the success response_object.

I do find the file ID in the response_object and I can use that to construct a URI that displays the image:

https://drive.google.com/file/d/0Bw4DMtLCtPMkNERiTnpVNDdQV2c/view

I would like to have 'an official/correct' URI to hand to the google Cloud Vision API as an image source. I think I'm looking for the webContentLink v3-file metadata. I guess, more generally, I can't see how to get all the metadata (as described on https://developers.google.com/drive/v3/reference/files) for the file that I have just created.

        var newFileMetadata = {
          'name': unique_file_name,
          description: options.multipart,
          useContentAsIndexableText: false,
          parents: [ file.id ]
        };

        var media = {
          mimeType: 'image/jpg',
          body: fs.createReadStream(options.src_dir + '/' + sourceFile),
          viewersCanCopyContent: true,
          writersCanShare: true
        };

        var request_object = drive.files.create({
            auth: auth,
            resource: newFileMetadata,
            media: media,
            fields: ['id']
            },
            function(err, response) {
              if (err) {
                console.log('drive.files.create error: %s %s', err, response);
                return;
              } else {
                // file create success; get response
                console.log('dump the response\n %s', JSON.stringify(response));
              }
            }
          );  // end of drive.files.create()

and the console output is (with cr for readability):

dump the request_object

{"uri":
 {"protocol":"https:",
 "slashes":true,
 "auth":null,
 "host":"www.googleapis.com",
 "port":null,
 "hostname":"www.googleapis.com",
 "hash":null,
 "search":"?fields=id&uploadType=multipart",
 "query":"fields=id&uploadType=multipart",
 "pathname":"/upload/drive/v3/files",
 "path":"/upload/drive/v3/files?fields=id&uploadType=multipart",
 "href":"https://www.googleapis.com/upload/drive/v3/files?fields=id&uploadType=multipart"},
 "method":"POST",
 "headers":{"Authorization":"Bearer ya29.GlxfB18oVtG6A3j7cXzSq17-RSmj9-2BlQm4zHD5sPzKkfhRM1FxlxUHc9mxWaka1N2fBiTJun-SYLB8ewuc63XVbUo01q0bS2FiS6iJTq9O1h9FQWfoO5r8E6z_6Q",
 "User-Agent":"google-api-nodejs-client/0.10.0","host":"www.googleapis.com",
 "transfer-encoding":"chunked",
 "content-type":"multipart/related;
 boundary=d6cef3f5-2246-5654-ac1f-d00561be5e8a"}
 }

dump the response
 {"id":"0Bw4DMtLCtPMkNERiTnpVNDdQV2c"}

to recap:

how do I get (in Node.js) a google Cloud Vision appropriate URI for a newly created google Drive v3 image file?

how do I get (in Node.js) the metadata for a newly created google Drive v3 image file?

Many thanks.

new information: I have tried a separate drive.files.get()

                drive.files.get({
                  auth: auth,
                  fileId: response.id
                },
                function(err, response) {
                  if (err) {
                  console.log('drive.files.get error: %s %s', err, response);
                  return;
                  } else {
                  // file create success; get properties
                  console.log('get properties\n %s', JSON.stringify(response));
                  }
                });

and I do receive some metadata (but not the big picture), console output, new upload:

get properties
 {"kind":"drive#file","id":"0Bw4DMtLCtPMkWFdTMUVwY2tRZ2c","name":"2017-06-04T17:57:42.189Zlovelock.png","mimeType":"image/png"}


问:
css structural selector :first-child
If i apply following style on the given html below, why it is applying the style on everything inside the body element. I was assuming since the body is NOT the first child of html it should not apply this style onto anything inside body element.

:first-child { color: blue;}

HTML

```<code><html>
    <head>
      <title>Test Page</title>
    </head>
    <style>
        :first-child { color: blue;}
    </style>
    <body>
      <div>
            <h1>This is a H6</h1>
            <p>Carz wtf noice pour uh saiz hoi.</p>
            <p>Oh winz lol wuv donutz yu. Herrow not wut carz pwety oh hornz. </p>
            <p>Bere noze dum cheezeburger oh. Notise hai mikrosoft foots. Dum oh iz nuthing gravy haz nozbody finking. Funnae hai nom winz noze r. </p>
      </div>
      <div>
        <h1>This is an H1</h1>
        <p>Sheeze dum can compewters flowerz. Loike choosday noice nom samez do hornz mac n. Funnae pour hoi dided gravy samez ghoast I.</p>
        <p> U pwety oh haz cat ghoast hai. Taytoes hornz hunnae hai meeeow ghoast.
        </p>

        <h2>This is an h2</h2>
        <p>Sheeze meeeow dum uh dided cat nom hornz wuv. </p>
        <p>Donutz scratchin mac n dum rong ded gravy.</p>
        <p>Thx chz can hoi wtf. Evrybody yu u ded choosday evrybody hai neether. Iz hai dided sheeze bukket noice nozzing chz watzzup?. </p>
        <h2>this is another h2</h2>
        <p>Graet samez iz iz nozbody saiz sheeze oh carz. Jest kitteh not scratchin herrow. Nom scratchin rong saiz ya kitteh haz chz nom. </p>
        <p>Graet gravy gravy mikrosoft. Dided winz cheezeburger finking samez wtf foots. Gravy wut mac n partay noice noze foots. </p>
        <p>Can sink nom compewter ur ded how herrow cat. </p>
      </div>
    </body>
    </html>
</code>```

答:
Since you are not supply an element, id, or class name before your pseudo class :first-child, the application is global. Every first child. Therefore, everything.

You can really notice how this works by using an :nth-child() selector:

:nth-child(4) {
  color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <title>Test Page</title>
</head>

<body>
  <div>
    <h1>This is a H6</h1>
    <p>Carz wtf noice pour uh saiz hoi.</p>
    <p>Oh winz lol wuv donutz yu. Herrow not wut carz pwety oh hornz. </p>
    <p>Bere noze dum cheezeburger oh. Notise hai mikrosoft foots. Dum oh iz nuthing gravy haz nozbody finking. Funnae hai nom winz noze r. </p>
  </div>
  <div>
    <h1>This is an H1</h1>
    <p>Sheeze dum can compewters flowerz. Loike choosday noice nom samez do hornz mac n. Funnae pour hoi dided gravy samez ghoast I.</p>
    <p> U pwety oh haz cat ghoast hai. Taytoes hornz hunnae hai meeeow ghoast.
    </p>

    <h2>This is an h2</h2>
    <p>Sheeze meeeow dum uh dided cat nom hornz wuv. </p>
    <p>Donutz scratchin mac n dum rong ded gravy.</p>
    <p>Thx chz can hoi wtf. Evrybody yu u ded choosday evrybody hai neether. Iz hai dided sheeze bukket noice nozzing chz watzzup?. </p>
    <h2>this is another h2</h2>
    <p>Graet samez iz iz nozbody saiz sheeze oh carz. Jest kitteh not scratchin herrow. Nom scratchin rong saiz ya kitteh haz chz nom. </p>
    <p>Graet gravy gravy mikrosoft. Dided winz cheezeburger finking samez wtf foots. Gravy wut mac n partay noice noze foots. </p>
    <p>Can sink nom compewter ur ded how herrow cat. </p>
  </div>
</body>

</html></code>```

Title: css structural selector :first-child

Body:
If i apply following style on the given html below, why it is applying the style on everything inside the body element. I was assuming since the body is NOT the first child of html it should not apply this style onto anything inside body element.

:first-child { color: blue;}

HTML

      <title>Test Page</title>

This is a H6

Carz wtf noice pour uh saiz hoi.

Oh winz lol wuv donutz yu. Herrow not wut carz pwety oh hornz.

Bere noze dum cheezeburger oh. Notise hai mikrosoft foots. Dum oh iz nuthing gravy haz nozbody finking. Funnae hai nom winz noze r.

This is an H1

Sheeze dum can compewters flowerz. Loike choosday noice nom samez do hornz mac n. Funnae pour hoi dided gravy samez ghoast I.

 U pwety oh haz cat ghoast hai. Taytoes hornz hunnae hai meeeow ghoast.

This is an h2

Sheeze meeeow dum uh dided cat nom hornz wuv.

Donutz scratchin mac n dum rong ded gravy.

Thx chz can hoi wtf. Evrybody yu u ded choosday evrybody hai neether. Iz hai dided sheeze bukket noice nozzing chz watzzup?.

this is another h2

Graet samez iz iz nozbody saiz sheeze oh carz. Jest kitteh not scratchin herrow. Nom scratchin rong saiz ya kitteh haz chz nom.

Graet gravy gravy mikrosoft. Dided winz cheezeburger finking samez wtf foots. Gravy wut mac n partay noice noze foots.

Can sink nom compewter ur ded how herrow cat.

Body:
Since you are not supply an element, id, or class name before your pseudo class :first-child, the application is global. Every first child. Therefore, everything.

You can really notice how this works by using an :nth-child() selector:

:nth-child(4) {
  color: blue;
}

<html>

<head>
  <title>Test Page</title>
</head>

<body>
  <div>
    <h1>This is a H6</h1>
    <p>Carz wtf noice pour uh saiz hoi.</p>
    <p>Oh winz lol wuv donutz yu. Herrow not wut carz pwety oh hornz. </p>
    <p>Bere noze dum cheezeburger oh. Notise hai mikrosoft foots. Dum oh iz nuthing gravy haz nozbody finking. Funnae hai nom winz noze r. </p>
  </div>
  <div>
    <h1>This is an H1</h1>
    <p>Sheeze dum can compewters flowerz. Loike choosday noice nom samez do hornz mac n. Funnae pour hoi dided gravy samez ghoast I.</p>
    <p> U pwety oh haz cat ghoast hai. Taytoes hornz hunnae hai meeeow ghoast.
    </p>

    <h2>This is an h2</h2>
    <p>Sheeze meeeow dum uh dided cat nom hornz wuv. </p>
    <p>Donutz scratchin mac n dum rong ded gravy.</p>
    <p>Thx chz can hoi wtf. Evrybody yu u ded choosday evrybody hai neether. Iz hai dided sheeze bukket noice nozzing chz watzzup?. </p>
    <h2>this is another h2</h2>
    <p>Graet samez iz iz nozbody saiz sheeze oh carz. Jest kitteh not scratchin herrow. Nom scratchin rong saiz ya kitteh haz chz nom. </p>
    <p>Graet gravy gravy mikrosoft. Dided winz cheezeburger finking samez wtf foots. Gravy wut mac n partay noice noze foots. </p>
    <p>Can sink nom compewter ur ded how herrow cat. </p>
  </div>
</body>

</html>


问:
If all my sql server database access is done thru stored procedures
If all my sql server database access is done thru stored procedures, and I plan on continuing that practice, is using linq2sql and/or the entity framework for future projects an unnecessary layer of complexity that doesn't add much value?

Related question: is Microsoft trying to steer developers away from relying on stored procs for data access?

答:
LINQ-to-SQL supports mapping lots of operations (including CRUD) to stored procedures, but you lose composability - i.e. you can't just add (exp).Where(x=>x.IsActive). One option there is table-valued functions (UDFs) in place of stored procedures that query data; this also presents a more rigid meta model (rather than SET FMT_ONLY ON, which is hit'n'miss).

That way, your query methods are composable at the database; but note that Entity Framework does not support this, even though LINQ-to-SQL does.

OwnerDisplayName: E.J. Brennan

OwnerDisplayName: Marc Gravell


问:
How to "transfer" UIImageView between view
when you click "Share" in my app you'll show an ActionSheet like this:

Take photo

Select photo from Library

Cancel

You tap "Take photo" and you'll see an ImagePicker, with "presentModalViewController".
You take a photo and you select "OK" in the ImagePicker.
Here, I want the photo just taken in a new view with other label. Like this:

(new view)
Little photo (just taken)
- Label 1 (ex. Title of photo)
- Label 2 (ex. Location of photo)

and a button "Share" for sharing your photo and its infos.

How can I do this? I'm stopped after take the photo. How can I send my photo (in a imageview) to another view?

Thanks

答:
for this,

make some global varible in appDelegate class and make them property.

for saving Image make UIImage object in app delegate and for title and path make string variables and make all these : property then.

then when you select image from modelView at the selection time you must set app delegate properties(image,title,path).and navigate to other page and on viewWillAppear of new page

set your controls (ImageView and labels) by these objects.

I hope, it helps you. You need to code this logic.


问:
If a certain value is in a certain range, print what ever the value is in java
I am not exactly sure how this is called and how it should be done, but I am learning Java and my assignment is to create a data class that will be able to add days to certain date and subtract and show the difference and so on.
My current issue is that I want to implement a rule for every month of the year, I am sure this can be done differently, but I want to try and do this.

Let us say we are given the date in format Year, month, day. 2017.09.31
I want to check before it is printed if month 09 is allowed to have 31 days.
So I wanted to go and write this:

```<code>if (MM==1 || MM==01);
</code>```

where MM is month, to say that the value of day for MM can be in a range from 1-30, if the number D is in that range print the number D.
Is there any function in Java that lets u use range in this manner?

答:
The way i did this in the end was the following:</p>

```<code>public void setDate (int y, int m, int d){
        YYYY = y;
        MM = ((m>=1 && m<=12) ? m : 1);

        int [] month = {31, 28+(YYYY%4==0?1:0), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        if( d>0 && d<=month[MM-1] ) {
            DD = d;
        } else {
            DD = 1;
        }
</code>```

Body:
I am not exactly sure how this is called and how it should be done, but I am learning Java and my assignment is to create a data class that will be able to add days to certain date and subtract and show the difference and so on.
My current issue is that I want to implement a rule for every month of the year, I am sure this can be done differently, but I want to try and do this.

Let us say we are given the date in format Year, month, day. 2017.09.31
I want to check before it is printed if month 09 is allowed to have 31 days.
So I wanted to go and write this:

if (MM==1 || MM==01);

where MM is month, to say that the value of day for MM can be in a range from 1-30, if the number D is in that range print the number D.
Is there any function in Java that lets u use range in this manner?

Body:
The way i did this in the end was the following:

public void setDate (int y, int m, int d){
        YYYY = y;
        MM = ((m>=1 && m<=12) ? m : 1);

        int [] month = {31, 28+(YYYY%4==0?1:0), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        if( d>0 && d<=month[MM-1] ) {
            DD = d;
        } else {
            DD = 1;
        }


问:
Insert date value in SQL Developer
I tried to create a table to capture temperature

Something like this :

```<code>| Id | TemDate    | Temperature |
|  1 | 2015-01-01 |          10 |
|  2 | 2015-01-02 |          25 |
</code>```

After I created my temperature table, I used

```<code> insert into temperature
 values(1, '2015-01-01', 10);
</code>```

and I got an error message saying: "not a valid month"

So I changed the code to

```<code>insert into temperature
values(1, to_date('2015-01-01', 'yy-mm-dd'), 10);
</code>```

after running the code the result table show tempdate as '01-Jan-2015' instead of '2015-01-01' as shown in the above table

I tired to used this code to fix the problem

```<code>insert into temperature
values(1, to_date ('2015-Jan-01','yy-mm-dd'), 10);
</code>```

but I still got '01-Jan-2015' not '2015-01-01'

How can I insert the date into the table so I can have the same format that look like '2015-01-01'? Thanks for the help!

答:
First, when inserting data into a table, provide the column names.

Second, in Oracle, you can use the date keyword and ISO standard dates:

```<code>insert into temperature(col1, col2, col3)  -- whatever they are
    values(1, date '2015-01-01', 10);
</code>```

This, when you query this, you are going to get the date in Oracle's "presentation" format.  If you want it in another format, use to_char():

```<code>select to_char(datecol, 'YYYY-MM-DD')
</code>```

Title: Insert date value in SQL Developer

Body:
I tried to create a table to capture temperature

Something like this :

| Id | TemDate    | Temperature |
|  1 | 2015-01-01 |          10 |
|  2 | 2015-01-02 |          25 |

After I created my temperature table, I used

 insert into temperature
 values(1, '2015-01-01', 10);

and I got an error message saying: "not a valid month"

So I changed the code to

insert into temperature
values(1, to_date('2015-01-01', 'yy-mm-dd'), 10);

after running the code the result table show tempdate as '01-Jan-2015' instead of '2015-01-01' as shown in the above table

I tired to used this code to fix the problem

insert into temperature
values(1, to_date ('2015-Jan-01','yy-mm-dd'), 10);

but I still got '01-Jan-2015' not '2015-01-01'

How can I insert the date into the table so I can have the same format that look like '2015-01-01'? Thanks for the help!

Body:
First, when inserting data into a table, provide the column names.

Second, in Oracle, you can use the date keyword and ISO standard dates:

insert into temperature(col1, col2, col3)  -- whatever they are
    values(1, date '2015-01-01', 10);

This, when you query this, you are going to get the date in Oracle's "presentation" format.  If you want it in another format, use to_char():

select to_char(datecol, 'YYYY-MM-DD')


问:
Why does this google app script taking forever to run? What is slowing it down?
Why does this code taking forever to run? What is slowing it down?

```<code>function Refresh(e){
     var e=SpreadsheetApp.getActiveSpreadsheet();
     var formulaSheet = e.getSheetByName("John");
     var formulaCell = formulaSheet.getRange(2,5);
     formulaCell.setValue(formulaCell.getFormula().replace("USD","USE"));
     formulaCell.setValue(formulaCell.getFormula().replace("USE","USD"));
</code>```

}

答: Something was wrong my browser, I cleared cache and it is much quicker now</p>

Body:
Why does this code taking forever to run? What is slowing it down?

function Refresh(e){
     var e=SpreadsheetApp.getActiveSpreadsheet();
     var formulaSheet = e.getSheetByName("John");
     var formulaCell = formulaSheet.getRange(2,5);
     formulaCell.setValue(formulaCell.getFormula().replace("USD","USE"));
     formulaCell.setValue(formulaCell.getFormula().replace("USE","USD"));

}