问:
Firebase for iOS error when uploading an image: object does not exist
I am trying to upload an image to firebase storage, but I am getting this error after selecting an image from photo library and before clicking “choose” button:

“Creating an image format with an unknown type is an error”

Also I am getting “object does not exist” after clicking “upload” button.

Here's my code:

```<code>import UIKit
import Firebase
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase

class uploadVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    @IBOutlet weak var imgPost: UIImageView!
    @IBOutlet weak var txtPost: UITextView!
    var uuid = NSUUID().uuidString

    override func viewDidLoad() {
        super.viewDidLoad()

        imgPost.isUserInteractionEnabled = true
        let gestureRecognizer = UITapGestureRecognizer(target: self,
        action: #selector(uploadVC.selectImage))
        imgPost.addGestureRecognizer(gestureRecognizer)
    }

    func selectImage() {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = .photoLibrary
        picker.allowsEditing = true
        present(picker, animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController,
        didFinishPickingMediaWithInfo info: [String : Any]) {
        imgPost.image = info[UIImagePickerControllerEditedImage] as?
        UIImage
        self.dismiss(animated: true, completion: nil)
    }

    @IBAction func btnUpload(_ sender: Any) {
        let mediaFolder = Storage().reference().child("media")
        if let data = UIImageJPEGRepresentation(imgPost.image!, 0.5) {
            mediaFolder.child("\(uuid).jpg").putData(data, metadata: nil,
            completion: { (metadata, error) in
                if error != nil {
                    let alert = UIAlertController(title: "Error", message:
                    error?.localizedDescription, preferredStyle:
                    UIAlertControllerStyle.alert)
                    let ok = UIAlertAction(title: "OK", style:
                    UIAlertActionStyle.cancel, handler: nil)
                    alert.addAction(ok)
                    self.present(alert, animated: true, completion: nil)
                } else {
                    print(metadata?.downloadURL()?.absoluteString)
                }
            })
        }
    }
}
</code>```

答:
I just figured out how it works.
According to Firebase storage sample with swift 3, the storage requires authentication first.

Reference: Firebase GitHub example

```<code>import UIKit
import Photos
import Firebase
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase

class uploadVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var imgPost: UIImageView!
    @IBOutlet weak var txtPost: UITextView!

    var uuid = NSUUID().uuidString
    var storageRef: StorageReference!
    var imageFile: URL?
    var filePath: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        // [START configurestorage]
        storageRef = Storage.storage().reference()
        // [END configurestorage]

        // [START storageauth]
        // Using Cloud Storage for Firebase requires the user be authenticated. Here we are using
        // anonymous authentication.
        if Auth.auth().currentUser == nil {
            Auth.auth().signInAnonymously(completion: { (user: User?, error: Error?) in
                if let error = error {
                    let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
                    let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
                    alert.addAction(ok)
                    self.present(alert, animated: true, completion: nil)
                }
            })
        }
        // [END storageauth]

        imgPost.isUserInteractionEnabled = true
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(uploadVC.selectImage))
        imgPost.addGestureRecognizer(gestureRecognizer)
    }

    func selectImage() {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = .photoLibrary
        picker.allowsEditing = true
        present(picker, animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        imgPost.image = info[UIImagePickerControllerEditedImage] as? UIImage
        picker.dismiss(animated: true, completion:nil)
        if #available(iOS 8.0, *), let referenceUrl = info[UIImagePickerControllerReferenceURL] as? URL {
            let assets = PHAsset.fetchAssets(withALAssetURLs: [referenceUrl], options: nil)
            let asset = assets.firstObject
            asset?.requestContentEditingInput(with: nil, completionHandler: { (contentEditingInput, info) in
                self.imageFile = contentEditingInput?.fullSizeImageURL
                self.filePath = "media/" + "\(self.uuid).jpg"
            })
        }
    }

    @IBAction func btnUpload(_ sender: Any) {
        // [START uploadimage]
        self.storageRef.child(filePath!)
            .putFile(from: imageFile!, metadata: nil) { (metadata, error) in
                if let error = error {
                    let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
                    let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
                    alert.addAction(ok)
                    self.present(alert, animated: true, completion: nil)
                    return
                }
                print(metadata?.downloadURL()?.absoluteString ?? "nothing")
        }
        // [END uploadimage]
    }
}
</code>```

Body:
I am trying to upload an image to firebase storage, but I am getting this error after selecting an image from photo library and before clicking “choose” button:

“Creating an image format with an unknown type is an error”

Also I am getting “object does not exist” after clicking “upload” button.

Here's my code:

import UIKit
import Firebase
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase

class uploadVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    @IBOutlet weak var imgPost: UIImageView!
    @IBOutlet weak var txtPost: UITextView!
    var uuid = NSUUID().uuidString

    override func viewDidLoad() {
        super.viewDidLoad()

        imgPost.isUserInteractionEnabled = true
        let gestureRecognizer = UITapGestureRecognizer(target: self,
        action: #selector(uploadVC.selectImage))
        imgPost.addGestureRecognizer(gestureRecognizer)
    }

    func selectImage() {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = .photoLibrary
        picker.allowsEditing = true
        present(picker, animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController,
        didFinishPickingMediaWithInfo info: [String : Any]) {
        imgPost.image = info[UIImagePickerControllerEditedImage] as?
        UIImage
        self.dismiss(animated: true, completion: nil)
    }

    @IBAction func btnUpload(_ sender: Any) {
        let mediaFolder = Storage().reference().child("media")
        if let data = UIImageJPEGRepresentation(imgPost.image!, 0.5) {
            mediaFolder.child("\(uuid).jpg").putData(data, metadata: nil,
            completion: { (metadata, error) in
                if error != nil {
                    let alert = UIAlertController(title: "Error", message:
                    error?.localizedDescription, preferredStyle:
                    UIAlertControllerStyle.alert)
                    let ok = UIAlertAction(title: "OK", style:
                    UIAlertActionStyle.cancel, handler: nil)
                    alert.addAction(ok)
                    self.present(alert, animated: true, completion: nil)
                } else {
                    print(metadata?.downloadURL()?.absoluteString)
                }
            })
        }
    }
}

Body:
I just figured out how it works.
According to Firebase storage sample with swift 3, the storage requires authentication first.

Reference: Firebase GitHub example

import UIKit
import Photos
import Firebase
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase

class uploadVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var imgPost: UIImageView!
    @IBOutlet weak var txtPost: UITextView!

    var uuid = NSUUID().uuidString
    var storageRef: StorageReference!
    var imageFile: URL?
    var filePath: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        // [START configurestorage]
        storageRef = Storage.storage().reference()
        // [END configurestorage]

        // [START storageauth]
        // Using Cloud Storage for Firebase requires the user be authenticated. Here we are using
        // anonymous authentication.
        if Auth.auth().currentUser == nil {
            Auth.auth().signInAnonymously(completion: { (user: User?, error: Error?) in
                if let error = error {
                    let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
                    let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
                    alert.addAction(ok)
                    self.present(alert, animated: true, completion: nil)
                }
            })
        }
        // [END storageauth]

        imgPost.isUserInteractionEnabled = true
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(uploadVC.selectImage))
        imgPost.addGestureRecognizer(gestureRecognizer)
    }

    func selectImage() {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = .photoLibrary
        picker.allowsEditing = true
        present(picker, animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        imgPost.image = info[UIImagePickerControllerEditedImage] as? UIImage
        picker.dismiss(animated: true, completion:nil)
        if #available(iOS 8.0, *), let referenceUrl = info[UIImagePickerControllerReferenceURL] as? URL {
            let assets = PHAsset.fetchAssets(withALAssetURLs: [referenceUrl], options: nil)
            let asset = assets.firstObject
            asset?.requestContentEditingInput(with: nil, completionHandler: { (contentEditingInput, info) in
                self.imageFile = contentEditingInput?.fullSizeImageURL
                self.filePath = "media/" + "\(self.uuid).jpg"
            })
        }
    }

    @IBAction func btnUpload(_ sender: Any) {
        // [START uploadimage]
        self.storageRef.child(filePath!)
            .putFile(from: imageFile!, metadata: nil) { (metadata, error) in
                if let error = error {
                    let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
                    let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
                    alert.addAction(ok)
                    self.present(alert, animated: true, completion: nil)
                    return
                }
                print(metadata?.downloadURL()?.absoluteString ?? "nothing")
        }
        // [END uploadimage]
    }
}


来源: stackexchange

问:
React Native ListView onEndReached keeps firing
For some reason that I don't understand, my ListView keeps firing even though it's at the top of the scroll, I need to wrap it inside a ScrollView because I want my ToolBar to hide when the user scrolls down in the ListView as well.

This is the render() method's content:

```<code><ScrollView>
    <ActivityContainer>
      <ListView
        onEndReachedThreshold={100}
        pageSize={10}
        initialListSize={20}
        onEndReached={() => {
                        console.log("fired"); // keeps firing
                      }}
        enableEmptySections={true}/>
    </ActivityContainer>
</ScrollView>
</code>```

Also tried wrapping the Whole thing in a view like this:

```<code><ScrollView>
   <View>
    <ActivityContainer>
      <ListView
        onEndReachedThreshold={100}
        pageSize={10}
        initialListSize={20}
        onEndReached={() => {
                        console.log("fired"); // keeps firing
                      }}
        enableEmptySections={true}/>
    </ActivityContainer>
   </View>
</ScrollView>
</code>```

Edit: I don't need renderHeader because I'm trying to scroll through everything on top of the ListView, it has many components and views and child views, not the header of the list view.

答:
Use a hash for paging in ListView when > 1 column

Currently, I'm on React Native v44 but haven't tried latest version.

In your constructor try this...

```<code>constructor(props) {
  this.pagesLoaded = {}
  this.currentPage = 1
  // etc
}
</code>```

Then in your data fetching method try this...

```<code>getData() {
  if (this.pagesLoaded[this.state.currentPage]) return
  this.pagesLoaded[this.state.currentPage] = true
  // fetch data
}
</code>```

This way when onEndReached is over-fired, it won't matter. This seems like a bug in ListView as I had set the dimensions around it and did not have it within a ScrollView so it was happening purely within the component, even if setting getItemLayout prop.

ContentLicense: CC BY-SA 3.0

Body:
For some reason that I don't understand, my ListView keeps firing even though it's at the top of the scroll, I need to wrap it inside a ScrollView because I want my ToolBar to hide when the user scrolls down in the ListView as well.

This is the render() method's content:

<ScrollView>
    <ActivityContainer>
      <ListView
        onEndReachedThreshold={100}
        pageSize={10}
        initialListSize={20}
        onEndReached={() => {
                        console.log("fired"); // keeps firing
                      }}
        enableEmptySections={true}/>
    </ActivityContainer>
</ScrollView>

