问:
iOS - Shadow spread on UILabel
I want to increase the spread of a shadow in my UILabel but I can't find the property to do that. I have added a photo below to illustrate the issue.

The top Label is the desired effect I am able to create in Photoshop. The bottom Label illustrates the properties I was able to find in iOS. Here is the code I used for the bottom Label.

```<code>let bottomLabel = UILabel(frame: CGRectMake(0, 0, maxWidth, 18))
bottomLabel.backgroundColor = UIColor.clearColor()
bottomLabel.textColor = UIColor.whiteColor()
bottomLabel.font = UIFont.boldSystemFontOfSize(16)
bottomLabel.text = title
bottomLabel.textAlignment = .Center
bottomLabel.numberOfLines = 1
bottomLabel.layer.shadowOffset = CGSize(width: 0, height: 0)
bottomLabel.layer.shadowOpacity = 1
bottomLabel.layer.shadowRadius = 2
</code>```

I did find a suggestion to use a second label as a shadow but this did not give the desired result. Here is the code for that Label.

```<code>let bottomLabelShadow = UILabel(frame: CGRectMake(0, 1, maxWidth, 18))
bottomLabelShadow.backgroundColor = UIColor.clearColor()
bottomLabelShadow.textColor = UIColor.blackColor()
bottomLabelShadow.font = UIFont.boldSystemFontOfSize(16)
bottomLabelShadow.text = title
bottomLabelShadow.textAlignment = .Center
bottomLabelShadow.numberOfLines = 1
bottomLabelShadow.layer.shadowOffset = CGSize(width: 0, height: 0)
bottomLabelShadow.layer.shadowOpacity = 1
bottomLabelShadow.layer.shadowRadius = 2
</code>```

答:
```<code>//Try This! Hope this helps!!

// Create a string
let myString = "Shadow"

// Create a shadow
let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray

// Create an attribute from the shadow
let myAttribute = [ NSShadowAttributeName: myShadow ]

// Add the attribute to the string
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)

// set the attributed text on a label
myLabel.attributedText = myAttrString
</code>```

As an extension:

```<code>extension UILabel {

    func setTextWithShadow(_ string: String) {

        let shadow = NSShadow()
        shadow.shadowBlurRadius = 3
        shadow.shadowOffset = CGSize(width: 3, height: 3)
        shadow.shadowColor = UIColor.black.withAlphaComponent(0.5)

        let attributes = [ NSAttributedString.Key.shadow: shadow ]
        let attributedString = NSAttributedString(string: string, attributes: attributes)

        self.attributedText = attributedString
    }

}
</code>```

Title: iOS - Shadow spread on UILabel

Body:
I want to increase the spread of a shadow in my UILabel but I can't find the property to do that. I have added a photo below to illustrate the issue.

The top Label is the desired effect I am able to create in Photoshop. The bottom Label illustrates the properties I was able to find in iOS. Here is the code I used for the bottom Label.

let bottomLabel = UILabel(frame: CGRectMake(0, 0, maxWidth, 18))
bottomLabel.backgroundColor = UIColor.clearColor()
bottomLabel.textColor = UIColor.whiteColor()
bottomLabel.font = UIFont.boldSystemFontOfSize(16)
bottomLabel.text = title
bottomLabel.textAlignment = .Center
bottomLabel.numberOfLines = 1
bottomLabel.layer.shadowOffset = CGSize(width: 0, height: 0)
bottomLabel.layer.shadowOpacity = 1
bottomLabel.layer.shadowRadius = 2

I did find a suggestion to use a second label as a shadow but this did not give the desired result. Here is the code for that Label.

let bottomLabelShadow = UILabel(frame: CGRectMake(0, 1, maxWidth, 18))
bottomLabelShadow.backgroundColor = UIColor.clearColor()
bottomLabelShadow.textColor = UIColor.blackColor()
bottomLabelShadow.font = UIFont.boldSystemFontOfSize(16)
bottomLabelShadow.text = title
bottomLabelShadow.textAlignment = .Center
bottomLabelShadow.numberOfLines = 1
bottomLabelShadow.layer.shadowOffset = CGSize(width: 0, height: 0)
bottomLabelShadow.layer.shadowOpacity = 1
bottomLabelShadow.layer.shadowRadius = 2

Body:
//Try This! Hope this helps!!

// Create a string
let myString = "Shadow"

// Create a shadow
let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray

// Create an attribute from the shadow
let myAttribute = [ NSShadowAttributeName: myShadow ]

// Add the attribute to the string
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)

// set the attributed text on a label
myLabel.attributedText = myAttrString

As an extension:

extension UILabel {

    func setTextWithShadow(_ string: String) {

        let shadow = NSShadow()
        shadow.shadowBlurRadius = 3
        shadow.shadowOffset = CGSize(width: 3, height: 3)
        shadow.shadowColor = UIColor.black.withAlphaComponent(0.5)

        let attributes = [ NSAttributedString.Key.shadow: shadow ]
        let attributedString = NSAttributedString(string: string, attributes: attributes)

        self.attributedText = attributedString
    }

}


来源: stackexchange

问:
Is a RESTful url valid without ids between objects?
I have two RESTful API design questions.  Let's say I have a fruitstand web app.  I want to return information about all the fruits I carry and the counts those fruits, and I do it with:

```<code>http://myfruitstand.com/fruits
</code>```

Question 1:
If I have 10 oranges, then I'm thinking that I can get information about a particular orange with:

```<code>http://myfruitstand.com/fruits/oranges/3
</code>```

But is the above url RESTful--don't I need an id between 'fruits' and 'oranges' to conform to REST standards?  Or is this url with 'fruits' being immediately followed with the subclass 'oranges' okay?

Question 2:
Similarly, if I want to have a discussion forum about my oranges (not a particular orange), can I put it here:

```<code>http://myfruitstand.com/fruits/oranges/comments
</code>```

Again, is the above url RESTful since there's no id between 'oranges' and 'comments' (an id here, of course, would imply a discussion about a particular orange and I don't want that)?  Here, there's no subclass rational of 'oranges' being immediately followed by 'comments.'

thanks in advance, Chuck

答:
It would be more RESTful to construct by resource-collection/id pairs, e.g. /fruits/:id1/items/:id2, where id1 = orange, id2 = 3

```<code>/fruits/orange/items/3
</code>```

Then the answer to the second question would be also correct if you lose the 's' on oranges, as you are treating orange as an instance of a resource and not a resource collection.

```<code>/fruits/orange/comments
</code>```

e.g. slide 48 of http://www.slideshare.net/Wombert/phpnw10-designing-http-services-and-restful-interfaces

ContentLicense: CC BY-SA 2.5

Body:
I have two RESTful API design questions.  Let's say I have a fruitstand web app.  I want to return information about all the fruits I carry and the counts those fruits, and I do it with:

http://myfruitstand.com/fruits

Question 1:
If I have 10 oranges, then I'm thinking that I can get information about a particular orange with:

http://myfruitstand.com/fruits/oranges/3

But is the above url RESTful--don't I need an id between 'fruits' and 'oranges' to conform to REST standards?  Or is this url with 'fruits' being immediately followed with the subclass 'oranges' okay?

Question 2:
Similarly, if I want to have a discussion forum about my oranges (not a particular orange), can I put it here:

http://myfruitstand.com/fruits/oranges/comments

Again, is the above url RESTful since there's no id between 'oranges' and 'comments' (an id here, of course, would imply a discussion about a particular orange and I don't want that)?  Here, there's no subclass rational of 'oranges' being immediately followed by 'comments.'

thanks in advance, Chuck

Body:
It would be more RESTful to construct by resource-collection/id pairs, e.g. /fruits/:id1/items/:id2, where id1 = orange, id2 = 3

/fruits/orange/items/3

Then the answer to the second question would be also correct if you lose the 's' on oranges, as you are treating orange as an instance of a resource and not a resource collection.

/fruits/orange/comments

e.g. slide 48 of http://www.slideshare.net/Wombert/phpnw10-designing-http-services-and-restful-interfaces


问:
Compare two string lists with each other Python
I would like to compare two string lists, locate the common strings and store the common strings in a new list.

For example:

```<code>my_list1=['      4,         -40.,         -12.\n',
 '      5,         -40.,         -15.\n',
 '      6,         -40.,         -18.\n',
 '      7,         -40.,         -21.\n',
 '      8,         -40.,         -24.\n',
 '      9,         -40.,         -27.\n',
 '     14,         -30.,         -30.\n',
 '     15,         -28.,         -30.\n']

my_list2=['49',
 '50',
 '51',
 '10',
 '53',
 '54',
 '55',
 '56',
 '57',
 '58',
 '59',
 '60',
 '6162',
 '15',
 '64',
 '65',
 '66']
</code>```

What I want to do is compare  each of the strings of my_list2 with the beginning of the strings in my_list1.

For example my_list1 contains '15' from my_list2 in [ '15, -28.,         -30.\n'] so i want a new list which is going to save all the common strings

答:
```<code>my_list1_new = [i.strip().split(",")[0] for i in my_list1 ]
for i in my_list2:
    if i in my_list1_new:
        print(my_list1[my_list1_new.index(i)])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to compare two string lists, locate the common strings and store the common strings in a new list.

For example:

my_list1=['      4,         -40.,         -12.\n',
 '      5,         -40.,         -15.\n',
 '      6,         -40.,         -18.\n',
 '      7,         -40.,         -21.\n',
 '      8,         -40.,         -24.\n',
 '      9,         -40.,         -27.\n',
 '     14,         -30.,         -30.\n',
 '     15,         -28.,         -30.\n']

my_list2=['49',
 '50',
 '51',
 '10',
 '53',
 '54',
 '55',
 '56',
 '57',
 '58',
 '59',
 '60',
 '6162',
 '15',
 '64',
 '65',
 '66']

What I want to do is compare  each of the strings of my_list2 with the beginning of the strings in my_list1.

For example my_list1 contains '15' from my_list2 in [ '15, -28.,         -30.\n'] so i want a new list which is going to save all the common strings


问:
Login failed with facebook. It works with one facebook account, yet it throws an error when trying with another account
Swift3 iOS 10:
I got an error when trying to get user information from facebook user. With the following snippet of code, I could access user data and it does works really well. As I change to login with another accounts it turns into error.

```<code>//Button
@IBAction func FBBtnPressed(_ sender: Any) {
    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) -> Void in
        if (error != nil){
            print(error) // Failed here...
        }else{
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if(fbloginresult.grantedPermissions.contains("email"))
            {
                self.fetchProfile() //This function never calls as I change login account, it turns into error (Error 304)
            }
        }
    }
}
//Fetch user info...
func fetchProfile(){
    let parameters = ["fields": "name, email, gender, birthday, location, id, picture.type(large)"]

    FBSDKGraphRequest(graphPath: "me", parameters: parameters).start(completionHandler: {
        connection, result, error -> Void in
        if error != nil {
            print("longin error =\(String(describing: error))")
        } else {
            if let userInfo = result as? [String:Any]{
                //Get user info...
                print(userInfo["name"])
                print(userInfo["email"])
                print(userInfo["gender"])
                print(userInfo["birthday"])
                print(userInfo["location"])
                print(userInfo["id"])

                }
            }
        }
    })
}
</code>```

答:
Sometimes fbloginresult.grantedPermissions will be nil.i am using below code

```<code>  self.fbLoginManager = FBSDKLoginManager.init()
  fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
  self.fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) -> Void in
            if (error == nil) {
                let fbloginresult : FBSDKLoginManagerLoginResult = result!
                if fbloginresult.grantedPermissions != nil && fbloginresult.grantedPermissions.contains("email") {
                    if((FBSDKAccessToken.current()) != nil){
                        FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, first_name, last_name, email, gender, birthday, location"]).start(completionHandler: { (connection, result, error) -> Void in
                            if error != nil {
                                print(error?.localizedDescription ?? "error in facebook login...!")
                                return
                            }
                            if let dict = result as? NSDictionary {
                                print("facebook login result --->\n\(dict)")
                                guard let id = dict["id"] else {
                                    print("Ooops... id = nil")
                                    return
                                }
                                let firstName: String = dict["first_name"] as? String ?? ""
                                let lastName : String = dict["last_name"] as? String ?? ""
                                let email : String = dict["email"] as? String ?? ""

                                print(firstName,lastName,email)

                                // here you can process your next step
                                self.fbLoginManager.logOut()
                            }
                        })
                    }
                } else {
                    print("facebook ---> login canceled")
                }
            } else {
                print(error?.localizedDescription ?? "facebook login has error")
            }
        }