Also tried wrapping the Whole thing in a view like this:

<ScrollView>
   <View>
    <ActivityContainer>
      <ListView
        onEndReachedThreshold={100}
        pageSize={10}
        initialListSize={20}
        onEndReached={() => {
                        console.log("fired"); // keeps firing
                      }}
        enableEmptySections={true}/>
    </ActivityContainer>
   </View>
</ScrollView>

Edit: I don't need renderHeader because I'm trying to scroll through everything on top of the ListView, it has many components and views and child views, not the header of the list view.

Body:
Use a hash for paging in ListView when > 1 column

Currently, I'm on React Native v44 but haven't tried latest version.

In your constructor try this...

constructor(props) {
  this.pagesLoaded = {}
  this.currentPage = 1
  // etc
}

Then in your data fetching method try this...

getData() {
  if (this.pagesLoaded[this.state.currentPage]) return
  this.pagesLoaded[this.state.currentPage] = true
  // fetch data
}

This way when onEndReached is over-fired, it won't matter. This seems like a bug in ListView as I had set the dimensions around it and did not have it within a ScrollView so it was happening purely within the component, even if setting getItemLayout prop.


问:
Syntax highlighting with C#?
I installed the last version of Rider to replace Visual Studio that cannot handle the solution (C# solution) I work with:

Rider 2017.1 EAP
Build #RS-171.4456.575, built on June 16, 2017
Rider EAP User
Expiration date: July 16, 2017
JRE: 1.8.0_112-release-736-b17 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 7 6.1
```

At first launch, I chose the dark window and the ReSharper dark theme; and then I opened the solution. The issue is that there is very few syntax highlighting: comments are in green, some keyword in blue (but partial is not colored, for example), and that is all. The names of classes are in same color as the rest (white) albeit all seems correctly configured in the Configuration window.

What can be the problem? Maybe the syntax highlighting is not yet implemented? Everything else work fine, I can find usage, go to declaration, etc. but the lack of coloration is a little bit annoying.

I specify that no color theme brings the full syntax highlighting.

答: In File -> Settings -> Editor -> Inspection Settings you can turn of color higlighting, maybe it is off? You can also change your color in the preferences at Editor -> Color and Fonts -> General in the drop down menu, maybe there is another scheme that fits you better.

Title: Syntax highlighting with C#?

Body:
I installed the last version of Rider to replace Visual Studio that cannot handle the solution (C# solution) I work with:

Rider 2017.1 EAP
Build #RS-171.4456.575, built on June 16, 2017
Rider EAP User
Expiration date: July 16, 2017
JRE: 1.8.0_112-release-736-b17 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 7 6.1

At first launch, I chose the dark window and the ReSharper dark theme; and then I opened the solution. The issue is that there is very few syntax highlighting: comments are in green, some keyword in blue (but partial is not colored, for example), and that is all. The names of classes are in same color as the rest (white) albeit all seems correctly configured in the Configuration window.

What can be the problem? Maybe the syntax highlighting is not yet implemented? Everything else work fine, I can find usage, go to declaration, etc. but the lack of coloration is a little bit annoying.

I specify that no color theme brings the full syntax highlighting.


问:
Validate dates in XML Document before writing to database
I'm currently getting user input from a very large form as an XML document. I'd like to validate this XML document against a schema before any database related operations. The problem is that users input dates according to their own preferences (US standard, ISO standard, etc.) and the database expects dates to be ISO standard. Is there anyway I can validate this XML document and change the dates to ISO format before adding it to the database? I'm using Perl for the back-end, any libraries that can help me do the same?

Cheers,

答:
There is Data::Validate::XSD with which I do not have any experience.

In the past, I did use XML::LibXML::Schema.

I would traverse the document, converting all dates using DateTime::Format::XSD (in conjunction with DateTime) and then attempt to validate.

ContentLicense: CC BY-SA 2.5


问:
How to convert RGB PIL image to numpy array with 3 channels?
I am loading image with the following code

```<code>image = PIL.Image.open(file_path)
image = np.array(image)
</code>```

It works, but the size of array appears to be (X, X, 4), i.e. it has 4 layers. I would like normal RGB layers. Is it possible?

UPDATE

I found that just removing 4th channel is unsufficcient. The following code was required:

```<code>image = PIL.Image.open(file_path)
image.thumbnail(resample_size)
image = image.convert("RGB")
image = np.asarray(image, dtype=np.float32) / 255
image = image[:, :, :3]
</code>```

Why?

答:
The fourth  layer is the transparency value for image formats that support transparency, like PNG.  If you remove the 4th value it'll be a correct RGB image without transparency.

EDIT:

Example:

```<code>>>> import PIL.Image
>>> image = PIL.Image.open('../test.png')
>>> import numpy as np
>>> image = np.array(image)
>>> image.shape
(381, 538, 4)
>>> image[...,:3].shape
(381, 538, 3)
</code>```

Body:
I am loading image with the following code

image = PIL.Image.open(file_path)
image = np.array(image)

It works, but the size of array appears to be (X, X, 4), i.e. it has 4 layers. I would like normal RGB layers. Is it possible?

UPDATE

I found that just removing 4th channel is unsufficcient. The following code was required:

image = PIL.Image.open(file_path)
image.thumbnail(resample_size)
image = image.convert("RGB")
image = np.asarray(image, dtype=np.float32) / 255
image = image[:, :, :3]

Why?

Body:
The fourth  layer is the transparency value for image formats that support transparency, like PNG.  If you remove the 4th value it'll be a correct RGB image without transparency.

EDIT:

Example:

>>> import PIL.Image
>>> image = PIL.Image.open('../test.png')
>>> import numpy as np
>>> image = np.array(image)
>>> image.shape
(381, 538, 4)
>>> image[...,:3].shape
(381, 538, 3)


问:
How to use gst-launch to streaming mp4 audio and video via rtp and play it?
I use these commands to send and recieve rtp data:

Send rtp data to UDP port 5000

```<code>gst-launch-1.0 -v filesrc location = haizeiwang.mp4 ! decodebin ! x264enc ! rtph264pay ! udpsink host=192.168.1.101 port=5000
</code>```

Receive rtp data from udp port 5000 and play it.

```<code>gst-launch-1.0 -v udpsrc port=5000 caps="application/x-rtp, media=video, clock-rate=90000, encoding-name=H264, payload=96, ssrc=3394826012, timestamp-offset=2215812541, seqnum-offset=46353" ! rtph264depay ! decodebin ! videoconvert ! autovideosink sync=false
</code>```

But i can only get vedio(not very clear) , and there is no sound. Could i get vedio and audio at the same time?  Which elememnts should i use? What the commands should be?

Thank you.

答:
Sender (audio+video):

```<code>gst-launch-1.0 -v uridecodebin name=uridec uri=file:///C:\\video.mp4 ! videoconvert ! x264enc noise-reduction=10000 tune=zerolatency byte-stream=true threads=4 key-int-max=15 intra-refresh=true ! mpegtsmux alignment=7 name=mux ! rtpmp2tpay ! queue ! udpsink host=127.0.0.1 port=5000 sync=true uridec. ! audioconvert ! voaacenc ! audio/mpeg ! queue ! mux.
</code>```

Receiver (audio+video, short version):

```<code>gst-launch-1.0 -v playbin uri=udp://127.0.0.1:5000
</code>```

Receiver (audio+video, long version):

```<code>gst-launch-1.0 -v udpsrc port=5000 ! tsparse ! decodebin name=dec ! videoconvert ! autovideosink sync=true dec. ! queue ! audioconvert ! audioresample ! autoaudiosink sync=true
</code>```

If you have access to VLC via cmd-line, you can play the stream with:

```<code>vlc rtp://@:5000
</code>```

Or just go to VLC graphical interface to Open Network Stream (CTRL+N) and use the address I shared above.

Body:
I use these commands to send and recieve rtp data:

Send rtp data to UDP port 5000

gst-launch-1.0 -v filesrc location = haizeiwang.mp4 ! decodebin ! x264enc ! rtph264pay ! udpsink host=192.168.1.101 port=5000

Receive rtp data from udp port 5000 and play it.

gst-launch-1.0 -v udpsrc port=5000 caps="application/x-rtp, media=video, clock-rate=90000, encoding-name=H264, payload=96, ssrc=3394826012, timestamp-offset=2215812541, seqnum-offset=46353" ! rtph264depay ! decodebin ! videoconvert ! autovideosink sync=false

But i can only get vedio(not very clear) , and there is no sound. Could i get vedio and audio at the same time?  Which elememnts should i use? What the commands should be?

Thank you.

Body:
Sender (audio+video):

gst-launch-1.0 -v uridecodebin name=uridec uri=file:///C:\\video.mp4 ! videoconvert ! x264enc noise-reduction=10000 tune=zerolatency byte-stream=true threads=4 key-int-max=15 intra-refresh=true ! mpegtsmux alignment=7 name=mux ! rtpmp2tpay ! queue ! udpsink host=127.0.0.1 port=5000 sync=true uridec. ! audioconvert ! voaacenc ! audio/mpeg ! queue ! mux.

Receiver (audio+video, short version):

gst-launch-1.0 -v playbin uri=udp://127.0.0.1:5000

Receiver (audio+video, long version):

gst-launch-1.0 -v udpsrc port=5000 ! tsparse ! decodebin name=dec ! videoconvert ! autovideosink sync=true dec. ! queue ! audioconvert ! audioresample ! autoaudiosink sync=true

If you have access to VLC via cmd-line, you can play the stream with:

vlc rtp://@:5000

Or just go to VLC graphical interface to Open Network Stream (CTRL+N) and use the address I shared above.


问:
Gradle Android Unit Tests with module dependency leads to NoClassDefFoundError
I am struggling with a JUnit run configuration.

Module A

main

Module B

main

tests

Module B uses Module A

I am trying to run unit tests in Module B. I have a dependency defined in build.gradle of Module B

```<code>compile project(':moduleA')
</code>```

It works fine in Android Studio, but when I want to get it running with gradle command line:

```<code>gradlew :moduleB:testDebugUnitTest
</code>```

It leads to failure for some tests with java.lang.NoClassDefFoundError, so I guess it cannot find the classes in Module A. I've checked the /build/intermediates/classes folder and the compiled classes are there. I've also tried to add a test dependency:

```<code>testCompile project(':moduleA')
</code>```

But it did not make any difference. I also tried to clean/rebuild and run on two machines. Build with gradle plugin 1.5 and gradle 2.9 and 2.11.

答: Are you sure you do not have Proguard enabled for you build?</p>

Body:
I am struggling with a JUnit run configuration.

Module A

main

Module B

main

tests

Module B uses Module A

I am trying to run unit tests in Module B. I have a dependency defined in build.gradle of Module B

compile project(':moduleA')

It works fine in Android Studio, but when I want to get it running with gradle command line:

gradlew :moduleB:testDebugUnitTest

It leads to failure for some tests with java.lang.NoClassDefFoundError, so I guess it cannot find the classes in Module A. I've checked the /build/intermediates/classes folder and the compiled classes are there. I've also tried to add a test dependency:

testCompile project(':moduleA')

But it did not make any difference. I also tried to clean/rebuild and run on two machines. Build with gradle plugin 1.5 and gradle 2.9 and 2.11.


问:
VueJS: what does an html attribute prefixed with a colon signify?
Example:

```<code><vue-select
  class="vue-select1"
  name="select1"
  :options="options1"
  :model.sync="result1"
></vue-select>
</code>```

What is the meaning the colon in front of :options and :model.sync here? I've searched all over the internet and can't find an answer anywhere.

Example seen here: https://github.com/Haixing-Hu/vue-select

答:
In a Vue template, a colon : prefixing an html attribute is shorthand for v-bind.

Here's the full documentation for v-bind.

ContentLicense: CC BY-SA 4.0

Body:
Example:

<vue-select
  class="vue-select1"
  name="select1"
  :options="options1"
  :model.sync="result1"
></vue-select>

What is the meaning the colon in front of :options and :model.sync here? I've searched all over the internet and can't find an answer anywhere.

Example seen here: https://github.com/Haixing-Hu/vue-select


问:
How to generate sequence number for members of each group
I have a table that is similar to this:

```<code>CREATE TABLE dbo.ReportGroups (
    ReportName     VARCHAR(50)    NOT NULL,
    GroupName      VARCHAR(50)    NOT NULL,
    SequenceNumber SMALLINT       NOT NULL,
    CONSTRAINT PK_ReportGroups PRIMARY KEY CLUSTERED (ReportName, GroupName)
)
</code>```

I'm importing into this table from a flat file that just contains the report names and group names, so I need to generate the SequenceNumber. For each report the sequence numbers should restart at 1.

I've seen how to do this with a script task for normal sequence numbers, but restarting for each new report name doesn't seem to be out there. My guess is that I'll need to use the Sort transform and then add code to check for changes in the report name(?) Has anyone done something like this? Any sample code to share?

答:
As I suspected, this was possible by adding a Sort transformation and then adjusting the Script transform. I added the Sort on ReportName->GroupName then added the following code to a Script transform:

```<code>public class ScriptMain : UserComponent
{
    short seqNum;
    string reportName;

    public override void PreExecute()
    {
        base.PreExecute();

        seqNum = 0;
        reportName = "";
    }

    public override void PostExecute()
    {
        base.PostExecute();
    }

    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        if (Row.MapName != reportName)
        {
            reportName = Row.MapName;
            seqNum = 1;
        }
        else
            seqNum++;

        Row.SequenceNumber = seqNum;
    }
}
</code>```

I've stripped out the help and comments to make the code a bit more condensed and readable on here.

Body:
I have a table that is similar to this:

CREATE TABLE dbo.ReportGroups (
    ReportName     VARCHAR(50)    NOT NULL,
    GroupName      VARCHAR(50)    NOT NULL,
    SequenceNumber SMALLINT       NOT NULL,
    CONSTRAINT PK_ReportGroups PRIMARY KEY CLUSTERED (ReportName, GroupName)
)

I'm importing into this table from a flat file that just contains the report names and group names, so I need to generate the SequenceNumber. For each report the sequence numbers should restart at 1.

I've seen how to do this with a script task for normal sequence numbers, but restarting for each new report name doesn't seem to be out there. My guess is that I'll need to use the Sort transform and then add code to check for changes in the report name(?) Has anyone done something like this? Any sample code to share?

Body:
As I suspected, this was possible by adding a Sort transformation and then adjusting the Script transform. I added the Sort on ReportName->GroupName then added the following code to a Script transform:

public class ScriptMain : UserComponent
{
    short seqNum;
    string reportName;

    public override void PreExecute()
    {
        base.PreExecute();

        seqNum = 0;
        reportName = "";
    }

    public override void PostExecute()
    {
        base.PostExecute();
    }

    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        if (Row.MapName != reportName)
        {
            reportName = Row.MapName;
            seqNum = 1;
        }
        else
            seqNum++;

        Row.SequenceNumber = seqNum;
    }
}

I've stripped out the help and comments to make the code a bit more condensed and readable on here.


问:
Visual Studio SSDT Data Compare how to compare two tables in a single database
Trying to do something simple Data Compare in SSDT but proving a bit hard.

In one database, I have two tables I want to compare.

These tables have the same schema, just different table names. And I just want to see if this tool will give me a nice way to compare the data in both.

I.e.

```<code>tblOutput
tblOutput_210314
</code>```

But this picking of two tables to compare against each other in a single database I can't see how to achieve.

Seems like you can only pick a table name which exists in both source and target databases. Since my source and target database is the same, I am basically comparing my table to itself ?

Anyone know of a way to achieve this with Data Compare ?

Visual Studio 2012

SQL Server Data Tools

Data Compare

答:
A work around for the tool limitation. If you have two tables with columns in common that need to be compared. One solution requires duplicating the database and comparing views.

For this example we have a database called CoffeeTableBooksDatabase with two tables, table_myBooks and table_aFriendsBooks with common columns authors and titles that need to be compared.

Duplicate the database with backup then do a restore:

Backup the Database (ex: CoffeeTableBooksDatabase)

Restore the Database with a different name (ex: AnotherCoffeeTableBooksDatabase)

Create a common view:

Create a view (ex: view_SomeBooks) with the same name in both databases

In the original database (ex: CoffeeTableBooksDatabase), add the first table (ex: table_myBooks) to the view (ex: view_SomeBooks) with all the columns common to both tables (ex: authors and titles)

In the duplicate database (ex: AnotherCoffeeTableBooksDatabase), add the second table (ex: table_aFriendsBooks) to the view (ex: view_SomeBooks) with all the columns common to both tables (ex: authors and titles)

Now you can compare both databases by just looking at the views comparison. This is not a recommended solution but it works using the tool and its current limitations.

Body:
Trying to do something simple Data Compare in SSDT but proving a bit hard.

In one database, I have two tables I want to compare.

These tables have the same schema, just different table names. And I just want to see if this tool will give me a nice way to compare the data in both.

I.e.

tblOutput
tblOutput_210314

But this picking of two tables to compare against each other in a single database I can't see how to achieve.

Seems like you can only pick a table name which exists in both source and target databases. Since my source and target database is the same, I am basically comparing my table to itself ?

Anyone know of a way to achieve this with Data Compare ?

Visual Studio 2012

SQL Server Data Tools

Data Compare


问:
Excel VBA: Storing the Value of One Cell in a Variable if a Certain Value Exists in the Same Column
I'm trying to determine how to store the value of a cell in a variable if a certain value exists in the same column. See the explanation below:

Example Table

So for example, I have a database storing whether an individual enjoys a certain fruit or not. What I want to happen is that for each person, going row by row in myRange (where myRange = "B" i & ":E" & i) if the cell is = Chr(13) & Chr(7) then store the value of the header in a variable (i.e. "Apple", "Grape", Banana", "Orange").

This is what I have right now as a snippet:

```<code>For i = 7 To iLastRow
    Set oCell = myRange.Find(What:=Chr(13) & Chr(7), LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, :=False, SearchFormat:=False)

    If oCell = Chr(13) & Chr(7) Then
        value = "DONT KNOW WHAT TO PUT HERE BUT IT WILL REFERENCE TO THE
                ITEMS 'Apple', 'Grape','Banana', 'Orange' DEPENDING ON WHICH
                COLUMN THE BLANK IS FOUND IN"
        sTemp = sTemp & "," & value
    Else
        Set oCell = Nothing
    End If
Next i
sTemp = Mid(sTemp, 2)
</code>```

答:
Here's one alternative using a loop in loop that gives a msgbox result as:

"Joe likes Orange,
James likes Apple, Banana, Grape,
John likes Apple, Banana, Orange,
Jack likes Apple, Grape,"

```<code>Sub what()
Dim P As String: Dim X As String: Dim S As String
Dim i As Integer: Dim j As Integer: Dim iLastRow As Integer
With ThisWorkbook.Worksheets("Sheet3")
    iLastRow = 10
    For i = 7 To iLastRow
        P = .Cells(i, 1).Value2
        For j = 2 To 5
            If .Cells(i, j).Value = "Y" Then
                V = .Cells(6, j).Value
                S = S & V & ", "
            End If
        Next j
        X = P & " likes " & S & vbNewLine & X
        S = ""
    Next i
End With
MsgBox X
End Sub
</code>```

Body:
I'm trying to determine how to store the value of a cell in a variable if a certain value exists in the same column. See the explanation below:

Example Table

So for example, I have a database storing whether an individual enjoys a certain fruit or not. What I want to happen is that for each person, going row by row in myRange (where myRange = "B" i & ":E" & i) if the cell is = Chr(13) & Chr(7) then store the value of the header in a variable (i.e. "Apple", "Grape", Banana", "Orange").

This is what I have right now as a snippet:

For i = 7 To iLastRow
    Set oCell = myRange.Find(What:=Chr(13) & Chr(7), LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, :=False, SearchFormat:=False)

    If oCell = Chr(13) & Chr(7) Then
        value = "DONT KNOW WHAT TO PUT HERE BUT IT WILL REFERENCE TO THE
                ITEMS 'Apple', 'Grape','Banana', 'Orange' DEPENDING ON WHICH
                COLUMN THE BLANK IS FOUND IN"
        sTemp = sTemp & "," & value
    Else
        Set oCell = Nothing
    End If
Next i
sTemp = Mid(sTemp, 2)

Body:
Here's one alternative using a loop in loop that gives a msgbox result as:

"Joe likes Orange,
James likes Apple, Banana, Grape,
John likes Apple, Banana, Orange,
Jack likes Apple, Grape,"

Sub what()
Dim P As String: Dim X As String: Dim S As String
Dim i As Integer: Dim j As Integer: Dim iLastRow As Integer
With ThisWorkbook.Worksheets("Sheet3")
    iLastRow = 10
    For i = 7 To iLastRow
        P = .Cells(i, 1).Value2
        For j = 2 To 5
            If .Cells(i, j).Value = "Y" Then
                V = .Cells(6, j).Value
                S = S & V & ", "
            End If
        Next j
        X = P & " likes " & S & vbNewLine & X
        S = ""
    Next i
End With
MsgBox X
End Sub


问:
JSON duplicated object
I am getting data from a json that I'd like to display as text for buttons, however, what I'm getting is duplicated buttons on top of each other. What ever I do, can't seem to resolve it. This is the function:

```<code>function initPlaylist() {

    //Get the playlists data from JSON
    $.get('json/playlists.json', function(data) {

        data.forEach(function(playlist) {

            //Create div for each playlist and populate it
            var album = $('<div>', {class: 'pl-singular-playlist'}).appendTo(playlistsContainer);

            //Playlist image
            $('<img>', {src: playlist.image}).appendTo(album);

            //Playlist button
            $('<button>', {
                'data-id': playlist.id,
                text: playlist.name,
                class: 'pl-play-button',
                click: function (e) {

                    //Show image in music player
                    $('<img>', {
                        src: playlist.image,
                        id: 'pl-selected-image'
                    }).appendTo(playerContainer);

                    //Set background image for the music player container
                    $(mainContainer).css('background-image', 'url(' + playlist.image + ')');
                    $(mainContainer).css('background-size', 'cover');
                    $(mainContainer).css('background-repeat', 'no-repeat');
                    $(mainContainer).css('background-position', 'center');

                    initAudio(e.currentTarget.dataset.id);
                }
            }).appendTo('.pl-singular-playlist');
        })
    })
}
</code>```

This is the project I currently have so you could see how it looks (buttons show on hover):

https://aviadweiss.github.io/playlists/

Would appreciate your help

答:
I think you want .appendTo(div); at the bottom.

As it stands, you're appending each button to all elements with the class pl-singular-playlist.

Title: JSON duplicated object

Body:
I am getting data from a json that I'd like to display as text for buttons, however, what I'm getting is duplicated buttons on top of each other. What ever I do, can't seem to resolve it. This is the function:

function initPlaylist() {

    //Get the playlists data from JSON
    $.get('json/playlists.json', function(data) {

        data.forEach(function(playlist) {

            //Create div for each playlist and populate it
            var album = $('
', {class: 'pl-singular-playlist'}).appendTo(playlistsContainer);

            //Playlist image
            $('', {src: playlist.image}).appendTo(album);

            //Playlist button
            $('<button>', {
                'data-id': playlist.id,
                text: playlist.name,
                class: 'pl-play-button',
                click: function (e) {

                    //Show image in music player
                    $('', {
                        src: playlist.image,
                        id: 'pl-selected-image'
                    }).appendTo(playerContainer);

                    //Set background image for the music player container
                    $(mainContainer).css('background-image', 'url(' + playlist.image + ')');
                    $(mainContainer).css('background-size', 'cover');
                    $(mainContainer).css('background-repeat', 'no-repeat');
                    $(mainContainer).css('background-position', 'center');

                    initAudio(e.currentTarget.dataset.id);
                }
            }).appendTo('.pl-singular-playlist');
        })
    })
}

This is the project I currently have so you could see how it looks (buttons show on hover):

https://aviadweiss.github.io/playlists/

Would appreciate your help


问:
big query limit and skip results for pagination
Im setting up queries from bigquery using the php library. but with out the limit on the query itself I get this response "The query has not completed yet.", its around 10k or more, but my pages should limit by 50 anyways. how to setup pagination on bigquery, that I do skip,limit.</p>

```<code>select * from table skip,limit