</code>```

Body:
Swift3 iOS 10:
I got an error when trying to get user information from facebook user. With the following snippet of code, I could access user data and it does works really well. As I change to login with another accounts it turns into error.

//Button
@IBAction func FBBtnPressed(_ sender: Any) {
    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) -> Void in
        if (error != nil){
            print(error) // Failed here...
        }else{
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if(fbloginresult.grantedPermissions.contains("email"))
            {
                self.fetchProfile() //This function never calls as I change login account, it turns into error (Error 304)
            }
        }
    }
}
//Fetch user info...
func fetchProfile(){
    let parameters = ["fields": "name, email, gender, birthday, location, id, picture.type(large)"]

    FBSDKGraphRequest(graphPath: "me", parameters: parameters).start(completionHandler: {
        connection, result, error -> Void in
        if error != nil {
            print("longin error =\(String(describing: error))")
        } else {
            if let userInfo = result as? [String:Any]{
                //Get user info...
                print(userInfo["name"])
                print(userInfo["email"])
                print(userInfo["gender"])
                print(userInfo["birthday"])
                print(userInfo["location"])
                print(userInfo["id"])

                }
            }
        }
    })
}

Body:
Sometimes fbloginresult.grantedPermissions will be nil.i am using below code

  self.fbLoginManager = FBSDKLoginManager.init()
  fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
  self.fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) -> Void in
            if (error == nil) {
                let fbloginresult : FBSDKLoginManagerLoginResult = result!
                if fbloginresult.grantedPermissions != nil && fbloginresult.grantedPermissions.contains("email") {
                    if((FBSDKAccessToken.current()) != nil){
                        FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, first_name, last_name, email, gender, birthday, location"]).start(completionHandler: { (connection, result, error) -> Void in
                            if error != nil {
                                print(error?.localizedDescription ?? "error in facebook login...!")
                                return
                            }
                            if let dict = result as? NSDictionary {
                                print("facebook login result --->\n\(dict)")
                                guard let id = dict["id"] else {
                                    print("Ooops... id = nil")
                                    return
                                }
                                let firstName: String = dict["first_name"] as? String ?? ""
                                let lastName : String = dict["last_name"] as? String ?? ""
                                let email : String = dict["email"] as? String ?? ""

                                print(firstName,lastName,email)

                                // here you can process your next step
                                self.fbLoginManager.logOut()
                            }
                        })
                    }
                } else {
                    print("facebook ---> login canceled")
                }
            } else {
                print(error?.localizedDescription ?? "facebook login has error")
            }
        }


问:
production build - dont open app
I am sorry for this short question. I don't know how to deploy angular2 app so I don't know what to write to help me. I need to deploy production. When I run this command npm build -prod, its ok, copy all js and html to dist folder, but when I open index.html in browser app don't start and in the log is this:

```<code>/E:/styles.a530fc809103522200ce.bundle.css Failed to load resource: net::ERR_FILE_NOT_FOUND
inline.64b91d2d61fb76e9d35a.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND
polyfills.fe38fa94cd758b43a148.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND
scripts.42e3c7ff6b40c17280bd.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND
vendor.7b7007a424e50f334b56.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND
main.5f1b617b49bf3e0d0eaa.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND
jquery-3.2.1.slim.min.js:2 jQuery.Deferred exception: $(...).select2 is not a function TypeError: $(...).select2 is not a function
    at HTMLDocument.<anonymous> (file:///E:/User/antos/Dokumenty/Projects/PCL%20VA/ProLight/ProLight.Client/dist/index.html:26:21)
    at j (https://code.jquery.com/jquery-3.2.1.slim.min.js:2:30203)
    at k (https://code.jquery.com/jquery-3.2.1.slim.min.js:2:30517) undefined
r.Deferred.exceptionHook @ jquery-3.2.1.slim.min.js:2
/E:/favicon.ico Failed to load resource: net::ERR_FILE_NOT_FOUND
jquery-3.2.1.slim.min.js:2 Uncaught TypeError: $(...).select2 is not a function
    at HTMLDocument.<anonymous> (index.html:26)
    at j (jquery-3.2.1.slim.min.js:2)
    at k (jquery-3.2.1.slim.min.js:2)
</code>```

I don't know where can be a problem and I don't know which files I must show you. Please tell me which files you want to see.

答:
I copied builded files to folder in server. I added web.config and added app to IIS DefaultAppPool. And I get this errors:

```<code>        GET http://server/inline.64b91d2d61fb76e9d35a.bundle.js
    server/:36 GET
http://server/polyfills.fe38fa94cd758b43a148.bundle.js
    server/:17 GET
http://server/styles.a530fc809103522200ce.bundle.css
    server/:36 GET
http://server/scripts.42e3c7ff6b40c17280bd.bundle.js
    server/:36 GET
http://server/vendor.7b7007a424e50f334b56.bundle.js
    server/:36 GET
http://server/main.5f1b617b49bf3e0d0eaa.bundle.js
    (index):36 GET
http://server/inline.64b91d2d61fb76e9d35a.bundle.js
    (index):36 GET
http://server/polyfills.fe38fa94cd758b43a148.bundle.js
    (index):36 GET
http://server/scripts.42e3c7ff6b40c17280bd.bundle.js
    (index):36 GET
http://server/vendor.7b7007a424e50f334b56.bundle.js
    (index):36 GET
http://server/main.5f1b617b49bf3e0d0eaa.bundle.js
    jquery-3.2.1.slim.min.js:2 jQuery.Deferred exception: $(...).select2 is not a function TypeError: $(...).select2 is not a function
        at HTMLDocument.<anonymous> (http://sigma913/ProLight.Client/:26:21)
        at j (https://code.jquery.com/jquery-3.2.1.slim.min.js:2:30203)
        at k (https://code.jquery.com/jquery-3.2.1.slim.min.js:2:30517) undefined
    r.Deferred.exceptionHook @ jquery-3.2.1.slim.min.js:2
    k @ jquery-3.2.1.slim.min.js:2
    jquery-3.2.1.slim.min.js:2 Uncaught TypeError: $(...).select2 is not a function
        at HTMLDocument.<anonymous> ((index):26)
        at j (jquery-3.2.1.slim.min.js:2)
        at k (jquery-3.2.1.slim.min.js:2)
</code>```

Here is my web.config:

```<code><configuration>
    <system.webServer>
        <handlers>
           <clear />
            <add
                name="StaticFile"
                path="*" verb="*"
                modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule"
                resourceType="Either"
                requireAccess="Read" />
        </handlers>
        <staticContent>
            <mimeMap fileExtension=".*" mimeType="application/octet-stream" />
        </staticContent>
    </system.webServer>
</configuration>
</code>```

Title: production build - dont open app

Body:
I am sorry for this short question. I don't know how to deploy angular2 app so I don't know what to write to help me. I need to deploy production. When I run this command npm build -prod, its ok, copy all js and html to dist folder, but when I open index.html in browser app don't start and in the log is this:

/E:/styles.a530fc809103522200ce.bundle.css Failed to load resource: net::ERR_FILE_NOT_FOUND
inline.64b91d2d61fb76e9d35a.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND
polyfills.fe38fa94cd758b43a148.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND
scripts.42e3c7ff6b40c17280bd.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND
vendor.7b7007a424e50f334b56.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND
main.5f1b617b49bf3e0d0eaa.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND
jquery-3.2.1.slim.min.js:2 jQuery.Deferred exception: $(...).select2 is not a function TypeError: $(...).select2 is not a function
    at HTMLDocument.<anonymous> (file:///E:/User/antos/Dokumenty/Projects/PCL%20VA/ProLight/ProLight.Client/dist/index.html:26:21)
    at j (https://code.jquery.com/jquery-3.2.1.slim.min.js:2:30203)
    at k (https://code.jquery.com/jquery-3.2.1.slim.min.js:2:30517) undefined
r.Deferred.exceptionHook @ jquery-3.2.1.slim.min.js:2
/E:/favicon.ico Failed to load resource: net::ERR_FILE_NOT_FOUND
jquery-3.2.1.slim.min.js:2 Uncaught TypeError: $(...).select2 is not a function
    at HTMLDocument.<anonymous> (index.html:26)
    at j (jquery-3.2.1.slim.min.js:2)
    at k (jquery-3.2.1.slim.min.js:2)

I don't know where can be a problem and I don't know which files I must show you. Please tell me which files you want to see.

Body:
I copied builded files to folder in server. I added web.config and added app to IIS DefaultAppPool. And I get this errors:

        GET http://server/inline.64b91d2d61fb76e9d35a.bundle.js
    server/:36 GET
http://server/polyfills.fe38fa94cd758b43a148.bundle.js
    server/:17 GET
http://server/styles.a530fc809103522200ce.bundle.css
    server/:36 GET
http://server/scripts.42e3c7ff6b40c17280bd.bundle.js
    server/:36 GET
http://server/vendor.7b7007a424e50f334b56.bundle.js
    server/:36 GET
http://server/main.5f1b617b49bf3e0d0eaa.bundle.js
    (index):36 GET
http://server/inline.64b91d2d61fb76e9d35a.bundle.js
    (index):36 GET
http://server/polyfills.fe38fa94cd758b43a148.bundle.js
    (index):36 GET
http://server/scripts.42e3c7ff6b40c17280bd.bundle.js
    (index):36 GET
http://server/vendor.7b7007a424e50f334b56.bundle.js
    (index):36 GET
http://server/main.5f1b617b49bf3e0d0eaa.bundle.js
    jquery-3.2.1.slim.min.js:2 jQuery.Deferred exception: $(...).select2 is not a function TypeError: $(...).select2 is not a function
        at HTMLDocument.<anonymous> (http://sigma913/ProLight.Client/:26:21)
        at j (https://code.jquery.com/jquery-3.2.1.slim.min.js:2:30203)
        at k (https://code.jquery.com/jquery-3.2.1.slim.min.js:2:30517) undefined
    r.Deferred.exceptionHook @ jquery-3.2.1.slim.min.js:2
    k @ jquery-3.2.1.slim.min.js:2
    jquery-3.2.1.slim.min.js:2 Uncaught TypeError: $(...).select2 is not a function
        at HTMLDocument.<anonymous> ((index):26)
        at j (jquery-3.2.1.slim.min.js:2)
        at k (jquery-3.2.1.slim.min.js:2)

Here is my web.config:

<configuration>
    <system.webServer>
        <handlers>
           <clear />
            <add
                name="StaticFile"
                path="*" verb="*"
                modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule"
                resourceType="Either"
                requireAccess="Read" />
        </handlers>
        <staticContent>
            <mimeMap fileExtension=".*" mimeType="application/octet-stream" />
        </staticContent>
    </system.webServer>
</configuration>


问:
Iterate Typed List in sections
I have the following list

```<code>Dim ordersToUpdate as New List(Of OrderUpdate)
</code>```

I am using a "For Each" to iterate and update a legacy DB

```<code>For Each order In ordersToUpdate

  UpdateDB(order)

Next
</code>```

I am having a LOCKING problem on the DB when the "ordersToUpdate" is large. Instead to puting a Threading.Thread.Sleep to pause, is there a proper way to break the list up into sections e.g iterating 100 at a time?

答:
```<code>Public Function SplitList(Of T)(ByVal list As List(Of T), ByVal size As Integer) As List(Of List(Of T))
        Dim result As New List(Of List(Of T))
        For i = 0 To CInt(Math.Ceiling(list.Count / size)) - 1
            result.Add(New List(Of T)(list.GetRange(i * size, Math.Min(size, list.Count - (i * size)))))
        Next
        Return result
    End Function
</code>```

Reference

Title: Iterate Typed List in sections

Body:
I have the following list

Dim ordersToUpdate as New List(Of OrderUpdate)

I am using a "For Each" to iterate and update a legacy DB

For Each order In ordersToUpdate

  UpdateDB(order)

Next

I am having a LOCKING problem on the DB when the "ordersToUpdate" is large. Instead to puting a Threading.Thread.Sleep to pause, is there a proper way to break the list up into sections e.g iterating 100 at a time?

Body:
Public Function SplitList(Of T)(ByVal list As List(Of T), ByVal size As Integer) As List(Of List(Of T))
        Dim result As New List(Of List(Of T))
        For i = 0 To CInt(Math.Ceiling(list.Count / size)) - 1
            result.Add(New List(Of T)(list.GetRange(i * size, Math.Min(size, list.Count - (i * size)))))
        Next
        Return result
    End Function

Reference


问:
Netbeans 8. Mark lines to go to them quickly
I'm looking for a way to mark lines in Netbeans 8.2 to be able to switch between them with a shortcut. For those who know Notepad++, you can mark lines by clicking next to the line number and switch between them just pressing F2. That's what I want.

If Netbeans doesn't have this useful shortcut, is there any plugin which make this possible?

Thanks in advance.

答: Netbeans has bookmarks feature. You can right-click on the left toolbar of required file, choose Bookmarks -> Toggle Bookmark (or press Ctrl+Shift+M) or press Toggle Bookmark button in the file top toolbar. Then you can navigate through bookmarks using the same popup (Bookmarks -> Next Bookmark, Bookmarks -> Previous Bookmark) or down/up buttons in the file top toolbar. But also you can use Ctrl+Shift+Period and Ctrl+Shift+Comma to navigate between bookmarks (you can change these shortcuts in the Tools -> Options -> Keymap popup).


问:
turbo c graphics no error but doesn't run
The following code doesn't have any error but it won't run. There's just a flash on the screen when I run it. It doesn't provide any output. what do I have to do?</p>

```<code>#include<graphics.h>
#include<conio.h>

void main()
{
    int gd = DETECT, gm;
    initgraph (&gd, &gm, "");
    setbkcolor (15);
    setcolor (0);
    settextjustify (1,1);
    settextstyle (3,0,12);
    outtextxy (getmaxx()/2, 1, "BATAAN PENINSULA STATE UNIVERSITY");
    outtextxy(getmaxx()/2, 3, "MAIN CAMPUS");
    settextstyle (3,0,10);
    outtextxy (getmaxx()/2, 5, "College of Engineering and Architecture");
    outtextxy (getmaxx()/2, 7, "Bachelor of Science in Civil Engineering(BSCE)");
    settextstyle (3,0,15);
    outtextxy (getmaxx()/2, getmaxy()/2, "COMPUTERIZED TUTORIAL SYSTEM");
    outtextxy (getmaxx()/2, 30, "(CORRECTION IN TAPING)");
    settextstyle (3,0,10);
    outtextxy (getmaxx()/2, getmaxy(), "Programmed by: BSCE-3A Group 8");

    getch();
    closegraph();
}
</code>```

答:
In initgrapgh, your "" are empty. They should have the path to the bgi library.
It should look something like this: </p>

```<code>initgraph(&gd, &gm, "C:\\TC\\BGI");
</code>```

Body:
The following code doesn't have any error but it won't run. There's just a flash on the screen when I run it. It doesn't provide any output. what do I have to do?

#include<graphics.h>
#include<conio.h>

void main()
{
    int gd = DETECT, gm;
    initgraph (&gd, &gm, "");
    setbkcolor (15);
    setcolor (0);
    settextjustify (1,1);
    settextstyle (3,0,12);
    outtextxy (getmaxx()/2, 1, "BATAAN PENINSULA STATE UNIVERSITY");
    outtextxy(getmaxx()/2, 3, "MAIN CAMPUS");
    settextstyle (3,0,10);
    outtextxy (getmaxx()/2, 5, "College of Engineering and Architecture");
    outtextxy (getmaxx()/2, 7, "Bachelor of Science in Civil Engineering(BSCE)");
    settextstyle (3,0,15);
    outtextxy (getmaxx()/2, getmaxy()/2, "COMPUTERIZED TUTORIAL SYSTEM");
    outtextxy (getmaxx()/2, 30, "(CORRECTION IN TAPING)");
    settextstyle (3,0,10);
    outtextxy (getmaxx()/2, getmaxy(), "Programmed by: BSCE-3A Group 8");

    getch();
    closegraph();
}

Body:
In initgrapgh, your "" are empty. They should have the path to the bgi library.
It should look something like this:

initgraph(&gd, &gm, "C:\\TC\\BGI");


问:
ndk-build :- How to get the exact path from calling $(abspath $(LOCAL_PATH)) in windows?
I am doing a sample native project.
I have two make files one is Android1.mk and another one is Android2.mk.
The second one is placed outside the project folder.My android studio project is located at

H:/Ndk_Dev/Demo

Android1.mk located at

H:/Ndk_Dev/Demo/app/src/main/jni

and Android2.mk is located at

H:/Ndk_Dev/externalJni

Android1.mk contains.

```<code>LOCAL_PATH := $(call my-dir)
MY_ROOT_PATH := $(abspath $(LOCAL_PATH)/../../../../../)
.......
.......
.......
include $(MY_ROOT_PATH)/externalJni/Android2.mk
</code>```

but while compiling, the path i got was

```<code>LOCAL_PATH    -------> H:/Ndk_Dev/Demo/app/src/main/jni
MY_ROOT_PATH  -------> H:/Ndk_Dev/Demo/app/src/main/H:/Ndk_Dev
</code>```

So it points to an invalid path for Android2.mk which was

```<code>H:/Ndk_Dev/Demo/app/src/main/H:/Ndk_Dev/externalJni/Android2.mk
</code>```

On my understanding the MY_ROOT_PATH should be H:/Ndk_Dev

Have anybody know any issue in calling $(abspath) on Windows.

答:
You should just call as following

```<code>MY_ROOT_PATH := $(abspath ../../../../../)
</code>```

It works for me.

Body:
I am doing a sample native project.
I have two make files one is Android1.mk and another one is Android2.mk.
The second one is placed outside the project folder.My android studio project is located at

H:/Ndk_Dev/Demo

Android1.mk located at

H:/Ndk_Dev/Demo/app/src/main/jni

and Android2.mk is located at

H:/Ndk_Dev/externalJni

Android1.mk contains.

LOCAL_PATH := $(call my-dir)
MY_ROOT_PATH := $(abspath $(LOCAL_PATH)/../../../../../)
.......
.......
.......
include $(MY_ROOT_PATH)/externalJni/Android2.mk

but while compiling, the path i got was

LOCAL_PATH    -------> H:/Ndk_Dev/Demo/app/src/main/jni
MY_ROOT_PATH  -------> H:/Ndk_Dev/Demo/app/src/main/H:/Ndk_Dev

So it points to an invalid path for Android2.mk which was

H:/Ndk_Dev/Demo/app/src/main/H:/Ndk_Dev/externalJni/Android2.mk

On my understanding the MY_ROOT_PATH should be H:/Ndk_Dev

Have anybody know any issue in calling $(abspath) on Windows.

Body:
You should just call as following

MY_ROOT_PATH := $(abspath ../../../../../)

It works for me.


问:
MySQL: How to get result from 2 different tables with 1 WHERE IN CLAUSE
I have 2 tables with different content and there is no way to join tables because there is no common identifier, but every table as 1 column with same content. I need to extract the content from these both colums and want to get ID's from each record that is the same. The following query extracts what I already know/have, but I don't get the ID's from the WHERE IN table.

Query

```<code>SELECT pd.products_id, pd.products_short_description
FROM products_description pd
WHERE pd.products_short_description IN (SELECT m.manufacturers_ean FROM manufacturers m)
</code>```

Result

```<code>ID | products_short_description
-------------------------------
2  | BMW
</code>```

This is what I need:

```<code>ID | products_short_description | ID | manufacturers_ean
--------------------------------------------------------
2  | BMW                        | 285| BMW
</code>```

答:
in this case What you do with where could be done whit inner join and so you could select the two column from manufacturers_ean   too</p>

```<code>SELECT pd.products_id, pd.products_short_description, m.ID m.manufacturers_ean
FROM products_description pd
INNER JOIN manufacturers m on m.manufacturers_ean  = pd.products_short_description
</code>```

Body:
I have 2 tables with different content and there is no way to join tables because there is no common identifier, but every table as 1 column with same content. I need to extract the content from these both colums and want to get ID's from each record that is the same. The following query extracts what I already know/have, but I don't get the ID's from the WHERE IN table.

Query

SELECT pd.products_id, pd.products_short_description
FROM products_description pd
WHERE pd.products_short_description IN (SELECT m.manufacturers_ean FROM manufacturers m)

Result

ID | products_short_description
-------------------------------
2  | BMW

This is what I need:

ID | products_short_description | ID | manufacturers_ean
--------------------------------------------------------
2  | BMW                        | 285| BMW

Body:
in this case What you do with where could be done whit inner join and so you could select the two column from manufacturers_ean   too

SELECT pd.products_id, pd.products_short_description, m.ID m.manufacturers_ean
FROM products_description pd
INNER JOIN manufacturers m on m.manufacturers_ean  = pd.products_short_description


问:
Select row After UIPickerView is loaded
I have an iPhone database app that loads a UIPickerView with data from a table.  I want to set the selected row to a particular row from the data in another table.

For example: Let's say I have a UIPickerView that is loaded with X number of names of the iPhone users' friends (the number of names is variable; it could be 1 or 1000 and all are entered into the database by the user). The iPhone user has a preference set that their current best friend is TED. I want the UIPickerView to be position to TED when displayed.

Where do I call selectRow?

I tried in viewDidAppear, but it was never called, in titleForRow which caused all kinds of strange behavior. viewDidLoad and viewWillAppear are out of the question, because I don't know what's in the datasource to the picker yet.

答:
For Swift it's simply:</p>

```<code>self.picker?.selectRow(0, inComponent: 0, animated: true)
</code>```

Title: Select row After UIPickerView is loaded

Body:
For Swift it's simply:

self.picker?.selectRow(0, inComponent: 0, animated: true)


问:
Bootstrap css conflict in wordpress admin page
if I enqueue Bootstrap CSS to my admin header it 'll apply to all options including my admin page.

```<code>add_action('admin_head', array(&$this,'enqueue_style_menu'));

public function enqueue_style_menu(){
    wp_register_style('ps-admin-css',plugins_url('css/admin-style.css', dirname(__FILE__)));
    wp_enqueue_style('ps-admin-css');
}
</code>```

this is my code is this is the right way to enqueue scripts to WP admin page?

答:
Check below code:

```<code>function load_custom_wp_admin_style($hook) {
    // Load only on ?page=mypluginname
    if($hook != 'toplevel_page_mypluginname') {
            return;
    }
    wp_enqueue_style( 'custom_wp_admin_css', plugins_url('admin-style.css', __FILE__) );
}

add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );
</code>```

Source: https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts

Body:
if I enqueue Bootstrap CSS to my admin header it 'll apply to all options including my admin page.

add_action('admin_head', array(&$this,'enqueue_style_menu'));

public function enqueue_style_menu(){
    wp_register_style('ps-admin-css',plugins_url('css/admin-style.css', dirname(__FILE__)));
    wp_enqueue_style('ps-admin-css');
}

this is my code is this is the right way to enqueue scripts to WP admin page?

Body:
Check below code:

function load_custom_wp_admin_style($hook) {
    // Load only on ?page=mypluginname
    if($hook != 'toplevel_page_mypluginname') {
            return;
    }
    wp_enqueue_style( 'custom_wp_admin_css', plugins_url('admin-style.css', __FILE__) );
}

add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );

Source: https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts

ContentLicense: CC BY-SA 4.0


问:
How should a list be represented in XML?
In XML, how should a list be represented?

With an enclosing list entity:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>
</code>```

Or without:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>
</code>```

答: For extensibility, I would use the first solution (the one with the children node).  If you ever wish to store any data about all of the children then you have a convenient node on which to place attributes.

OwnerDisplayName: Mat

Body:
In XML, how should a list be represented?

With an enclosing list entity:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>

Or without:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>

OwnerDisplayName: Jason Jackson


问:
Does C have a standard ABI?
From a discussion somewhere else:

C++ has no standard ABI (Application Binary Interface)

But neither does C, right?

On any given platform it pretty much does. It wouldn't be useful as the lingua franca for inter-language communication if it lacked one.

What's your take on this?

答:
C defines no ABI.  In fact, it bends over backwards to avoid defining an ABI.  Those people, who like me, who have spent most of their programming lives programming in C on 16/32/64 bit architectures with 8 bit bytes, 2's complement arithmetic and flat address spaces, will usually be quite surprised on reading the convoluted language of the current C standard.

For example, read the stuff about pointers.  The standard doesn't say anything so simple as "a pointer is an address" for that would be making an assumption about the ABI.  In particular, it allows for pointers being in different address spaces and having varying width.

An ABI is a mapping from the execution model of the language to a particular machine/operating system/compiler combination.  It makes no sense to define one in the language specification because that runs the risk of excluding C implementations on some architectures.

Title: Does C have a standard ABI?


问:
How read Chinese text from postgreSQL database using ado.net c#?
Try to read the chinese text but did not succeed.

I have used Npgsql as a Provider and npgqsl.dll as dll

I have used ADO.NET NpgsqlConnection,NpgsqlCommand,NpgsqlDataReader and NpgsqlDataAdapter class objects.

I want to read the chinese text which is stored in table of postgreSQL database.

Anyone help me.

答:
If your database has encoding SQL_ASCII, you are lost.

Other that that, set the connection string parameter Client Encoding to the value your .NET application expects.


问:
Casting an object to List<T> to be able to use extension methods
I have generated an extension method to display a IList<T> in a meaningful manner:

```<code>public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}
</code>```

To use this extension I can do this:

```<code>IList<someClass> myList = CreateList();
myList.ToDisplay();
</code>```

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

```<code>public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}
</code>```

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

答:
Why not create an overload, using object as parameter might not be the best thing to do.

For List:

```<code>public string CreateDisplayString<T>(IList<T> element)
{
  if (element == null)
    return string.Empty;

  return element.ToDisplay();
}
</code>```

For String:

```<code>public string CreateDisplayString(string element)
{
  if (element == null)
    return string.Empty;

  return element.ToString();
}
</code>```

Body:
I have generated an extension method to display a IList<T> in a meaningful manner:

public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}

To use this extension I can do this:

IList<someClass> myList = CreateList();
myList.ToDisplay();

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

Body:
Why not create an overload, using object as parameter might not be the best thing to do.

For List:

public string CreateDisplayString<T>(IList<T> element)
{
  if (element == null)
    return string.Empty;

  return element.ToDisplay();
}

For String:

public string CreateDisplayString(string element)
{
  if (element == null)
    return string.Empty;

  return element.ToString();
}


问:
Interface reference that specifies I need an object implementing 2 or more interfaces
Let us say I have this overly simple code here:

```<code>class Person
{
    public int age;
    public string name;
    public Person(int age, string name)
    {
        this.age = age;
        this.name = name;
    }
}
public class MySimpleDatabase
{
    List<Person> people;

    internal List<Person> People
    {
        get
        {
            if(people == null)
            {
                people = new List<Person>();
                people.Add(new Person(24, "ASD"));
                people.Add(new Person(35, "QWE"));
                people.Add(new Person(12, "MNB"));
            }
            return people;
        }
    }
}
public class ProcessPeopleConcrete
{
    public void WriteNames()
    {
        List<Person> people = new MySimpleDatabase().People;
        foreach (var person in people)
        {
            Console.WriteLine(person.name);
        }
    }
}
public class ProcessPeopleInterface
{
    public void WriteNames()
    {
        //question for here.
        IEnumerable<Person> people = new MySimpleDatabase().People;
        foreach (var person in people)
        {
            Console.WriteLine(person.name);
        }
    }
}
</code>```

Here I have the concrete processor as well as the interface based one. Here the interface processor is more maintainable of course, but as far as I know

```<code>   //edited here to clarify
</code>```

I can specify only one type for a variable that I require, in my case it is the IEnumerable<Person>.

What if I need something there that implements not one, but two interfaces at the same time, that have nothing to do with each other (one doesn't implement the other)?

So say I need any collection that has to implement both ICloneable and IEnumerator. In a comment it was put correctly that I could define another interface that implements both of them. But if I use pre-defined collections, I can't do that becuase then I won't be able to toss any of them as they obviously don't implement my custom made interface.

What sort of type would I specify in this case to my variable people (commented with "question here")? If there was a variable declaration like <IEnumerable, ICloneable> people; that would imaginarily mean I need something that implements both IEnumerable and ICloneable. But is there a language feature similar to that or it is what I said it is - imaginary only?

答:
This might not exactly be what you are looking for, but here's something similar to you concept. I created a simple function accepting a Tuple of IEnumerable and IList, then you can feed arguments to it:

```<code>public static void Foo(Tuple<IEnumerable<int>, IList<int>> complex)
    {
        foreach (var item in complex.Item1)
        {
            Console.WriteLine(item.ToString());
        }

        complex.Item2.Add(9);

    }
</code>```

A simple list:

```<code> List<int> ints = new List<int>
  {
      1,
      3,
      5,
      7
   };
</code>```

The function is then invoked by either first instantiating a separate variable, as I did, or writing the instantiation right into the Foo() function.

```<code>Tuple<IEnumerable<int>, IList<int>> tuple = Tuple.Create((ints as IEnumerable<int>), (ints as IList<int>));
Foo(tuple);
</code>```

I'm also interested in a real solution though, provided that there is one.

Body:
Let us say I have this overly simple code here:

class Person
{
    public int age;
    public string name;
    public Person(int age, string name)
    {
        this.age = age;
        this.name = name;
    }
}
public class MySimpleDatabase
{
    List<Person> people;

    internal List<Person> People
    {
        get
        {
            if(people == null)
            {
                people = new List<Person>();
                people.Add(new Person(24, "ASD"));
                people.Add(new Person(35, "QWE"));
                people.Add(new Person(12, "MNB"));
            }
            return people;
        }
    }
}
public class ProcessPeopleConcrete
{
    public void WriteNames()
    {
        List<Person> people = new MySimpleDatabase().People;
        foreach (var person in people)
        {
            Console.WriteLine(person.name);
        }
    }
}
public class ProcessPeopleInterface
{
    public void WriteNames()
    {
        //question for here.
        IEnumerable<Person> people = new MySimpleDatabase().People;
        foreach (var person in people)
        {
            Console.WriteLine(person.name);
        }
    }
}

Here I have the concrete processor as well as the interface based one. Here the interface processor is more maintainable of course, but as far as I know

   //edited here to clarify

I can specify only one type for a variable that I require, in my case it is the IEnumerable<Person>.

What if I need something there that implements not one, but two interfaces at the same time, that have nothing to do with each other (one doesn't implement the other)?

So say I need any collection that has to implement both ICloneable and IEnumerator. In a comment it was put correctly that I could define another interface that implements both of them. But if I use pre-defined collections, I can't do that becuase then I won't be able to toss any of them as they obviously don't implement my custom made interface.

What sort of type would I specify in this case to my variable people (commented with "question here")? If there was a variable declaration like <IEnumerable, ICloneable> people; that would imaginarily mean I need something that implements both IEnumerable and ICloneable. But is there a language feature similar to that or it is what I said it is - imaginary only?

Body:
This might not exactly be what you are looking for, but here's something similar to you concept. I created a simple function accepting a Tuple of IEnumerable and IList, then you can feed arguments to it:

public static void Foo(Tuple<IEnumerable<int>, IList<int>> complex)
    {
        foreach (var item in complex.Item1)
        {
            Console.WriteLine(item.ToString());
        }

        complex.Item2.Add(9);

    }

A simple list:

 List<int> ints = new List<int>
  {
      1,
      3,
      5,
      7
   };

The function is then invoked by either first instantiating a separate variable, as I did, or writing the instantiation right into the Foo() function.

Tuple<IEnumerable<int>, IList<int>> tuple = Tuple.Create((ints as IEnumerable<int>), (ints as IList<int>));
Foo(tuple);

I'm also interested in a real solution though, provided that there is one.


问:
Pre-commit SVN Hook + image optimization script
I was wondering if anyone had tried to make a pre-commit SVN hook to "smush" images before the commit using SmushIt, PunyPNG or any optimization script.

I tried looking on google but looks like nobody ever tried to do this.

I need advices and/or feedbacks.

Thanks !

答:
Pre-commit hooks should not modify the transaction that is about to be committed. From the svn book:

While hook scripts can do almost
  anything, there is one dimension in
  which hook script authors should show
  restraint: do not modify a commit
  transaction using hook scripts. While
  it might be tempting to use hook
  scripts to automatically correct
  errors, shortcomings, or policy
  violations present in the files being
  committed, doing so can cause
  problems. Subversion keeps client-side
  caches of certain bits of repository
  data, and if you change a commit
  transaction in this way, those caches
  become indetectably stale. This
  inconsistency can lead to surprising
  and unexpected behavior. Instead of
  modifying the transaction, you should
  simply validate the transaction in the
  pre-commit hook and reject the commit
  if it does not meet the desired
  requirements. As a bonus, your users
  will learn the value of careful,
  compliance-minded work habits.

A safer alternative would be to simply check images in the pre-commit hook, and refuse the commit if the criteria are not met. (You could still have a "smushing" script in your project and committers would just have to remember to run it manually before each commit that involves images.)

If you are sure you really want to modify commits on the fly, you might still be able to do it safely on the client side. For example, TortoiseSVN has client-side hook scripts.


答:
```<code>SELECT pd.products_id, pd.products_short_description, m.manufacturers_id, m.manufacturers_ean
FROM products_description pd INNER JOIN manufacturers m ON pd.products_short_description = m.manufacturers_ean;
</code>```

Title: MySQL: How to get result from 2 different tables with 1 WHERE IN CLAUSE


问:
HTML Javascript font size change
```<code><html>
<head>
  <meta charset="utf-8">
  <script>
    function test(){
      var name = document.getElementById('name').value;
      var snumber = document.getElementById('snumber').value;
      document.write("name="+name+"");
      document.write("&snumber="+snumber+"<br />");
    }
  </script>
</head>

<body>
   <h2>Example of sending data using POST</h2>
     Name :
   <input type="text" id="name"><br/>
     Student number:
   <input type="text" id="snumber"><br/><br/>
   <input type="button" value="submit" onclick="test();">
</body>
</html>
</code>```

I want to change the font size of 6th and 7th lines' result to h2 size
I can change in body section by putting

```<code> <h2></h2>
</code>```

however, it's not working in a script section. If I input data in name and snumber section, It connects to a new page that shows inputs like "name=David&snum=21467564" I want this font size to be h2 size!

答:
you can do something like this:</p>

```<code><script>
function test(){
 var name = document.getElementById('name').value;
 var snumber = document.getElementById('snumber').value;
 document.write("<h2>name="+name+"</h2>");
 document.write("<h2>&snumber="+snumber+"</h2><br />");
}
</script>
</code>```

Title: HTML Javascript font size change

Body:
  <meta charset="utf-8">

Example of sending data using POST

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

     Student number:
   <input type="text" id="snumber">

   <input type="button" value="submit" onclick="test();">

I want to change the font size of 6th and 7th lines' result to h2 size
I can change in body section by putting

however, it's not working in a script section. If I input data in name and snumber section, It connects to a new page that shows inputs like "name=David&snum=21467564" I want this font size to be h2 size!

Body:
you can do something like this:

<script>
function test(){
 var name = document.getElementById('name').value;
 var snumber = document.getElementById('snumber').value;
 document.write("<h2>name="+name+"</h2>");
 document.write("<h2>&snumber="+snumber+"</h2><br />");
}
</script>


问:
Kubernetes - Implementing Kubernetes Master HA solution in CentOS7
I am in the process of implementing an HA solution for Kubernetes Master nodes in a CentOS7 env.

My env looks like :

```<code>K8S_Master1 : 172.16.16.5
K8S_Master2 : 172.16.16.51
HAProxy     : 172.16.16.100
K8S_Minion1 : 172.16.16.50

etcd Version: 3.1.7
Kubernetes v1.5.2
CentOS Linux release 7.3.1611 (Core)
</code>```

My etcd cluster is setup properly and is in working state.

```<code>[root@master1 ~]# etcdctl cluster-health
member 282a4a2998aa4eb0 is healthy: got healthy result from http://172.16.16.51:2379
member dd3979c28abe306f is healthy: got healthy result from http://172.16.16.5:2379
member df7b762ad1c40191 is healthy: got healthy result from http://172.16.16.50:2379
</code>```

My K8S config for Master1 is :

```<code>[root@master1 ~]# cat /etc/kubernetes/apiserver
KUBE_API_ADDRESS="--address=0.0.0.0"
KUBE_ETCD_SERVERS="--etcd_servers=http://127.0.0.1:4001"
KUBE_SERVICE_ADDRESSES="--service-cluster-ip-range=10.100.0.0/16"
KUBE_ADMISSION_CONTROL="--admission_control=NamespaceLifecycle,NamespaceExists,LimitRanger,SecurityContextDeny,ResourceQuota"

[root@master1 ~]# cat /etc/kubernetes/config
KUBE_LOGTOSTDERR="--logtostderr=true"
KUBE_LOG_LEVEL="--v=0"
KUBE_ALLOW_PRIV="--allow_privileged=false"
KUBE_MASTER="--master=http://127.0.0.1:8080"

[root@master1 ~]# cat /etc/kubernetes/controller-manager
KUBE_CONTROLLER_MANAGER_ARGS="--leader-elect"

[root@master1 ~]# cat /etc/kubernetes/scheduler
KUBE_SCHEDULER_ARGS="--leader-elect"
</code>```

As for Master2 , I have configured it to be :

```<code>[root@master2 kubernetes]# cat apiserver
KUBE_API_ADDRESS="--address=0.0.0.0"
KUBE_ETCD_SERVERS="--etcd_servers=http://127.0.0.1:4001"
KUBE_SERVICE_ADDRESSES="--service-cluster-ip-range=10.100.0.0/16"
KUBE_ADMISSION_CONTROL="--admission_control=NamespaceLifecycle,NamespaceExists,LimitRanger,SecurityContextDeny,ResourceQuota"

[root@master2 kubernetes]# cat config
KUBE_LOGTOSTDERR="--logtostderr=true"
KUBE_LOG_LEVEL="--v=0"
KUBE_ALLOW_PRIV="--allow_privileged=false"
KUBE_MASTER="--master=http://127.0.0.1:8080"

[root@master2 kubernetes]# cat scheduler
KUBE_SCHEDULER_ARGS=""

[root@master2 kubernetes]# cat controller-manager
KUBE_CONTROLLER_MANAGER_ARGS=""
</code>```

Note that --leader-elect is only configured on Master1 as I want Master1 to be the leader.

My HA Proxy config is simple :

```<code>frontend K8S-Master
    bind 172.16.16.100:8080
    default_backend K8S-Master-Nodes

backend K8S-Master-Nodes
    mode        http
    balance     roundrobin
    server      master1 172.16.16.5:8080 check
    server      master2 172.16.16.51:8080 check
</code>```

Now I have directed my minion to connect to the Load Balancer IP rather than directly to the Master IP.

Config on Minion is :

```<code>[root@minion kubernetes]# cat /etc/kubernetes/config
KUBE_LOGTOSTDERR="--logtostderr=true"
KUBE_LOG_LEVEL="--v=0"
KUBE_ALLOW_PRIV="--allow_privileged=false"
KUBE_MASTER="--master=http://172.16.16.100:8080"
</code>```

On both Master nodes, I see the minion/node status as Ready

```<code>[root@master1 ~]# kubectl get nodes
NAME           STATUS    AGE
172.16.16.50   Ready     2h

[root@master2 ~]# kubectl get nodes
NAME           STATUS    AGE
172.16.16.50   Ready     2h
</code>```

I setup an example nginx pod using :

```<code>apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx
spec:
  replicas: 2
  selector:
    app: nginx
  template:
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
</code>```

I created the Replication Controller on Master1 using :

```<code>[root@master1 ~]# kubectl create -f nginx.yaml
</code>```

And on both Master nodes, I was able to see the pods created.

```<code>[root@master1 ~]# kubectl get po
NAME          READY     STATUS    RESTARTS   AGE
nginx-jwpxd   1/1       Running   0          29m
nginx-q613j   1/1       Running   0          29m

[root@master2 ~]# kubectl get po
NAME          READY     STATUS    RESTARTS   AGE
nginx-jwpxd   1/1       Running   0          29m
nginx-q613j   1/1       Running   0          29m
</code>```

Now logically thinking, if I were to take down Master1 node and delete the pods on Master2 , Master2 should recreate the pods. So this is what I do.

On Master1 :

```<code>[root@master1 ~]# systemctl stop kube-scheduler ; systemctl stop kube-apiserver ; systemctl stop kube-controller-manager
</code>```

On Master2 :

```<code>[root@slave1 kubernetes]# kubectl delete po --all
pod "nginx-l7mvc" deleted
pod "nginx-r3m58" deleted
</code>```

Now Master2 should create the pods since the Replication Controller is still up. But the new Pods are stuck in :

```<code>[root@master2 kubernetes]# kubectl get po
NAME          READY     STATUS        RESTARTS   AGE
nginx-l7mvc   1/1       Terminating   0          13m
nginx-qv6z9   0/1       Pending       0          13m
nginx-r3m58   1/1       Terminating   0          13m
nginx-rplcz   0/1       Pending       0          13m
</code>```

Ive waited a long time but the pods are stuck in this state.

But when I restart the services on Master1 :

```<code>[root@master1 ~]# systemctl start kube-scheduler ; systemctl start kube-apiserver ; systemctl start kube-controller-manager
</code>```

Then I see progress on Master1 :

```<code>NAME          READY     STATUS              RESTARTS   AGE
nginx-qv6z9   0/1       ContainerCreating   0          14m
nginx-rplcz   0/1       ContainerCreating   0          14m

[root@slave1 kubernetes]# kubectl get po
NAME          READY     STATUS    RESTARTS   AGE
nginx-qv6z9   1/1       Running   0          15m
nginx-rplcz   1/1       Running   0          15m
</code>```

Why doesnt Master2 recreate the pods ? This is the confusion that I am trying to figure out. Ive come a long way to setup a fully function HA setup but seems like almost there only if I can figure out this puzzle.

答:
In my opinion, the error comes from the fact that Master2 has no --leader-elect flag enabled. There can only be one scheduler and controller processes running at the same time, that is the reason of --leader-elect. The aim of this flag is to have them "compete" to see which of the scheduler and controller processes is active at a given time. As you did not set the flag in both master nodes, then there are two scheduler and controller processes active, and thus the conflicts you are experiencing. In order to fix the issue, I advise you to enable this flag in all of the master nodes.

What is more, according to the k8s documentation https://kubernetes.io/docs/tasks/administer-cluster/highly-available-master/#best-practices-for-replicating-masters-for-ha-clusters:

Do not use a cluster with two master replicas. Consensus on a two replica cluster requires both replicas running when changing persistent state. As a result, both replicas are needed and a failure of any replica turns cluster into majority failure state. A two-replica cluster is thus inferior, in terms of HA, to a single replica cluster.

Body:
I am in the process of implementing an HA solution for Kubernetes Master nodes in a CentOS7 env.

My env looks like :

K8S_Master1 : 172.16.16.5
K8S_Master2 : 172.16.16.51
HAProxy     : 172.16.16.100
K8S_Minion1 : 172.16.16.50

etcd Version: 3.1.7
Kubernetes v1.5.2
CentOS Linux release 7.3.1611 (Core)

My etcd cluster is setup properly and is in working state.

[root@master1 ~]# etcdctl cluster-health
member 282a4a2998aa4eb0 is healthy: got healthy result from http://172.16.16.51:2379
member dd3979c28abe306f is healthy: got healthy result from http://172.16.16.5:2379
member df7b762ad1c40191 is healthy: got healthy result from http://172.16.16.50:2379

My K8S config for Master1 is :

[root@master1 ~]# cat /etc/kubernetes/apiserver
KUBE_API_ADDRESS="--address=0.0.0.0"
KUBE_ETCD_SERVERS="--etcd_servers=http://127.0.0.1:4001"
KUBE_SERVICE_ADDRESSES="--service-cluster-ip-range=10.100.0.0/16"
KUBE_ADMISSION_CONTROL="--admission_control=NamespaceLifecycle,NamespaceExists,LimitRanger,SecurityContextDeny,ResourceQuota"

[root@master1 ~]# cat /etc/kubernetes/config
KUBE_LOGTOSTDERR="--logtostderr=true"
KUBE_LOG_LEVEL="--v=0"
KUBE_ALLOW_PRIV="--allow_privileged=false"
KUBE_MASTER="--master=http://127.0.0.1:8080"

[root@master1 ~]# cat /etc/kubernetes/controller-manager
KUBE_CONTROLLER_MANAGER_ARGS="--leader-elect"

[root@master1 ~]# cat /etc/kubernetes/scheduler
KUBE_SCHEDULER_ARGS="--leader-elect"

As for Master2 , I have configured it to be :

[root@master2 kubernetes]# cat apiserver
KUBE_API_ADDRESS="--address=0.0.0.0"
KUBE_ETCD_SERVERS="--etcd_servers=http://127.0.0.1:4001"
KUBE_SERVICE_ADDRESSES="--service-cluster-ip-range=10.100.0.0/16"
KUBE_ADMISSION_CONTROL="--admission_control=NamespaceLifecycle,NamespaceExists,LimitRanger,SecurityContextDeny,ResourceQuota"

[root@master2 kubernetes]# cat config
KUBE_LOGTOSTDERR="--logtostderr=true"
KUBE_LOG_LEVEL="--v=0"
KUBE_ALLOW_PRIV="--allow_privileged=false"
KUBE_MASTER="--master=http://127.0.0.1:8080"

[root@master2 kubernetes]# cat scheduler
KUBE_SCHEDULER_ARGS=""

[root@master2 kubernetes]# cat controller-manager
KUBE_CONTROLLER_MANAGER_ARGS=""

Note that --leader-elect is only configured on Master1 as I want Master1 to be the leader.

My HA Proxy config is simple :

frontend K8S-Master
    bind 172.16.16.100:8080
    default_backend K8S-Master-Nodes

backend K8S-Master-Nodes
    mode        http
    balance     roundrobin
    server      master1 172.16.16.5:8080 check
    server      master2 172.16.16.51:8080 check

Now I have directed my minion to connect to the Load Balancer IP rather than directly to the Master IP.

Config on Minion is :

[root@minion kubernetes]# cat /etc/kubernetes/config
KUBE_LOGTOSTDERR="--logtostderr=true"
KUBE_LOG_LEVEL="--v=0"
KUBE_ALLOW_PRIV="--allow_privileged=false"
KUBE_MASTER="--master=http://172.16.16.100:8080"

On both Master nodes, I see the minion/node status as Ready

[root@master1 ~]# kubectl get nodes
NAME           STATUS    AGE
172.16.16.50   Ready     2h

[root@master2 ~]# kubectl get nodes
NAME           STATUS    AGE
172.16.16.50   Ready     2h

I setup an example nginx pod using :

apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx
spec:
  replicas: 2
  selector:
    app: nginx
  template:
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80

I created the Replication Controller on Master1 using :

[root@master1 ~]# kubectl create -f nginx.yaml

And on both Master nodes, I was able to see the pods created.

[root@master1 ~]# kubectl get po
NAME          READY     STATUS    RESTARTS   AGE
nginx-jwpxd   1/1       Running   0          29m
nginx-q613j   1/1       Running   0          29m

[root@master2 ~]# kubectl get po
NAME          READY     STATUS    RESTARTS   AGE
nginx-jwpxd   1/1       Running   0          29m
nginx-q613j   1/1       Running   0          29m

Now logically thinking, if I were to take down Master1 node and delete the pods on Master2 , Master2 should recreate the pods. So this is what I do.

On Master1 :

[root@master1 ~]# systemctl stop kube-scheduler ; systemctl stop kube-apiserver ; systemctl stop kube-controller-manager

On Master2 :

[root@slave1 kubernetes]# kubectl delete po --all
pod "nginx-l7mvc" deleted
pod "nginx-r3m58" deleted

Now Master2 should create the pods since the Replication Controller is still up. But the new Pods are stuck in :

[root@master2 kubernetes]# kubectl get po
NAME          READY     STATUS        RESTARTS   AGE
nginx-l7mvc   1/1       Terminating   0          13m
nginx-qv6z9   0/1       Pending       0          13m
nginx-r3m58   1/1       Terminating   0          13m
nginx-rplcz   0/1       Pending       0          13m

Ive waited a long time but the pods are stuck in this state.

But when I restart the services on Master1 :

[root@master1 ~]# systemctl start kube-scheduler ; systemctl start kube-apiserver ; systemctl start kube-controller-manager

Then I see progress on Master1 :

NAME          READY     STATUS              RESTARTS   AGE
nginx-qv6z9   0/1       ContainerCreating   0          14m
nginx-rplcz   0/1       ContainerCreating   0          14m

[root@slave1 kubernetes]# kubectl get po
NAME          READY     STATUS    RESTARTS   AGE
nginx-qv6z9   1/1       Running   0          15m
nginx-rplcz   1/1       Running   0          15m

Why doesnt Master2 recreate the pods ? This is the confusion that I am trying to figure out. Ive come a long way to setup a fully function HA setup but seems like almost there only if I can figure out this puzzle.


答:
Query Will be :</p>

```<code> SELECT pd.products_id, pd.products_short_description, m.ID, m.manufacturers_ean
    FROM products_description pd,manufacturers m
    WHERE m.manufacturers_ean = pd.products_short_description
</code>```

Body:
Query Will be :

 SELECT pd.products_id, pd.products_short_description, m.ID, m.manufacturers_ean
    FROM products_description pd,manufacturers m
    WHERE m.manufacturers_ean = pd.products_short_description


问:
Access ng-model of element which is inside parent ng-repeat
SORRY FOR THE TITLE

So, let me explain you my scenario

Firstly there is one parent ng-repeat

Inside parent  ng-repeat I have 3 select options which are also loaded by ng-repeat

Problem I am facing is, I want to access ng-model of each select option and perform specific action on change. I tried setting ng-model but din't really worked well

Any suggestions are appreciated, really spent a lot time on this

<!DOCTYPE html>

{{item.propertyName}}

   Type of Riks {{$index}}
   <select ng-model="a.modelRiskType" ng-change="riskTypeChange(riskType)">
   <option ng-repeat="singleItem in item.riskTypeData">{{singleItem.riskType}}</option>
   </select>
   Type of damage {{$index}}
   <select ng-model="b.modelDamageType">
   <option ng-repeat="singleItem in item.damageData">{{singleItem.damage}}</option>
   </select>
   Type of Injury {{$index}}
   <select ng-model="injury">
   <option ng-repeat="singleItem in item.injuryData">{{singleItem.injury}}</option>
   </select>

```

答:
ng-repeat creates a child scope. So here you can pass the model of inner ng-repeat with a change event and use it.

E.g. Let the controller as

```<code>   var app = angular.module('plunker', []);

    app.controller('MainCtrl', function($scope) {
     $scope.details = [
        {
            "Name": "John",
            "CountryId": "1"
        },
        {
            "Name": "Dave",
            "CountryId": "2"
        }];

    $scope.Countries = [
        {
            "Id": "1",
            "Country": "USA"
        },
        {
            "Id": "2",
            "Country": "England"
        }];

    $scope.Change=function(id){
      alert(id)
    }
  });
</code>```

The HTML can be like this for getting the model value of select inside ng-repeat

```<code><body ng-app="plunker" ng-controller="MainCtrl">
  <div class="box" ng-repeat="item in details track by $index">
    <select ng-model="CountryModel"
     ng-options="option.Country as option.Country for option in Countries"
     ng-change=Change(CountryModel)>
   </select>
</div>
</code>```

Here is the demo plunker https://plnkr.co/edit/KbZ6fCbjHuFGlHugY8ff?p=preview

Body:
ng-repeat creates a child scope. So here you can pass the model of inner ng-repeat with a change event and use it.

E.g. Let the controller as

   var app = angular.module('plunker', []);

    app.controller('MainCtrl', function($scope) {
     $scope.details = [
        {
            "Name": "John",
            "CountryId": "1"
        },
        {
            "Name": "Dave",
            "CountryId": "2"
        }];

    $scope.Countries = [
        {
            "Id": "1",
            "Country": "USA"
        },
        {
            "Id": "2",
            "Country": "England"
        }];

    $scope.Change=function(id){
      alert(id)
    }
  });

The HTML can be like this for getting the model value of select inside ng-repeat

<body ng-app="plunker" ng-controller="MainCtrl">
  <div class="box" ng-repeat="item in details track by $index">
    <select ng-model="CountryModel"
     ng-options="option.Country as option.Country for option in Countries"
     ng-change=Change(CountryModel)>
   </select>
</div>

Here is the demo plunker https://plnkr.co/edit/KbZ6fCbjHuFGlHugY8ff?p=preview


问:
Dialog box size in Dynamics AX Report SSRS

Hi! Anyone knows how to resize the dialog box for the report ssrs controller? I tried in build() method in UIBuilder with
    dialogFieldGroup.widthMode(FormWidth::ColumnWidth);
I don't want to have scroll bar in the dialog.

答:
Try this steps:

1 - Get FormRun

```<code>dialog.formRun();
</code>```

2 - Lock FormRun

```<code>FormRun.lock();
</code>```

3 - Add/set yours controls.

4 - Call method resetSize()

```<code>FormRun.resetSize();
</code>```

5 - Unlock form

```<code>FormRun.unlock();
</code>```

If does not work try this

```<code>dialog.form().design(1).width("Your width value param);
</code>```

Body:
Try this steps:

1 - Get FormRun

dialog.formRun();

2 - Lock FormRun

FormRun.lock();

3 - Add/set yours controls.

4 - Call method resetSize()

FormRun.resetSize();

5 - Unlock form

FormRun.unlock();

If does not work try this

dialog.form().design(1).width("Your width value param);


问:
Sending Hebrew subject in php mail goes Klingon...?
I'm trying to send email with hebrew content/subject like so:

```<code>$to = 'email@email.com';
$subject = "איזה יום יפה היום";
$message = 'ממש יום יפה';

$headers = 'From: email@email.com' . "\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers);
</code>```

But what I get in the subject is more Klingon than modern Hebrew. The message itself comes out fine, it's just the subject that's all messed up.

What can I do? (I'm open to any hacks you got)

答: The Content-Type does only describe the message content but not the header. You need to apply the encoded-word encoding on the Subject value. See my answer on PHP email header subject encoding problem for further information.

Body:
I'm trying to send email with hebrew content/subject like so:

$to = 'email@email.com';
$subject = "איזה יום יפה היום";
$message = 'ממש יום יפה';

$headers = 'From: email@email.com' . "\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers);

But what I get in the subject is more Klingon than modern Hebrew. The message itself comes out fine, it's just the subject that's all messed up.

What can I do? (I'm open to any hacks you got)


答:
Simple! just add h2 element.

function test(){
 var name = document.getElementById('name').value;
 var snumber = document.getElementById('snumber').value;
 document.write("
name="+name+"
");
 document.write("
&snumber="+snumber+"
");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Example of sending data using POST</h2>
Name :
<input type="text" id="name"><br/>
Student number:
<input type="text" id="snumber"><br/><br/>
<input type="button" value="submit" onclick="test();"></code>```

Title: HTML Javascript font size change

Body:
Simple! just add h2 element.

function test(){
 var name = document.getElementById('name').value;
 var snumber = document.getElementById('snumber').value;
 document.write("<h2>name="+name+"</h2>");
 document.write("<h2>&snumber="+snumber+"</h2>");
}

<h2>Example of sending data using POST</h2>
Name :
<input type="text" id="name"><br/>
Student number:
<input type="text" id="snumber"><br/><br/>
<input type="button" value="submit" onclick="test();">


问:
How to serve different web component to IE 11
I've configured my "polymer build" (v 2.0) to transpile an ES5 version just for IE 11, but now I need to serve only that version for IE 11 users and the ES6 version for all other browsers. What's the best way to achieve this?

Ideally, I'd like to use just one import in whichever client pages use my custom element and have some logic on the server to dish out the appropriate version, but being a newbie to web components, I don't want roll my own solution (which will probably be nasty) if there's a "right way" of doing it (so far I haven't found it, but I'll keep searching).

Thanks.

答:
You should use a webserver, which is capable of detecting the browsers features.

The Polymer Team itself has released a library for nodeJS, which reads in your polymer.json file and looks in your builds directory and serves the correct build according to the features the browser of the client supports. The server itself supports H2 Push aswell, which is a nice feature.

https://github.com/Polymer/prpl-server-node

This is my builds configuration in polymer.json. It generates a different build for each capability. I cross checked, what versions of browsers support these technologies and added a build for each neccecary combination.

```<code>"builds": [{
  "name": "none",
  "browserCapabilities": [],
  "addServiceWorker": true,
  "bundle": true,
  "swPrecacheConfig": "sw-precache-config.js",
  "insertPrefetchLinks": true,
  "js": {
    "minify": true,
    "compile": true
  },
  "css": {"minify": true},
  "html": {"minify": true}
},
{
  "name": "noes6",
  "browserCapabilities": ["push", "serviceworker"],
  "addServiceWorker": true,
  "addPushManifest": true,
  "swPrecacheConfig": "sw-precache-config.js",
  "insertPrefetchLinks": true,
  "js": {
    "minify": true,
    "compile": true
  },
  "css": {"minify": true},
  "html": {"minify": true}
},
{
  "name": "nopush",
  "browserCapabilities": ["es2015", "serviceworker"],
  "addServiceWorker": true,
  "swPrecacheConfig": "sw-precache-config.js",
  "insertPrefetchLinks": true,
  "bundle": true,
  "js": {"minify": true},
  "css": {"minify": true},
  "html": {"minify": true}
},
{
  "name": "all",
  "browserCapabilities": ["es2015", "push", "serviceworker"],
  "addServiceWorker": true,
  "addPushManifest": true,
  "swPrecacheConfig": "sw-precache-config.js",
  "js": {"minify": true},
  "css": {"minify": true},
  "html": {"minify": true}
}]
</code>```

And a simple express server, which utilizes the prpl-server library for differential serving (bare in mind, that this is ES6 Syntax):

```<code>const prpl = require('prpl-server');
const express = require('express');
const config = require('./build/polymer.json');

const app = express();

app.get('/*', prpl.makeHandler('./build/', config));

app.listen(process.env.PORT || 80);
</code>```

Body:
You should use a webserver, which is capable of detecting the browsers features.

The Polymer Team itself has released a library for nodeJS, which reads in your polymer.json file and looks in your builds directory and serves the correct build according to the features the browser of the client supports. The server itself supports H2 Push aswell, which is a nice feature.

https://github.com/Polymer/prpl-server-node

This is my builds configuration in polymer.json. It generates a different build for each capability. I cross checked, what versions of browsers support these technologies and added a build for each neccecary combination.

"builds": [{
  "name": "none",
  "browserCapabilities": [],
  "addServiceWorker": true,
  "bundle": true,
  "swPrecacheConfig": "sw-precache-config.js",
  "insertPrefetchLinks": true,
  "js": {
    "minify": true,
    "compile": true
  },
  "css": {"minify": true},
  "html": {"minify": true}
},
{
  "name": "noes6",
  "browserCapabilities": ["push", "serviceworker"],
  "addServiceWorker": true,
  "addPushManifest": true,
  "swPrecacheConfig": "sw-precache-config.js",
  "insertPrefetchLinks": true,
  "js": {
    "minify": true,
    "compile": true
  },
  "css": {"minify": true},
  "html": {"minify": true}
},
{
  "name": "nopush",
  "browserCapabilities": ["es2015", "serviceworker"],
  "addServiceWorker": true,
  "swPrecacheConfig": "sw-precache-config.js",
  "insertPrefetchLinks": true,
  "bundle": true,
  "js": {"minify": true},
  "css": {"minify": true},
  "html": {"minify": true}
},
{
  "name": "all",
  "browserCapabilities": ["es2015", "push", "serviceworker"],
  "addServiceWorker": true,
  "addPushManifest": true,
  "swPrecacheConfig": "sw-precache-config.js",
  "js": {"minify": true},
  "css": {"minify": true},
  "html": {"minify": true}
}]

And a simple express server, which utilizes the prpl-server library for differential serving (bare in mind, that this is ES6 Syntax):

const prpl = require('prpl-server');
const express = require('express');
const config = require('./build/polymer.json');

const app = express();

app.get('/*', prpl.makeHandler('./build/', config));

app.listen(process.env.PORT || 80);


问:
window.location = window.location not work in IE7
To refresh the page I am using window.location = window.location it works fine with FireFox but not with IE7

any Idea??

Thanx

答:
Another simple solution is submitting empty form.. tested it now for IE, FF and Chrome:

```<code>function Reload() {
    var oForm = document.createElement("form");
    document.body.appendChild(oForm);
    oForm.submit();
}
</code>```

This way you can also read the posted data back from the server and submit it again without having the "confirmation" you mentioned, if it's relevant let us know what server side language you're using.

Body:
Another simple solution is submitting empty form.. tested it now for IE, FF and Chrome:

function Reload() {
    var oForm = document.createElement("form");
    document.body.appendChild(oForm);
    oForm.submit();
}

This way you can also read the posted data back from the server and submit it again without having the "confirmation" you mentioned, if it's relevant let us know what server side language you're using.


问:
SQL Server - Generating schedule list of repeating dates
We have a set of records where each record (Job) has a cycle (or frequency) in days that determines when the job appears on somebody's work list. E.G

Job A is generated every 7 days
Job B is generated every 14 days.

Each Job also has a start date.

I need to generate a table which contains all the possible job dates between a date range.

Here is my first part of code which generates the possible dates.

```<code>DECLARE @ForecastEarliestStartDate as DATETIME, @formStartDate as DATE,@formEndDate as DATE, @cycleInDays as BIGINT;

--set input param values
SET @ForecastEarliestStartDate = CAST('2017-07-03' AS DATETIME)
SET @formStartDate = getdate();
SET @formEndDate = getdate()+60;
SET @cycleInDays = 28;

WITH mycte AS
(
  SELECT @ForecastEarliestStartDate DateValue
  UNION ALL
  SELECT   DateValue + @cycleInDays
  FROM    mycte
  WHERE   DateValue + @cycleInDays < @formEndDate
)

SELECT  *
FROM    mycte
WHERE DateValue between @formStartDate and @formEndDate
OPTION (MAXRECURSION 0);
</code>```

This works fine as for a single Job, but how can I run it against a whole table of Jobs where @ForecastEarliestStartDate, @formStartDate, @formEndDate, @cycleInDays are fields in a table?

答:
The first thing to note is that a recursive CTE is one of the worst ways to generate a set or series (the worst being with explicit loops). Before going any further I would recommend reading the following series of articles:

Generate a set or sequence without loops – part 1

Generate a set or sequence without loops – part 2

Generate a set or sequence without loops – part 3

For example's sake, I will assume that you don't have a numbers table, and can't create one, so I will use the stacked CTE method. This query will get you a list of numbers from 0 to 99,999.

```<code>WITH N1 AS (SELECT N FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (N)),
N2 (N) AS (SELECT 1 FROM N1 AS N1 CROSS JOIN N1 AS N2),
N3 (N) AS (SELECT 1 FROM N2 AS N1 CROSS JOIN N2 AS N2)
SELECT N = ROW_NUMBER() OVER(ORDER  BY N) - 1
FROM N3
</code>```

If you need more numbers, you can add cross joins, if you need less you can remove them.

You can then just join these numbers to your table of jobs, each time adding (n * CycleInDays) to your start date:

```<code>WITH N1 AS (SELECT N FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (N)),
N2 (N) AS (SELECT 1 FROM N1 AS N1 CROSS JOIN N1 AS N2),
N3 (N) AS (SELECT 1 FROM N2 AS N1 CROSS JOIN N2 AS N2),
Numbers (Number) AS (SELECT N = ROW_NUMBER() OVER(ORDER  BY N) - 1 FROM N3)

SELECT  t.*,
        Iteration = n.Number,
        Date = DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
FROM    (VALUES
            (1, CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-09-03'), 28 ),
            (2, CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-09-03'), 19)
        ) t (JobID, ForecastEarliestStartDate, formStartDate, formEndDate, cycleInDays)
        INNER JOIN Numbers AS N
            ON t.formEndDate >= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
            AND t.formStartDate <= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
ORDER BY t.JobID, n.Number;
</code>```

This gives:

```<code>JobID   ForecastEarliestStartDate   formStartDate   formEndDate     cycleInDays     Iteration   Date
------------------------------------------------------------------------------------------------------------------
1       2017-07-03                  2017-07-03      2017-09-03      28              0           2017-07-03
1       2017-07-03                  2017-07-03      2017-09-03      28              1           2017-07-31
1       2017-07-03                  2017-07-03      2017-09-03      28              2           2017-08-28
2       2017-07-03                  2017-07-03      2017-09-03      19              0           2017-07-03
2       2017-07-03                  2017-07-03      2017-09-03      19              1           2017-07-22
2       2017-07-03                  2017-07-03      2017-09-03      19              2           2017-08-10
2       2017-07-03                  2017-07-03      2017-09-03      19              3           2017-08-29
</code>```

ADDENDUM

In response to the comments:

Great. So the general idea is that a loop is slower but if you genuinely don't know how man iterations there could be, what then? A loop?

No, as long as your numbers table is big enough to cover the maximum iterations then you don't need a loop. The example I have used with 100,000 rows is enough to cover 273 years of jobs that run every single day. I would have thought this would suffice.

BTW I do have a numbers table. Could you show me how to solve my problem without the need generating it please

Sure, simply remove the CTE that generates the numbers, and change the reference to the Numbers CTE to whatever your numbers table is called:

```<code>SELECT  t.*,
        Iteration = n.Number,
        Date = DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
FROM    (VALUES
            (1, CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-09-03'), 28 ),
            (2, CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-09-03'), 19)
        ) t (JobID, ForecastEarliestStartDate, formStartDate, formEndDate, cycleInDays)
        INNER JOIN dbo.Numbers AS N  ---- CHANGE TO WHATEVER YOUR NUMBERS TABLE IS CALLED
            ON t.formEndDate >= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
            AND t.formStartDate <= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
ORDER BY t.JobID, n.Number;
</code>```

Just noticed you are hard coding the Jobs into the query. They exist in another table, so not sure how this solves my issue

I have hard coded the jobs into the query just to emulate the table that you have (I have had to guess a bit since there is not much information about this table in the question). Simply replace the table-value constructor I have used with your actual table. e.g.

```<code>SELECT  t.*,
        Iteration = n.Number,
        Date = DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
FROM    dbo.[Your Job Table] AS t
        INNER JOIN dbo.[Your Numbers Table] AS N
            ON t.formEndDate >= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
            AND t.formStartDate <= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
ORDER BY t.JobID, n.Number;
</code>```

Body:
We have a set of records where each record (Job) has a cycle (or frequency) in days that determines when the job appears on somebody's work list. E.G

Job A is generated every 7 days
Job B is generated every 14 days.

Each Job also has a start date.

I need to generate a table which contains all the possible job dates between a date range.

Here is my first part of code which generates the possible dates.

DECLARE @ForecastEarliestStartDate as DATETIME, @formStartDate as DATE,@formEndDate as DATE, @cycleInDays as BIGINT;

--set input param values
SET @ForecastEarliestStartDate = CAST('2017-07-03' AS DATETIME)
SET @formStartDate = getdate();
SET @formEndDate = getdate()+60;
SET @cycleInDays = 28;

WITH mycte AS
(
  SELECT @ForecastEarliestStartDate DateValue
  UNION ALL
  SELECT   DateValue + @cycleInDays
  FROM    mycte
  WHERE   DateValue + @cycleInDays < @formEndDate
)

SELECT  *
FROM    mycte
WHERE DateValue between @formStartDate and @formEndDate
OPTION (MAXRECURSION 0);

This works fine as for a single Job, but how can I run it against a whole table of Jobs where @ForecastEarliestStartDate, @formStartDate, @formEndDate, @cycleInDays are fields in a table?

Body:
The first thing to note is that a recursive CTE is one of the worst ways to generate a set or series (the worst being with explicit loops). Before going any further I would recommend reading the following series of articles:

Generate a set or sequence without loops – part 1

Generate a set or sequence without loops – part 2

Generate a set or sequence without loops – part 3

For example's sake, I will assume that you don't have a numbers table, and can't create one, so I will use the stacked CTE method. This query will get you a list of numbers from 0 to 99,999.

WITH N1 AS (SELECT N FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (N)),
N2 (N) AS (SELECT 1 FROM N1 AS N1 CROSS JOIN N1 AS N2),
N3 (N) AS (SELECT 1 FROM N2 AS N1 CROSS JOIN N2 AS N2)
SELECT N = ROW_NUMBER() OVER(ORDER  BY N) - 1
FROM N3

If you need more numbers, you can add cross joins, if you need less you can remove them.

You can then just join these numbers to your table of jobs, each time adding (n * CycleInDays) to your start date:

WITH N1 AS (SELECT N FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (N)),
N2 (N) AS (SELECT 1 FROM N1 AS N1 CROSS JOIN N1 AS N2),
N3 (N) AS (SELECT 1 FROM N2 AS N1 CROSS JOIN N2 AS N2),
Numbers (Number) AS (SELECT N = ROW_NUMBER() OVER(ORDER  BY N) - 1 FROM N3)

SELECT  t.*,
        Iteration = n.Number,
        Date = DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
FROM    (VALUES
            (1, CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-09-03'), 28 ),
            (2, CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-09-03'), 19)
        ) t (JobID, ForecastEarliestStartDate, formStartDate, formEndDate, cycleInDays)
        INNER JOIN Numbers AS N
            ON t.formEndDate >= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
            AND t.formStartDate <= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
ORDER BY t.JobID, n.Number;

This gives:

JobID   ForecastEarliestStartDate   formStartDate   formEndDate     cycleInDays     Iteration   Date
------------------------------------------------------------------------------------------------------------------
1       2017-07-03                  2017-07-03      2017-09-03      28              0           2017-07-03
1       2017-07-03                  2017-07-03      2017-09-03      28              1           2017-07-31
1       2017-07-03                  2017-07-03      2017-09-03      28              2           2017-08-28
2       2017-07-03                  2017-07-03      2017-09-03      19              0           2017-07-03
2       2017-07-03                  2017-07-03      2017-09-03      19              1           2017-07-22
2       2017-07-03                  2017-07-03      2017-09-03      19              2           2017-08-10
2       2017-07-03                  2017-07-03      2017-09-03      19              3           2017-08-29

ADDENDUM

In response to the comments:

Great. So the general idea is that a loop is slower but if you genuinely don't know how man iterations there could be, what then? A loop?

No, as long as your numbers table is big enough to cover the maximum iterations then you don't need a loop. The example I have used with 100,000 rows is enough to cover 273 years of jobs that run every single day. I would have thought this would suffice.

BTW I do have a numbers table. Could you show me how to solve my problem without the need generating it please

Sure, simply remove the CTE that generates the numbers, and change the reference to the Numbers CTE to whatever your numbers table is called:

SELECT  t.*,
        Iteration = n.Number,
        Date = DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
FROM    (VALUES
            (1, CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-09-03'), 28 ),
            (2, CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-07-03'), CONVERT(DATE, '2017-09-03'), 19)
        ) t (JobID, ForecastEarliestStartDate, formStartDate, formEndDate, cycleInDays)
        INNER JOIN dbo.Numbers AS N  ---- CHANGE TO WHATEVER YOUR NUMBERS TABLE IS CALLED
            ON t.formEndDate >= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
            AND t.formStartDate <= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
ORDER BY t.JobID, n.Number;

Just noticed you are hard coding the Jobs into the query. They exist in another table, so not sure how this solves my issue

I have hard coded the jobs into the query just to emulate the table that you have (I have had to guess a bit since there is not much information about this table in the question). Simply replace the table-value constructor I have used with your actual table. e.g.

SELECT  t.*,
        Iteration = n.Number,
        Date = DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
FROM    dbo.[Your Job Table] AS t
        INNER JOIN dbo.[Your Numbers Table] AS N
            ON t.formEndDate >= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
            AND t.formStartDate <= DATEADD(DAY, n.Number * t.cycleInDays, t.ForecastEarliestStartDate)
ORDER BY t.JobID, n.Number;


问:
r - Count/percentage specific result per day
I have a dataset of about 15.000 observations spanning a couple of months.
Each date has a varying number of observations.
The result of each observation is either "1" or "0".

```<code>Obs   Reslt  Date         ....
1     0      19-02-2017
2     1      19-02-2017
3     0      19-02-2017
4     0      19-02-2017
5     1      20-02-2017
6     1      20-02-2017
7     0      20-02-2017
8     0      20-02-2017
</code>```

I would like to know the percentage of observation per day that have a result of "1".

In the example above the result would be:

```<code>19-02-2017 - 25%
20-02-2017 - 50%
</code>```

I was wondering if someone could help me with this.
Thank you!

答:
If your dataset is called df then

```<code>library(dplyr)
df %>%
  group_by(Date) %>%
  summarise(Perc = mean(Reslt)) %>%
  mutate(PercText = scales::percent(Perc))
</code>```

EDIT: I've also included a second column PercText which has the percentage stored as text.

Body:
I have a dataset of about 15.000 observations spanning a couple of months.
Each date has a varying number of observations.
The result of each observation is either "1" or "0".

Obs   Reslt  Date         ....
1     0      19-02-2017
2     1      19-02-2017
3     0      19-02-2017
4     0      19-02-2017
5     1      20-02-2017
6     1      20-02-2017
7     0      20-02-2017
8     0      20-02-2017

I would like to know the percentage of observation per day that have a result of "1".

In the example above the result would be:

19-02-2017 - 25%
20-02-2017 - 50%

I was wondering if someone could help me with this.
Thank you!

Body:
If your dataset is called df then

library(dplyr)
df %>%
  group_by(Date) %>%
  summarise(Perc = mean(Reslt)) %>%
  mutate(PercText = scales::percent(Perc))

EDIT: I've also included a second column PercText which has the percentage stored as text.


问:
How to access, in windows host, to the web interface of graylog running on a virtual ubuntu
I am having problems with this:
I installed graylog in ubuntu running on virtualbox as the documentation said (installing the required elasticsearch 2x and mongodb). The web interface is available at localhost:9000 by default and I can access to it after starting graylog in the virtual machine, but, and here comes my problem, I cannot access the interface in the windows host.

I am using NAT network configurations with port forwarding. Here you have a picture with the port forwarding configurations with the graylog port highlighted (the other are from other attempts):
Port-forwarding configurations in virtualbox

I have test the port forwarding with xampp, I installed it in the virtual ubuntu and then configured the port forwarding as in the image (port 2223). With xampp running in the virtual machine I went to 10.46.1.24:2223 in windows and it worked.
I have tried the other type of network configurations (bridged, host-only) and it did not worked.
I tried to use the virtual appliance provided in the graylog download page too, but it did not worked.

I do not know if I am missing some configiration or something and I read again the graylog documentation to see is I was missing something but I cannot solve this and that is why I am here asking for help.

Please tell me if you know how to configure this or if you deduced that I failed in some step.

答:
I have solved my problems, here goes what I did:

I changed (and uncommented) in th /etc/graylog/server/server.conf the variables:

web_listen_uri to have this: IP_virtualmachine:9000/

rest_listen_uri with: IP_vortualmachine:12900/

rest_transport_uri: IP_windowshost:12900

Then I forward ports in virtual box NAT configurations to the same ports (9000 and 12900) in windows.

The change in rest_transport_uri is because when I enter the web interface with ip:9000, the interface try to access to the rest api (by default the defined rest_listen_uri), and as the rest_listen_uri is defined in the IP of the virtual machine, in the host it will failed, and that is why I typed my windows host ip in the rest_transport_uri. This causes the web interface to stop working in the virtual machine but it will work in th windows host.

The rest_listen_uri and the web_listen_uri are specified in differents ports because it is needed in the port forwarding (because it is not possible to forward the rest api working in ip:9000/api/.