$bigQuery = new BigQueryClient([
    'projectId' => 'xxxxx',
]);
$datasetId = 'dbxxxx';
$dataset = $bigQuery->dataset($datasetId);
$options = array(
    'useLegacySql' => true,
    'maxResults' => 50,
    'startIndex' => 1
    );

$query = "SELECT id FROM [ideas] WHERE date >= '".$datefrom."' AND date <= '".$dateto."' ORDER BY date DESC";
$runquery = $bigQuery->runQuery($query,$options);
</code>```

答:
Can you please elaborate on what you mean by doing "skip,limit"?

Looking at the source code for the BigQuery PHP library, the recommended use is to wait for the query to finish before attempting to access rows:
https://github.com/GoogleCloudPlatform/google-cloud-php/blob/master/src/BigQuery/QueryResults.php

Usage example:

```<code>$isComplete = $queryResults->isComplete();
if ($isComplete) {
  $rows = $queryResults->rows();
  foreach ($rows as $row) {
      echo $row['name'] . PHP_EOL;
  }
}
</code>```

If your result set is ~10,000 (not very large), you may find it easier to skip pagination and simply retrieve all rows in the result at once.

Body:
Im setting up queries from bigquery using the php library. but with out the limit on the query itself I get this response "The query has not completed yet.", its around 10k or more, but my pages should limit by 50 anyways. how to setup pagination on bigquery, that I do skip,limit.

select * from table skip,limit

$bigQuery = new BigQueryClient([
    'projectId' => 'xxxxx',
]);
$datasetId = 'dbxxxx';
$dataset = $bigQuery->dataset($datasetId);
$options = array(
    'useLegacySql' => true,
    'maxResults' => 50,
    'startIndex' => 1
    );

$query = "SELECT id FROM [ideas] WHERE date >= '".$datefrom."' AND date <= '".$dateto."' ORDER BY date DESC";
$runquery = $bigQuery->runQuery($query,$options);

Body:
Can you please elaborate on what you mean by doing "skip,limit"?

Looking at the source code for the BigQuery PHP library, the recommended use is to wait for the query to finish before attempting to access rows:
https://github.com/GoogleCloudPlatform/google-cloud-php/blob/master/src/BigQuery/QueryResults.php

Usage example:

$isComplete = $queryResults->isComplete();
if ($isComplete) {
  $rows = $queryResults->rows();
  foreach ($rows as $row) {
      echo $row['name'] . PHP_EOL;
  }
}

If your result set is ~10,000 (not very large), you may find it easier to skip pagination and simply retrieve all rows in the result at once.


问:
Trying to make a django rest api that doesn't look like my models
I'm trying to make an API for an outside group where I define user access.  I have a setup in django that makes it easy to administer, but I would like the output to be quite simplistic for the other team.

This is the output I'm looking for would be something like:

```<code>{
    "user_list": {
        "user": {
            "username": "username1",
            "top_accesses": ["top_access_1", "top_access_2", "top_access_5"],
            "middle_accesses": ["middle_access_1", "middle_access_2", "middle_access_7"],
            "lower_accesses": ["lower_access_1", "lower_access_2", "lower_access_22"],
        },
        "user": {
            "username": "username2",
            "top_accesses": ["top_access_1", "top_access_2", "top_access_8"],
            "middle_accesses": ["middle_access_3", "middle_access_5", "middle_access_6"],
            "lower_accesses": ["lower_access_21", "lower_access_33", "lower_access_36"],
        }
    }
}
</code>```

However, I'm having trouble using django's built in ORM to come up with these sets from my models.  I can think of how to do it in SQL, but this isn't a particularly clean method.  I know there must be a better way to do it since using TabularInline shows exactly what I want to see in the admin page

Here are my models:

```<code>class TopAccess(models.Model):
    name = models.CharField(max_length=100)
    site_user_access = models.ManyToManyField(User, blank=True)
    site_group_access = models.ManyToManyField(Group, blank=True)

    class Meta:
        verbose_name_plural = "Top Access"

    def __str__(self):
        return self.name

class MiddleAccess(models.Model):
    name = models.CharField(max_length=100)
    site_user_access = models.ManyToManyField(User, blank=True)
    site_group_access = models.ManyToManyField(Group, blank=True)

    class Meta:
        verbose_name_plural = "Middle Access"

    def __str__(self):
        return self.name

class LowerAccess(models.Model):
    name = models.CharField(max_length=100)
    site_user_access = models.ManyToManyField(User, blank=True)
    site_group_access = models.ManyToManyField(Group, blank=True)

    class Meta:
        verbose_name_plural = "Lower Access"

    def __str__(self):
        return self.name
</code>```

Ideally I would be able to return a query object that plays well with the django-rest-framework in the end, since I like how nicely it returns the same data in whichever form is requested

Edit:
This is what I'm thinking is going to be close to the solution, but I know I'm using class inheritance incorrectly

```<code>class MaybeThisCouldWork(User):
    t_user = TopAccess.objects.filter(site_user_access=User)
    m_user = MiddleAccess.objects.filter(site_user_access=User)
    l_user = LowerAccess.objects.filter(site_user_access=User)
    user_groups = User.objects.filter(id=User)
    for user_group in user_groups:
        t_group = TopAccess.objects.filter(
                site_group_access=user_groups
                )
        m_group = MiddleAccess.objects.filter(
                site_group_access=user_groups
                )
        l_group = LowerAccess.objects.filter(
                site_group_access=user_groups
                )
        t_user = t_user | t_group
        m_user = m_user | m_group
        l_user = l_user | l_group
</code>```

答:
You could use serializers, may be something like this,</p>

```<code>class TopAccessSerializer(serializers.ModelSerializer):
    class Meta:
        model = TopAccess
        fields = ['name']

class MiddleAccessSerializer(serializers.ModelSerializer):
    class Meta:
        model = MiddleAccess
        fields = ['name']

class LowerAccessSerializer(serializers.ModelSerializer):
    class Meta:
        model = LowerAccess
        fields = ['name']

class UserSerializer(serializers.ModelSerializer):
    topaccess = TopAccessSerializer(source='topaccess_set', many=True)
    middleaccess = MiddleAccessSerializer(source='middleaccess_set', many=True)
    loweraccess = LowerAccessSerializer(source='loweraccess_set', many=True)

    class Meta:
        model = User
        fields = ['username', 'topaccess', 'middleaccess', 'loweraccess']
</code>```

Body:
I'm trying to make an API for an outside group where I define user access.  I have a setup in django that makes it easy to administer, but I would like the output to be quite simplistic for the other team.

This is the output I'm looking for would be something like:

{
    "user_list": {
        "user": {
            "username": "username1",
            "top_accesses": ["top_access_1", "top_access_2", "top_access_5"],
            "middle_accesses": ["middle_access_1", "middle_access_2", "middle_access_7"],
            "lower_accesses": ["lower_access_1", "lower_access_2", "lower_access_22"],
        },
        "user": {
            "username": "username2",
            "top_accesses": ["top_access_1", "top_access_2", "top_access_8"],
            "middle_accesses": ["middle_access_3", "middle_access_5", "middle_access_6"],
            "lower_accesses": ["lower_access_21", "lower_access_33", "lower_access_36"],
        }
    }
}

However, I'm having trouble using django's built in ORM to come up with these sets from my models.  I can think of how to do it in SQL, but this isn't a particularly clean method.  I know there must be a better way to do it since using TabularInline shows exactly what I want to see in the admin page

Here are my models:

class TopAccess(models.Model):
    name = models.CharField(max_length=100)
    site_user_access = models.ManyToManyField(User, blank=True)
    site_group_access = models.ManyToManyField(Group, blank=True)

    class Meta:
        verbose_name_plural = "Top Access"

    def __str__(self):
        return self.name

class MiddleAccess(models.Model):
    name = models.CharField(max_length=100)
    site_user_access = models.ManyToManyField(User, blank=True)
    site_group_access = models.ManyToManyField(Group, blank=True)

    class Meta:
        verbose_name_plural = "Middle Access"

    def __str__(self):
        return self.name

class LowerAccess(models.Model):
    name = models.CharField(max_length=100)
    site_user_access = models.ManyToManyField(User, blank=True)
    site_group_access = models.ManyToManyField(Group, blank=True)

    class Meta:
        verbose_name_plural = "Lower Access"

    def __str__(self):
        return self.name

Ideally I would be able to return a query object that plays well with the django-rest-framework in the end, since I like how nicely it returns the same data in whichever form is requested

Edit:
This is what I'm thinking is going to be close to the solution, but I know I'm using class inheritance incorrectly

class MaybeThisCouldWork(User):
    t_user = TopAccess.objects.filter(site_user_access=User)
    m_user = MiddleAccess.objects.filter(site_user_access=User)
    l_user = LowerAccess.objects.filter(site_user_access=User)
    user_groups = User.objects.filter(id=User)
    for user_group in user_groups:
        t_group = TopAccess.objects.filter(
                site_group_access=user_groups
                )
        m_group = MiddleAccess.objects.filter(
                site_group_access=user_groups
                )
        l_group = LowerAccess.objects.filter(
                site_group_access=user_groups
                )
        t_user = t_user | t_group
        m_user = m_user | m_group
        l_user = l_user | l_group

Body:
You could use serializers, may be something like this,

class TopAccessSerializer(serializers.ModelSerializer):
    class Meta:
        model = TopAccess
        fields = ['name']

class MiddleAccessSerializer(serializers.ModelSerializer):
    class Meta:
        model = MiddleAccess
        fields = ['name']

class LowerAccessSerializer(serializers.ModelSerializer):
    class Meta:
        model = LowerAccess
        fields = ['name']

class UserSerializer(serializers.ModelSerializer):
    topaccess = TopAccessSerializer(source='topaccess_set', many=True)
    middleaccess = MiddleAccessSerializer(source='middleaccess_set', many=True)
    loweraccess = LowerAccessSerializer(source='loweraccess_set', many=True)

    class Meta:
        model = User
        fields = ['username', 'topaccess', 'middleaccess', 'loweraccess']


问:
System.Drawing.Graphics, to draw tables?
Does anyone have any examples of using this System.Drawing.Graphics library to draw tables using DrawRectangle or DrawRectangles or any other method?

I'm trying to set up here with DrawRectangle, but it's difficult, it takes too long to do something simple and it´s a no intuitive tool.
I've crafted articles on the web, but I have not found anything beyond what I've learned so far.

答:
The solution is here bellow:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    var image = new Bitmap(800, 600);
    try
    {
        var graph = Graphics.FromImage(image);
        graph.FillRectangle(Brushes.White, new Rectangle(new Point(0, 0), image.Size));
        for (int col = 0; col < image.Width; col += 100) {
            graph.DrawLine(Pens.Black, new Point(col, 0), new Point(col, image.Height));
        }
        for (int row = 0; row < image.Height; row += 30) {
            graph.DrawLine(Pens.Black, new Point(0, row), new Point(image.Width, row));
        }
        graph.DrawRectangle(Pens.Black, new Rectangle(0, 0, image.Width - 1, image.Height - 1));

        Response.Clear();
        Response.ContentType = "image/jpeg";
        image.Save(Response.OutputStream, ImageFormat.Jpeg);
        Response.End();
    }
    finally
    {
        image.Dispose();
    }
}
</code>```

Body:
The solution is here bellow:

protected void Page_Load(object sender, EventArgs e)
{
    var image = new Bitmap(800, 600);
    try
    {
        var graph = Graphics.FromImage(image);
        graph.FillRectangle(Brushes.White, new Rectangle(new Point(0, 0), image.Size));
        for (int col = 0; col < image.Width; col += 100) {
            graph.DrawLine(Pens.Black, new Point(col, 0), new Point(col, image.Height));
        }
        for (int row = 0; row < image.Height; row += 30) {
            graph.DrawLine(Pens.Black, new Point(0, row), new Point(image.Width, row));
        }
        graph.DrawRectangle(Pens.Black, new Rectangle(0, 0, image.Width - 1, image.Height - 1));

        Response.Clear();
        Response.ContentType = "image/jpeg";
        image.Save(Response.OutputStream, ImageFormat.Jpeg);
        Response.End();
    }
    finally
    {
        image.Dispose();
    }
}


问:
Badge - data structure / models?
I'm trying to figure out how one would set up a database and/or model in order to handle various badges. Lets take the Stack Overflow badges as an example. There are different rules for each and some might be just a variable different (like 10 comments vs 100 comments).

My question is how do you set up this type validation/check within an application? Should each badge have its own method?

答:
Being that SO runs off SQL Server, SQL Server Agent Job to run periodically to tabulate statistics.  The stored procedure(s) in the job would insert into a badges/etc table when criteria is met.

Triggers would be another option, but their execution can't be delayed for the scope of multiple users.

Title: Badge - data structure / models?


问:
VBA does not active
I suggest that my workbook contains a VBA code below. But It does not run when I opened my workbook too.</p>

```<code>Sub Appl_StatusBar()
      Application.StatusBar = "SupportABC"
End Sub
</code>```

答:
If you put your code in the Workbook Open Event it will do what you need. To do this click the top dropdown where it says "(General)" and hit "Workbook". In the right dropdown select "Open" and save your code there". See below</p>

```<code>Private Sub Workbook_Open()
    Application.StatusBar = "SupportABC"
End Sub
</code>```

Title: VBA does not active

Body:
I suggest that my workbook contains a VBA code below. But It does not run when I opened my workbook too.

Sub Appl_StatusBar()
      Application.StatusBar = "SupportABC"
End Sub

Body:
If you put your code in the Workbook Open Event it will do what you need. To do this click the top dropdown where it says "(General)" and hit "Workbook". In the right dropdown select "Open" and save your code there". See below

Private Sub Workbook_Open()
    Application.StatusBar = "SupportABC"
End Sub


问:
Canonical tag value not appearing in page-source when using react-helmet
I'm using react js and react-helmet to change the canonical tag values in the pages. But, it is not updating the value. Everywhere it is showing https://www.example.com, which is mentioned in my index.php file. I need to update the canonical link. I have earlier used jquery, but it didn't work out. It was updating in element-inspector and not in page-source but google was marking as duplicate pages.

I'm following https://github.com/nfl/react-helmet#server-usage

canonical url code

```<code>var newCanonicalUrl = "https://www.examle.com" + this.state.productUrl;
</code>```

inside render function

```<code>return(<Helmet link = {[{"rel" : "canonical", "href" : {newCanonicalUrl}}]}>);
</code>```

答:
This should do the trick:</p>

```<code>link = {[
      { rel : 'canonical', href : newCanonicalUrl  }
]}
</code>```

Body:
I'm using react js and react-helmet to change the canonical tag values in the pages. But, it is not updating the value. Everywhere it is showing https://www.example.com, which is mentioned in my index.php file. I need to update the canonical link. I have earlier used jquery, but it didn't work out. It was updating in element-inspector and not in page-source but google was marking as duplicate pages.

I'm following https://github.com/nfl/react-helmet#server-usage

canonical url code

var newCanonicalUrl = "https://www.examle.com" + this.state.productUrl;

inside render function

return(<Helmet link = {[{"rel" : "canonical", "href" : {newCanonicalUrl}}]}>);

Body:
This should do the trick:

link = {[
      { rel : 'canonical', href : newCanonicalUrl  }
]}


问:
ASP.NET - Copying extra files on publish not working recursively
I have a web application project that I want to publish to a web server.  There is a folder of files that are not included in the project, but need to be copied when it is published.  I found a few posts on how to do this copying with MSBuild, but I cannot get it to copy all files/folders recursively in the main folder I want to copy.

The folder I want to copy is (proj)/Scripts.  (This directory is excluded from the application project because I have all my JavaScript code in a separate project in the same solution, and this folder is copied from the JS project's output folder after it performs minification and other build tasks.)

Here is the section I have added to my *.csproj file:

```<code>  <PropertyGroup>
    <CopyAllFilesToSingleFolderForPackageDependsOn>
      CustomCollectFiles;
      $(CopyAllFilesToSingleFolderForPackageDependsOn);
    </CopyAllFilesToSingleFolderForPackageDependsOn>
  </PropertyGroup>

  <Target Name="CustomCollectFiles">
    <ItemGroup>
      <_CustomFiles Include="Scripts\*" />
      <FilesForPackagingFromProject Include="%(_CustomFiles.Identity)">
        <DestinationRelativePath>
            <!-- whitespace and new line added for question readability -->
            Scripts\%(RecursiveDir)%(Filename)%(Extension)
        </DestinationRelativePath>
      </FilesForPackagingFromProject>
    </ItemGroup>
  </Target>
</code>```

This will copy any files in the top level of the /Scripts folder, but nothing in its subfolders.

How do I make it recursive?

Fixed my own problem:

```<code><PropertyGroup>
    <CopyAllFilesToSingleFolderForPackageDependsOn>
      CustomCollectFiles;
      $(CopyAllFilesToSingleFolderForPackageDependsOn);
    </CopyAllFilesToSingleFolderForPackageDependsOn>
  </PropertyGroup>

  <Target Name="CustomCollectFiles">
    <ItemGroup>
      <_CustomFiles Include="Scripts\**\*.*" />
      <FilesForPackagingFromProject Include="%(_CustomFiles.Identity)">
        <DestinationRelativePath>Scripts\%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
      </FilesForPackagingFromProject>
    </ItemGroup>
  </Target>
</code>```

<_CustomFiles Include="Scripts\*" /> had to be changed to

<_CustomFiles Include="Scripts\**\*.*" />

答:
This worked for me:

```<code>  <ItemGroup>
    <Content Include="YourTargetDir\**\*.*">
      <Link>YourTargetDir\%(RecursiveDir)%(Filename)%(Extension)</Link>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
</code>```

Body:
I have a web application project that I want to publish to a web server.  There is a folder of files that are not included in the project, but need to be copied when it is published.  I found a few posts on how to do this copying with MSBuild, but I cannot get it to copy all files/folders recursively in the main folder I want to copy.

The folder I want to copy is (proj)/Scripts.  (This directory is excluded from the application project because I have all my JavaScript code in a separate project in the same solution, and this folder is copied from the JS project's output folder after it performs minification and other build tasks.)

Here is the section I have added to my *.csproj file:

  <PropertyGroup>
    <CopyAllFilesToSingleFolderForPackageDependsOn>
      CustomCollectFiles;
      $(CopyAllFilesToSingleFolderForPackageDependsOn);
    </CopyAllFilesToSingleFolderForPackageDependsOn>
  </PropertyGroup>

  <Target Name="CustomCollectFiles">
    <ItemGroup>
      <_CustomFiles Include="Scripts\*" />
      <FilesForPackagingFromProject Include="%(_CustomFiles.Identity)">
        <DestinationRelativePath>

            Scripts\%(RecursiveDir)%(Filename)%(Extension)
        </DestinationRelativePath>
      </FilesForPackagingFromProject>
    </ItemGroup>
  </Target>

This will copy any files in the top level of the /Scripts folder, but nothing in its subfolders.

How do I make it recursive?

Fixed my own problem:

<PropertyGroup>
    <CopyAllFilesToSingleFolderForPackageDependsOn>
      CustomCollectFiles;
      $(CopyAllFilesToSingleFolderForPackageDependsOn);
    </CopyAllFilesToSingleFolderForPackageDependsOn>
  </PropertyGroup>

  <Target Name="CustomCollectFiles">
    <ItemGroup>
      <_CustomFiles Include="Scripts\**\*.*" />
      <FilesForPackagingFromProject Include="%(_CustomFiles.Identity)">
        <DestinationRelativePath>Scripts\%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
      </FilesForPackagingFromProject>
    </ItemGroup>
  </Target>

<_CustomFiles Include="Scripts\*" /> had to be changed to

<_CustomFiles Include="Scripts\**\*.*" />

Body:
This worked for me:

  <ItemGroup>
    <Content Include="YourTargetDir\**\*.*">
      <Link>YourTargetDir\%(RecursiveDir)%(Filename)%(Extension)</Link>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>


问:
Getting the error Undefined variable and all values getting saved as 0 in sql db when saving an html form using php
Html code:

```<code><html>
<head>
</head>
<body>
<p><h1>Student Information Input Form</h1></p>
<section>
<form method="POST" action="connection.php">
<p><b>Name:</b> <input type="text" id="name" name="name"></input></p>
<p><b>Username:</b> <input type="text" id="username" name="username"></input></p>
<p><b>Password:</b> <input type="password" id="password" name="password"></input></p>
<p><b>Email:</b> <input type="email" id="email" name="email"></input></p>
<p><input type="submit" id="submit" name="submit"></p>
</form>
</section>
</body>
</html>
</code>```

PHP Code:

```<code><?php
$servername="localhost";
$username="root";
$password="";
$dbname="newdb";

//Create Connection
$conn=new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//get values from form
if (isset($_POST['name'])) {
$nameForm=$_POST['name'];
}
if (isset($_POST['username'])) {
$usernameForm=$_POST['username'];
}
if (isset($_POST['passsword'])) {
$passwordForm=$_POST['password'];
}
if (isset($_POST['email'])) {
$emailForm=$_POST['email'];
}

//Insert Values
$sql = "INSERT INTO userinfo (name, username, password, email) VALUES ('$nameForm', '$usernameForm', '$passwordForm', '$emailForm')";

//To check whether data is inserted properly or not
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
</code>```

Error Message:

Notice: Undefined variable: passwordForm in
  C:\xampp\htdocs\Project2_php db\connection.php on line 28 New record
  created successfully

On clicking The submit button I am getting the above error and in the database, all the values are stored as zero.

答:
its a typo if (isset($_POST['passsword'])) { // password

NOTE:
Also consider switching to PDO statement

Body:
Html code:

Student Information Input Form

<form method="POST" action="connection.php">

Name: <input type="text" id="name" name="name"></input>

Username: <input type="text" id="username" name="username"></input>

Password: <input type="password" id="password" name="password"></input>

Email: <input type="email" id="email" name="email"></input>

<input type="submit" id="submit" name="submit">

</form>

PHP Code:

<?php
$servername="localhost";
$username="root";
$password="";
$dbname="newdb";

//Create Connection
$conn=new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//get values from form
if (isset($_POST['name'])) {
$nameForm=$_POST['name'];
}
if (isset($_POST['username'])) {
$usernameForm=$_POST['username'];
}
if (isset($_POST['passsword'])) {
$passwordForm=$_POST['password'];
}
if (isset($_POST['email'])) {
$emailForm=$_POST['email'];
}

//Insert Values
$sql = "INSERT INTO userinfo (name, username, password, email) VALUES ('$nameForm', '$usernameForm', '$passwordForm', '$emailForm')";

//To check whether data is inserted properly or not
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

Error Message:

Notice: Undefined variable: passwordForm in
  C:\xampp\htdocs\Project2_php db\connection.php on line 28 New record
  created successfully

On clicking The submit button I am getting the above error and in the database, all the values are stored as zero.


问:
Convert string of dictionary to list with removal of single quotes
I have one string having dictionary, I want to convert it into a list, but unable to remove single quote while doing the same.

Can someone help me in figuring out what is missing here?

```<code>>>> a = '{"src_ports": [7] , "dst_ports": [8]}'
</code>```

What I want is following:

```<code>[{"src_ports": [7] , "dst_ports": [8]}]
</code>```

But what I get is following:

```<code>>>> a = [a]
>>> a
['{"src_ports": [7] , "dst_ports": [8]}']
</code>```

Edited:
With ast, order of dictionary elements gets changed, I need to keep it intact.

```<code>>>> import ast
>>> b = [ast.literal_eval(a)]
>>> b
[{'dst_ports': [8], 'src_ports': [7]}]
</code>```

答:
You can use the ast.literal_eval() function as a safer eval() for that:

```<code>import ast

a = '{"src_ports": [7] , "dst_ports": [8]}'

b = [ast.literal_eval(a)]
# [{'dst_ports': [8], 'src_ports': [7]}]
</code>```

UPDATE - Provided your structure remains the same, you can use the json module in combination with collections.OrderedDict if you want to preserve the order. Keep in mind that both Python dict and JSON are, generally, unordered structures:

```<code>import json
import collections

a = '{"src_ports": [7] , "dst_ports": [8]}'

b = json.loads(a, object_pairs_hook=collections.OrderedDict)
</code>```

But if you print it out it you'll get something like OrderedDict([(u'src_ports', [7]), (u'dst_ports', [8])]) however your order will be preserved, for example if you're serializing it later or loop through it.

Body:
I have one string having dictionary, I want to convert it into a list, but unable to remove single quote while doing the same.

Can someone help me in figuring out what is missing here?

>>> a = '{"src_ports": [7] , "dst_ports": [8]}'

What I want is following:

[{"src_ports": [7] , "dst_ports": [8]}]

But what I get is following:

>>> a = [a]
>>> a
['{"src_ports": [7] , "dst_ports": [8]}']

Edited:
With ast, order of dictionary elements gets changed, I need to keep it intact.

>>> import ast
>>> b = [ast.literal_eval(a)]
>>> b
[{'dst_ports': [8], 'src_ports': [7]}]

Body:
You can use the ast.literal_eval() function as a safer eval() for that:

import ast

a = '{"src_ports": [7] , "dst_ports": [8]}'

b = [ast.literal_eval(a)]
# [{'dst_ports': [8], 'src_ports': [7]}]

UPDATE - Provided your structure remains the same, you can use the json module in combination with collections.OrderedDict if you want to preserve the order. Keep in mind that both Python dict and JSON are, generally, unordered structures:

import json
import collections

a = '{"src_ports": [7] , "dst_ports": [8]}'

b = json.loads(a, object_pairs_hook=collections.OrderedDict)

But if you print it out it you'll get something like OrderedDict([(u'src_ports', [7]), (u'dst_ports', [8])]) however your order will be preserved, for example if you're serializing it later or loop through it.


问:
how to pass variable with require() in PHP
I'm stuck trying to pass variables between 2 PHP files a.php and b.php  using require(). I learned that PHP variables have a single scope, which means that if a.php includes b.php, it can read its variables. However, I would like b.php to be able to read a variable from a.php with my current setup. For example, I can print out $msg if it is set in b.php but not a.php. Is there a simple way to do this?

a.php

```<code><?php

$msg = "Welcome NEW USER ! We can't wait for you to check out our books!";
require("connect.php");
require("b.php");
$table = "SELECT * FROM `login`";
if ($query_run=mysqli_query($cnn,$table)){

$username = $_POST['username'];
$pw = $_POST['password'];

$sql = "INSERT INTO login (username,password) VALUES ('{$username}','{$pw}')";

if($cnn->query($sql)===TRUE){echo "Query ran successfully";}
else{echo "Error: ".$sql."<br>".$cnn->error;}
}
else{die("table connection failed");}
$cnn.close();

?>
</code>```

b.php

```<code><?php
echo "<h1>".$msg."</h1>
<form action='' method='post'>
Username: <input type='text' name='username'><br>
Password: <input type='text' name='password'><br>
<input type='submit' name='submit'>
</form>
"

?>
</code>```

答:
If you make require an infinite cycling occurs,try require_once in each file.
But the best solution is to create a third file be it c.php and include both b.php and a.php in it

Body:
I'm stuck trying to pass variables between 2 PHP files a.php and b.php  using require(). I learned that PHP variables have a single scope, which means that if a.php includes b.php, it can read its variables. However, I would like b.php to be able to read a variable from a.php with my current setup. For example, I can print out $msg if it is set in b.php but not a.php. Is there a simple way to do this?

a.php

<?php

$msg = "Welcome NEW USER ! We can't wait for you to check out our books!";
require("connect.php");
require("b.php");
$table = "SELECT * FROM `login`";
if ($query_run=mysqli_query($cnn,$table)){

$username = $_POST['username'];
$pw = $_POST['password'];

$sql = "INSERT INTO login (username,password) VALUES ('{$username}','{$pw}')";

if($cnn->query($sql)===TRUE){echo "Query ran successfully";}
else{echo "Error: ".$sql."
".$cnn->error;}
}
else{die("table connection failed");}
$cnn.close();

?>

b.php

<?php
echo "
".$msg."

<form action='' method='post'>
Username: <input type='text' name='username'>

Password: <input type='text' name='password'>

<input type='submit' name='submit'>
</form>
"

?>


问:
Python sqlite3 and string formatting - Error
This is my code:

```<code>title = "Importunate Widow"
conn = sqlite3.connect('parable.sqlite')
c = conn.cursor()
sqlite3.enable_callback_tracebacks(True)

c.executescript("""
            CREATE TABLE IF NOT EXISTS _index(
                title text NOT NULL,
                context text NOT NULL
                );

            CREATE TABLE IF NOT EXISTS {}(
                value int NOT NULL,
                number int NOT NULL,
                question text NOT NULL,
                choice1 text,
                choice2 text,
                choice3 text,
                choice4 text,
                answer text NOT NULL,
                explanation text,
                see text
                )""".format(title))

    c.executemany('INSERT INTO _index(title,context) VALUES(?,?)', index)

    c.executemany('INSERT INTO {}(value,number,question,choice1,choice2,choice3,choice4,answer,explanation,see) VALUES(?,?,?,?,?,?,?,?,?,?)'.format(title), quiz)
    conn.commit()
    conn.close()
</code>```

This gives me:

```<code> OperationalError    Traceback (most recent call last)
 /home/user/Hobby/Quiz/quiz_sqlite.py in <module>()
sqlite3.enable_callback_tracebacks(True)
     87
---> 88         c.executescript("""CREATE TABLE IF NOT EXISTS _index(title text NOT NULL,context text NOT NULL);CREATE TABLE IF NOT EXISTS {}(value int NOT NULL,number int NOT NULL,question text NOT NULL,choice1 text,choice2 text,choice3 text,choice4 text,answer text NOT NULL,explanation text,check text )""".format(title))
     89
     90         c.executemany('INSERT INTO _index(title,context) VALUES(?,?)', index)

OperationalError: near "Widow": syntax error
</code>```

I am basically iterating over multiple files and inserting data into tables named after the files. I have searched the internet and have turned up with nothing.

What I tried:

Tried adding ; after the ) before """

Tried adding , after see text

Tried changing the name of the column see to refer

None of this helped!

What is the syntax error in the code?

答: You're trying to use Importunate Widow as a table name. You're not allowed to use spaces in a table or field name.

Body:
This is my code:

title = "Importunate Widow"
conn = sqlite3.connect('parable.sqlite')
c = conn.cursor()
sqlite3.enable_callback_tracebacks(True)

c.executescript("""
            CREATE TABLE IF NOT EXISTS _index(
                title text NOT NULL,
                context text NOT NULL
                );

            CREATE TABLE IF NOT EXISTS {}(
                value int NOT NULL,
                number int NOT NULL,
                question text NOT NULL,
                choice1 text,
                choice2 text,
                choice3 text,
                choice4 text,
                answer text NOT NULL,
                explanation text,
                see text
                )""".format(title))

    c.executemany('INSERT INTO _index(title,context) VALUES(?,?)', index)

    c.executemany('INSERT INTO {}(value,number,question,choice1,choice2,choice3,choice4,answer,explanation,see) VALUES(?,?,?,?,?,?,?,?,?,?)'.format(title), quiz)
    conn.commit()
    conn.close()

This gives me:

 OperationalError    Traceback (most recent call last)
 /home/user/Hobby/Quiz/quiz_sqlite.py in <module>()
sqlite3.enable_callback_tracebacks(True)
     87
---> 88         c.executescript("""CREATE TABLE IF NOT EXISTS _index(title text NOT NULL,context text NOT NULL);CREATE TABLE IF NOT EXISTS {}(value int NOT NULL,number int NOT NULL,question text NOT NULL,choice1 text,choice2 text,choice3 text,choice4 text,answer text NOT NULL,explanation text,check text )""".format(title))
     89
     90         c.executemany('INSERT INTO _index(title,context) VALUES(?,?)', index)

OperationalError: near "Widow": syntax error

I am basically iterating over multiple files and inserting data into tables named after the files. I have searched the internet and have turned up with nothing.

What I tried:

Tried adding ; after the ) before """

Tried adding , after see text

Tried changing the name of the column see to refer

None of this helped!

What is the syntax error in the code?


问:
Twilio web app notify
I need push notification on mobile webapp (Xojo, iOS+Android), I was thinking to use Twilio Notify Beta but it is not clear to me how it works.

Say a user starts the webapp: first time it should bind with a REST api, but I don't understand where to find the "device token", how to define if the mobile user has to accept the notification or he/she has already did it, etc.

Docs are here.

Can you push me in the right direction?

答:
Twilio developer evangelist here.

You've found yourself among the wrong part of the documentation there I'm afraid.

The section you want is the Notify Usage section which gives you an introduction and then leads on to:

Registering for notifications on iOS

Registering for notifications on Android

Both articles walk you through how to get a device token, register a binding and send a push notification.

If you are looking to do this for the web too, Twilio Notify supports sending notifications via FCM. You need to require FCM's JavaScript and use that to get a "registration token" which you can also set up as a binding (by following the rest of the Android guide once you have the registration token).

Let me know if that helps at all.

Title: Twilio web app notify


问:
How to parse a json having nested json type objects with boost
I have a json which looks like

```<code>{
  "children": [
    {
      "name": "apple",
      "path": "hutchison",
      "state": 16,
      "url": "https://go.gl/",
      "id": "ZXNrb0luZGlh",
      "properties": [
        {
          "id": "type",
          "name": "type",
          "propertyType": "string",
          "value": "COMPANY"
        },
        {
          "id": "folderify",
          "name": "folderify",
          "propertyType": "boolean",
          "value": "true"
        },
        {
          "id": "name",
          "name": "name",
          "propertyType": "string",
          "value": "yum"
        }
      ],
      "content": [],
      "createdBy": "00ui3tqahuu6bwMhU0i6",
      "creationDate": 1497348318103,
      "modificationDate": 1499082955407,
      "modifiedBy": "00ui3tqahuu6bwMhU0i6"
    },
    {
      "name": "test",
      "path": "test",
      "state": 13,
      "url": "https://ODE/v0/test",
      "id": "YW5ib3Rlc3Q=",
      "properties": [
        {
          "id": "string",
          "name": "string",
          "propertyType": "string",
          "value": "string"
        }
      ],
      "content": [],
      "createdBy": "00u33355JQXgmzqO90i5",
      "creationDate": 1498463285568,
      "modificationDate": 1498463356176,
      "modifiedBy": "00u33355JQXgmzqO90i5"
    },
    {
      "name": "KE",
      "path": "KE",
      "state": 4,
      "url": "https://full.com/NODE/v0/DEKE",
      "id": "REVLRQ==",
      "properties": [
        {
          "id": "type",
          "name": "type",
          "propertyType": "string",
          "value": "COMPANY"
        },
        {
          "id": "folderify",
          "name": "folderify",
          "propertyType": "boolean",
          "value": "true"
        },
        {
          "id": "name",
          "name": "name",
          "propertyType": "string",
          "value": "KE"
        }
      ],
      "content": [],
      "createdBy": "00uy9bswhaVnUggF00i6",
      "creationDate": 1498805345347,
      "modificationDate": 1498805346371,
      "modifiedBy": "00uy9bswhaVnUggF00i6"
    }
]
,
  "name": "",
  "path": "",
  "state": 27,
  "url": "https://go.gl/ODE/v0",
  "id": "ROOT",
  "properties": [],
  "content": [],
  "createdBy": "INITIAL",
  "creationDate": 1497261853581,
  "modificationDate": 1498805345347,
  "modifiedBy": "00uy9bswhaVnUggF00i6"
}
</code>```

I want each and every key-value(s) pair to be traversed once by of course using boost library (any other approach in cpp is also welcomed), to later save them in relevant containers.

答:
I am actually using Json for modern C++ to manage any Json. It's really intuitive and easy to integrate.

I don't really know which key-value you're trying to reach but let's say you'd like to store the name of the first children in a string variable.

You'd parse your json like so:

```<code>json yourJson = json::parse(yourJsonString);
</code>```

Then you'd access the name and store it in a string variable like so:

```<code>string nameFirstChildren = yourJson["children"][0]["name"].get<string>();
</code>```

Then, you can save it in a container of your choice or you could just do it without using a string variable before saving it to your container.

Whatever works for you!

You could also use RapidJson

Body:
I have a json which looks like

{
  "children": [
    {
      "name": "apple",
      "path": "hutchison",
      "state": 16,
      "url": "https://go.gl/",
      "id": "ZXNrb0luZGlh",
      "properties": [
        {
          "id": "type",
          "name": "type",
          "propertyType": "string",
          "value": "COMPANY"
        },
        {
          "id": "folderify",
          "name": "folderify",
          "propertyType": "boolean",
          "value": "true"
        },
        {
          "id": "name",
          "name": "name",
          "propertyType": "string",
          "value": "yum"
        }
      ],
      "content": [],
      "createdBy": "00ui3tqahuu6bwMhU0i6",
      "creationDate": 1497348318103,
      "modificationDate": 1499082955407,
      "modifiedBy": "00ui3tqahuu6bwMhU0i6"
    },
    {
      "name": "test",
      "path": "test",
      "state": 13,
      "url": "https://ODE/v0/test",
      "id": "YW5ib3Rlc3Q=",
      "properties": [
        {
          "id": "string",
          "name": "string",
          "propertyType": "string",
          "value": "string"
        }
      ],
      "content": [],
      "createdBy": "00u33355JQXgmzqO90i5",
      "creationDate": 1498463285568,
      "modificationDate": 1498463356176,
      "modifiedBy": "00u33355JQXgmzqO90i5"
    },
    {
      "name": "KE",
      "path": "KE",
      "state": 4,
      "url": "https://full.com/NODE/v0/DEKE",
      "id": "REVLRQ==",
      "properties": [
        {
          "id": "type",
          "name": "type",
          "propertyType": "string",
          "value": "COMPANY"
        },
        {
          "id": "folderify",
          "name": "folderify",
          "propertyType": "boolean",
          "value": "true"
        },
        {
          "id": "name",
          "name": "name",
          "propertyType": "string",
          "value": "KE"
        }
      ],
      "content": [],
      "createdBy": "00uy9bswhaVnUggF00i6",
      "creationDate": 1498805345347,
      "modificationDate": 1498805346371,
      "modifiedBy": "00uy9bswhaVnUggF00i6"
    }
]
,
  "name": "",
  "path": "",
  "state": 27,
  "url": "https://go.gl/ODE/v0",
  "id": "ROOT",
  "properties": [],
  "content": [],
  "createdBy": "INITIAL",
  "creationDate": 1497261853581,
  "modificationDate": 1498805345347,
  "modifiedBy": "00uy9bswhaVnUggF00i6"
}

I want each and every key-value(s) pair to be traversed once by of course using boost library (any other approach in cpp is also welcomed), to later save them in relevant containers.

Body:
I am actually using Json for modern C++ to manage any Json. It's really intuitive and easy to integrate.

I don't really know which key-value you're trying to reach but let's say you'd like to store the name of the first children in a string variable.

You'd parse your json like so:

json yourJson = json::parse(yourJsonString);

Then you'd access the name and store it in a string variable like so:

string nameFirstChildren = yourJson["children"][0]["name"].get<string>();

Then, you can save it in a container of your choice or you could just do it without using a string variable before saving it to your container.

Whatever works for you!

You could also use RapidJson


问:
POST 500 Error Bot Emulator Localhost for IIS hosted Bot
I have used IIS to locally host my bot like so: https: //localhost/MyBot. Currently when I try to connect to my bot in the bot emulator I get a POST 500 error, and am unable to send messages. I am new to this and most documentation for publishing a bot to a local server is limited. I can however successfully open this link from my browser.

Am I experiencing this error because I don't have the https: //localhost/Bridget/api/messages directory/url? I tried creating Virtual Directories in IIS but that did not help solve my problem. Do I need tunneling software? Is there a simple tutorial for deploying a bot locally using IIS and connecting to it via the bot emulator?

Here is the error I see in the emulator:

Bot Emulator Error

Using ngrok tunneling software this is what I see:

NGROK Bot Emulator Error

Here is the code that processing incoming POST messages:

```<code>/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
    if (activity.Type == ActivityTypes.Message)
    {
        // Strip any @mentions
        Mention[] m = activity.GetMentions();
        for (int x = 0; x < m.Length; x++)
        {
            if (m[x].Mentioned.Id == activity.Recipient.Id)
            {
                if (m[x].Text != null)
                {
                    activity.Text = activity.Text.Replace(m[x].Text, "");
                }
            }
        }

        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

        await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
    }
    else if (activity.Type == ActivityTypes.Invoke)
    {
            // Some Code...
    }
    else
    {
        HandleSystemMessage(activity);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}
</code>```

答:
I fixed the issue, it was because IIS was not allowing POST requests. All I did was go to Request filtering and added the verb POST:

IIS POST Fix

Body:
I have used IIS to locally host my bot like so: https: //localhost/MyBot. Currently when I try to connect to my bot in the bot emulator I get a POST 500 error, and am unable to send messages. I am new to this and most documentation for publishing a bot to a local server is limited. I can however successfully open this link from my browser.

Am I experiencing this error because I don't have the https: //localhost/Bridget/api/messages directory/url? I tried creating Virtual Directories in IIS but that did not help solve my problem. Do I need tunneling software? Is there a simple tutorial for deploying a bot locally using IIS and connecting to it via the bot emulator?

Here is the error I see in the emulator:

Bot Emulator Error

Using ngrok tunneling software this is what I see:

NGROK Bot Emulator Error

Here is the code that processing incoming POST messages:

///
/// POST: api/Messages
/// Receive a message from a user and reply to it
///
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
    if (activity.Type == ActivityTypes.Message)
    {
        // Strip any @mentions
        Mention[] m = activity.GetMentions();
        for (int x = 0; x < m.Length; x++)
        {
            if (m[x].Mentioned.Id == activity.Recipient.Id)
            {
                if (m[x].Text != null)
                {
                    activity.Text = activity.Text.Replace(m[x].Text, "");
                }
            }
        }

        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

        await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
    }
    else if (activity.Type == ActivityTypes.Invoke)
    {
            // Some Code...
    }
    else
    {
        HandleSystemMessage(activity);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}


问:
Can't Select username and password Column from user table (MySql)
I am putting up an authenticating system on my local server to test run some scripts for my personal use using PHP and MYSQL.  I ran the following code to select the 'username' and 'password' column from a 'users' table, but i kip getting this error after inputting the correct credentials:

```<code>Invalid username/password combination
</code>```

Here is the script:

```<code><?php // authentication.php

require_once 'login.php';

$connection = new mysqli($hn, $un, $pw, $db);
if ($connection->connect_error) die($connection->connect_error);

if (isset($_SERVER['PHP_AUTH_USER']) &&
     isset($_SERVER['PHP_AUTH_PW'])) {

        $un_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_USER']);
        $pw_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_PW']);

        $query = "SELECT * FROM users WHERE username='$un_temp' AND password='$pw_temp'";
        $result = $connection->query($query);
        if (!$result) die($connection->error);

    else if ($result->num_rows) {

        $row = $result->fetch_array(MYSQLI_NUM);
        $result->close();

            if ( password_verify( $pw_temp == $row[3]) ) {

                echo "$row[0] $row[1] : Hi $row[0], you are now logged in as '$row[2]'";

            }

        }

            else die("Invalid username/password combination");

     } else {

            header('WWW-Authenticate: Basic realm="Restricted Section"');
            header('HTTP/1.0 401 Unauthorized');
            die("Pleaser enter your username and password");
     }

    $connection->close();

    function mysql_entities_fix_string($connection, $string) {

        return htmlentities(mysql_fix_string($connection, $string));
     }

    function mysql_fix_string($connection, $string) {

        if (get_magic_quotes_gpc()) $string = stripslashes($string);
        return $connection->real_escape_string($string);
     }

?>
</code>```

答:
password_verify accepts the submitted password and its associated password hash, but is being supplied a boolean value ($pw_temp == $row[3]) See: http://php.net/manual/en/function.password-verify.php.

Assuming you use password_hash without a static salt to save the values in the database. Querying the password column is not possible, as password_hash will automatically salt passwords with a unique value. Which prevents you from comparing a second hash of the submitted value to the one in the database. So you would either need to store username as unique index or iterate over the duplicate usernames, and call password_verify to compare each user's password.

Assuming usernames are unique in your table, you should update your code to look like the following.

```<code>if (!isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
    header('WWW-Authenticate: Basic realm="Restricted Section"');
    header('HTTP/1.0 401 Unauthorized');
    die("Please enter your username and password");
}
$un_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_USER']);
$pw_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_PW']);
$query = "SELECT * FROM `users` WHERE `username`='$un_temp'";
if (!$result = $connection->query($query)) {
    die($connection->error);
}
if (!$result->num_rows) {
    die("Invalid username/password combination");
}
$row = $result->fetch_array(MYSQLI_NUM);
$result->close();
if (password_verify($pw_temp, $row[3])) {
    echo "$row[0] $row[1] : Hi $row[0], you are now logged in as '$row[2]'";
}
$connection->close();
</code>```

Demonstration Notice how each hashed password is different.
Keep in mind, since I am unable to query against a database, I used an array to show the equivalent process.

There were also a few syntax related issues in your original code, which would be a bit much to note in a comment.

else if should be one word so that it looks like elseif [sic] to avoid syntax conflicts, but since your condition results in calling die(), an else is not needed.

isset can verify multiple arguments, so calling it again in the same if comparison with && is not needed [sic].

Wrapping column and table names using identifier quotes (backticks), will help to avoid MySQL reserved keyword issues [sic].

```<code>SELECT * FROM `users` WHERE `username`='$un_temp' AND `password`='$pw_temp'
</code>```

Lastly, due to the encryption algorithm and cost being subject to change between PHP security updates [sic]. When using password_hash and password_verify, you should always ensure the password is still cryptographically secure, by using password_needs_rehash [sic] like so:

```<code>if (password_verify($password, $oldHash)) {
    //verify legacy password to new password_hash options
    if (password_needs_rehash($oldHash, \PASSWORD_DEFAULT)) {
        //rehash/store plain-text password using new hash
        $newHash = password_hash($password, \PASSWORD_DEFAULT);
        $updateSQL = "UPDATE `users` SET `password`='$newHash' WHERE `username`='$un_temp' AND `password`='$oldHash'";
        $connection->query($updateSQL);
    }
}
</code>```

Body:
I am putting up an authenticating system on my local server to test run some scripts for my personal use using PHP and MYSQL.  I ran the following code to select the 'username' and 'password' column from a 'users' table, but i kip getting this error after inputting the correct credentials:

Invalid username/password combination

Here is the script:

<?php // authentication.php

require_once 'login.php';

$connection = new mysqli($hn, $un, $pw, $db);
if ($connection->connect_error) die($connection->connect_error);

if (isset($_SERVER['PHP_AUTH_USER']) &&
     isset($_SERVER['PHP_AUTH_PW'])) {

        $un_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_USER']);
        $pw_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_PW']);

        $query = "SELECT * FROM users WHERE username='$un_temp' AND password='$pw_temp'";
        $result = $connection->query($query);
        if (!$result) die($connection->error);

    else if ($result->num_rows) {

        $row = $result->fetch_array(MYSQLI_NUM);
        $result->close();

            if ( password_verify( $pw_temp == $row[3]) ) {

                echo "$row[0] $row[1] : Hi $row[0], you are now logged in as '$row[2]'";

            }

        }

            else die("Invalid username/password combination");

     } else {

            header('WWW-Authenticate: Basic realm="Restricted Section"');
            header('HTTP/1.0 401 Unauthorized');
            die("Pleaser enter your username and password");
     }

    $connection->close();

    function mysql_entities_fix_string($connection, $string) {

        return htmlentities(mysql_fix_string($connection, $string));
     }

    function mysql_fix_string($connection, $string) {

        if (get_magic_quotes_gpc()) $string = stripslashes($string);
        return $connection->real_escape_string($string);
     }

?>

Body:
password_verify accepts the submitted password and its associated password hash, but is being supplied a boolean value ($pw_temp == $row[3]) See: http://php.net/manual/en/function.password-verify.php.

Assuming you use password_hash without a static salt to save the values in the database. Querying the password column is not possible, as password_hash will automatically salt passwords with a unique value. Which prevents you from comparing a second hash of the submitted value to the one in the database. So you would either need to store username as unique index or iterate over the duplicate usernames, and call password_verify to compare each user's password.

Assuming usernames are unique in your table, you should update your code to look like the following.

if (!isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
    header('WWW-Authenticate: Basic realm="Restricted Section"');
    header('HTTP/1.0 401 Unauthorized');
    die("Please enter your username and password");
}
$un_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_USER']);
$pw_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_PW']);
$query = "SELECT * FROM `users` WHERE `username`='$un_temp'";
if (!$result = $connection->query($query)) {
    die($connection->error);
}
if (!$result->num_rows) {
    die("Invalid username/password combination");
}
$row = $result->fetch_array(MYSQLI_NUM);
$result->close();
if (password_verify($pw_temp, $row[3])) {
    echo "$row[0] $row[1] : Hi $row[0], you are now logged in as '$row[2]'";
}
$connection->close();

Demonstration Notice how each hashed password is different.
Keep in mind, since I am unable to query against a database, I used an array to show the equivalent process.

There were also a few syntax related issues in your original code, which would be a bit much to note in a comment.

else if should be one word so that it looks like elseif [sic] to avoid syntax conflicts, but since your condition results in calling die(), an else is not needed.

isset can verify multiple arguments, so calling it again in the same if comparison with && is not needed [sic].

Wrapping column and table names using identifier quotes (backticks), will help to avoid MySQL reserved keyword issues [sic].

SELECT * FROM `users` WHERE `username`='$un_temp' AND `password`='$pw_temp'

Lastly, due to the encryption algorithm and cost being subject to change between PHP security updates [sic]. When using password_hash and password_verify, you should always ensure the password is still cryptographically secure, by using password_needs_rehash [sic] like so:

if (password_verify($password, $oldHash)) {
    //verify legacy password to new password_hash options
    if (password_needs_rehash($oldHash, \PASSWORD_DEFAULT)) {
        //rehash/store plain-text password using new hash
        $newHash = password_hash($password, \PASSWORD_DEFAULT);
        $updateSQL = "UPDATE `users` SET `password`='$newHash' WHERE `username`='$un_temp' AND `password`='$oldHash'";
        $connection->query($updateSQL);
    }
}