问:
using TwitPic + OAuth to upload a photo + tweet to Twitter (.NET C#) - why no tweet?
I'm uploading photos to TwitPic, using OAuth, from a .NET app written in C#.

The oAuth stuff is a little tricky. I found two bits of .NET code to handle it, but wasn't satisfied with either.  DotNetOpenAuth seemed to be pretty heavy, more than I need.  (Just wanna do oAuth signatures and token requests).  The OAuthBase.cs code seemed confused and inelegant to me. I had to pass 6 string parameters to methods, and if I got any out of order, woe be unto me.

So I wrote some code to do it myself, it's fairly small and it seems to work. It works to acquire "request tokens".  It works to pop the authorize web page and to acquire "access tokens".  It also works to upload photos to TwitPic.

All the HTTP responses come back as 200 or 201.

The upload HTTP message looks like this:

```<code>POST http://api.twitpic.com/2/upload.json HTTP/1.1
Content-Type: multipart/form-data; boundary=48cb9a6d-1f1d-432d-b6e3-307e32e8228a
X-Auth-Service-Provider: https://api.twitter.com/1/account/verify_credentials.json
X-Verify-Credentials-Authorization: OAuth realm="http://api.twitter.com/",
  oauth_consumer_key="Dv1er93yKzEMn74hZfPmJA",
  oauth_nonce="51fi305k",
  oauth_signature="4oWcmZcd%2F%2F81JslJ70xFXFm8%2BQs%3D",
  oauth_signature_method="HMAC-SHA1",
  oauth_timestamp="1292277715",
  oauth_token="59152613-z8EP4GoYS1Mgo3E29JfIqBnyTRlruAJs8Bkvs3q0T",
  oauth_version="1.0"
Host: api.twitpic.com
Content-Length: 14605
Expect: 100-continue
Connection: Keep-Alive

--48cb9a6d-1f1d-432d-b6e3-307e32e8228a
Content-Disposition: file; name="media"; filename="CropperCapture[10].jpg"
Content-Type: image/jpeg
....
--48cb9a6d-1f1d-432d-b6e3-307e32e8228a
Content-Disposition: form-data; name="key"

twitpic-api-key-here
--48cb9a6d-1f1d-432d-b6e3-307e32e8228a
Content-Disposition: form-data; name="message"

uploaded from Yappy. (at 12/13/2010 5:01:55 PM)
--48cb9a6d-1f1d-432d-b6e3-307e32e8228a--
</code>```

The json I get back from the upload is like this:

```<code>{"id":"3f0jeiw5",
 "text":"uploaded from Yappy. (at 12\/13\/2010 5:01:55 PM)",
 "url":"http:\\/twitpic.com\/3f0jeiw5",
 "width":257,
 "height":184,
 "size":14156,
 "type":"jpg",
 "timestamp":"Mon, 13 Dec 2010 22:02:06 +0000",
 "user":{
   "id":54591561,"screen_name":"bfavre"}
}
</code>```

But the problem is, after I upload the image to Twitpic, the image is available on TwitPic, but the associated message never appears on Twitter.

What gives?

I read in a random blog post that using TwitPic+oAuth requires me to post the tweet message in a separate HTTP transaction, direct to Twitter.  huh?  I thought the mail purpose of oAuth was to allow consumers to do things on my behalf - like allowing TwitPic to post a tweet for me.

Any hints?

EDIT

I'm learning a little more here.  This blog post from May 2010 suggests to me that using a value for X-Auth-Service-Provider of https://api.twitter.com/1/account/verify_credentials.json tells TwitPic to call "verify_credentials.json" on twitter.com when it gets my request.  If it really IS just verifying my credentials, this would explain why no Tweet is posted.

The post also suggests that swapping that out and replacing it with https://api.twitter.com/1/status/update.json should allow me to update Twitter via TwitPic with delegation.  But it is a forward-looking post - it says that getting this capability requires work on Twitter's part.

I haven't found an example HTTP message that does this yet. Anyone?

UPDATE

After converting the verify URL to https://api.twitter.com/1/status/update.json and using POST for the signature, I get a 401 response code:

```<code>{"errors":
  [{"code":401,
    "message":"Could not authenticate you (header rejected by twitter)."}]
}
</code>```

This is basically the same problem as described here, in the twitter dev forum.  The suggestion at the end of that thread was that the signature-computation algorithm is wrong, but I think that's incorrect, as my sig algorithm works with all other requests.

答:
I don't know the final answer, but I think that the changes that were described as coming "Real Soon Now" in Raffi's blog post of May 2010, have not actually been made, for whatever reason.

So in fact, using OAuth, you do have to post separately to TwitPic and to Twitter.

It's not hard to do this in Twitter, though.  Just do a POST on the statuses/update.xml URL.

```<code>private void Tweet(string message)
{
    var twitterUpdateUrlBase = "http://api.twitter.com/1/statuses/update.xml?status=";
    var url = twitterUpdateUrlBase + UrlEncode(message);

    var authzHeader = oauth.GenerateAuthzHeader(url, "POST");

    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.PreAuthenticate = true;
    request.AllowWriteStreamBuffering = true;
    request.Headers.Add("Authorization", authzHeader);

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        if (response.StatusCode != HttpStatusCode.OK)
        MessageBox.Show("There's been a problem trying to tweet:" +
                        Environment.NewLine +
                        response.StatusDescription +
                        Environment.NewLine +
                        Environment.NewLine +
                        "You will have to tweet manually." +
                        Environment.NewLine);
    }
}
</code>```

There are two tricky parts to that code:  First is the UrlEncode() call.  OAuth specifies that the urlencoding must use uppercase letters. The built-in .NET routine uses lowercase.  So be sure to upcase.

The second tricky part is is getting the OAuth Authorization Header. If you use an OAuth library package it should be pretty simple. For those who want a simple one, you can get one here: OAuth.cs. (Get the OAuthManager downloaD)

Body:
I'm uploading photos to TwitPic, using OAuth, from a .NET app written in C#.

The oAuth stuff is a little tricky. I found two bits of .NET code to handle it, but wasn't satisfied with either.  DotNetOpenAuth seemed to be pretty heavy, more than I need.  (Just wanna do oAuth signatures and token requests).  The OAuthBase.cs code seemed confused and inelegant to me. I had to pass 6 string parameters to methods, and if I got any out of order, woe be unto me.

So I wrote some code to do it myself, it's fairly small and it seems to work. It works to acquire "request tokens".  It works to pop the authorize web page and to acquire "access tokens".  It also works to upload photos to TwitPic.

All the HTTP responses come back as 200 or 201.

The upload HTTP message looks like this:

POST http://api.twitpic.com/2/upload.json HTTP/1.1
Content-Type: multipart/form-data; boundary=48cb9a6d-1f1d-432d-b6e3-307e32e8228a
X-Auth-Service-Provider: https://api.twitter.com/1/account/verify_credentials.json
X-Verify-Credentials-Authorization: OAuth realm="http://api.twitter.com/",
  oauth_consumer_key="Dv1er93yKzEMn74hZfPmJA",
  oauth_nonce="51fi305k",
  oauth_signature="4oWcmZcd%2F%2F81JslJ70xFXFm8%2BQs%3D",
  oauth_signature_method="HMAC-SHA1",
  oauth_timestamp="1292277715",
  oauth_token="59152613-z8EP4GoYS1Mgo3E29JfIqBnyTRlruAJs8Bkvs3q0T",
  oauth_version="1.0"
Host: api.twitpic.com
Content-Length: 14605
Expect: 100-continue
Connection: Keep-Alive

--48cb9a6d-1f1d-432d-b6e3-307e32e8228a
Content-Disposition: file; name="media"; filename="CropperCapture[10].jpg"
Content-Type: image/jpeg
....
--48cb9a6d-1f1d-432d-b6e3-307e32e8228a
Content-Disposition: form-data; name="key"

twitpic-api-key-here
--48cb9a6d-1f1d-432d-b6e3-307e32e8228a
Content-Disposition: form-data; name="message"

uploaded from Yappy. (at 12/13/2010 5:01:55 PM)
--48cb9a6d-1f1d-432d-b6e3-307e32e8228a--

The json I get back from the upload is like this:

{"id":"3f0jeiw5",
 "text":"uploaded from Yappy. (at 12\/13\/2010 5:01:55 PM)",
 "url":"http:\\/twitpic.com\/3f0jeiw5",
 "width":257,
 "height":184,
 "size":14156,
 "type":"jpg",
 "timestamp":"Mon, 13 Dec 2010 22:02:06 +0000",
 "user":{
   "id":54591561,"screen_name":"bfavre"}
}

But the problem is, after I upload the image to Twitpic, the image is available on TwitPic, but the associated message never appears on Twitter.

What gives?

I read in a random blog post that using TwitPic+oAuth requires me to post the tweet message in a separate HTTP transaction, direct to Twitter.  huh?  I thought the mail purpose of oAuth was to allow consumers to do things on my behalf - like allowing TwitPic to post a tweet for me.

Any hints?

EDIT

I'm learning a little more here.  This blog post from May 2010 suggests to me that using a value for X-Auth-Service-Provider of https://api.twitter.com/1/account/verify_credentials.json tells TwitPic to call "verify_credentials.json" on twitter.com when it gets my request.  If it really IS just verifying my credentials, this would explain why no Tweet is posted.

The post also suggests that swapping that out and replacing it with https://api.twitter.com/1/status/update.json should allow me to update Twitter via TwitPic with delegation.  But it is a forward-looking post - it says that getting this capability requires work on Twitter's part.

I haven't found an example HTTP message that does this yet. Anyone?

UPDATE

After converting the verify URL to https://api.twitter.com/1/status/update.json and using POST for the signature, I get a 401 response code:

{"errors":
  [{"code":401,
    "message":"Could not authenticate you (header rejected by twitter)."}]
}

This is basically the same problem as described here, in the twitter dev forum.  The suggestion at the end of that thread was that the signature-computation algorithm is wrong, but I think that's incorrect, as my sig algorithm works with all other requests.

Body:
I don't know the final answer, but I think that the changes that were described as coming "Real Soon Now" in Raffi's blog post of May 2010, have not actually been made, for whatever reason.

So in fact, using OAuth, you do have to post separately to TwitPic and to Twitter.

It's not hard to do this in Twitter, though.  Just do a POST on the statuses/update.xml URL.

private void Tweet(string message)
{
    var twitterUpdateUrlBase = "http://api.twitter.com/1/statuses/update.xml?status=";
    var url = twitterUpdateUrlBase + UrlEncode(message);

    var authzHeader = oauth.GenerateAuthzHeader(url, "POST");

    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.PreAuthenticate = true;
    request.AllowWriteStreamBuffering = true;
    request.Headers.Add("Authorization", authzHeader);

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        if (response.StatusCode != HttpStatusCode.OK)
        MessageBox.Show("There's been a problem trying to tweet:" +
                        Environment.NewLine +
                        response.StatusDescription +
                        Environment.NewLine +
                        Environment.NewLine +
                        "You will have to tweet manually." +
                        Environment.NewLine);
    }
}

There are two tricky parts to that code:  First is the UrlEncode() call.  OAuth specifies that the urlencoding must use uppercase letters. The built-in .NET routine uses lowercase.  So be sure to upcase.

The second tricky part is is getting the OAuth Authorization Header. If you use an OAuth library package it should be pretty simple. For those who want a simple one, you can get one here: OAuth.cs. (Get the OAuthManager downloaD)


来源: stackexchange

问:
Why do I give correct positional arguments but still get back a error message?
I've been having an issue with the following code:

```<code>class User:

def __init__(self, first_name, last_name, **profile):
    self.profile = profile
    self.first_name = first_name
    self.last_name = last_name`
    self.profile['first_name'] = first_name
    self.profile['last_name'] = last_name

def query(self, key):
    value = self.profile[key]
    print('Here is the result:' + '\n\t' + str(value))

class UserVip(User):
def __init__(self, first_name, last_name, **profile):
    super().__init__(self, first_name, last_name, **profile)

ron_weasley = UserVip('ron', 'weasley',
                  age=17,`enter code here
                  school='hogwarts'
                  )
</code>```

And when I ran it，I got back this error message

```<code>TypeError: __init__() takes 3 positional arguments but 4 were given
</code>```

But the '**profile'can recieve any number of arguments,can't it?Then I checked the arguments,and tried like this

```<code>ron_weasley = UserVip('ron', 'weasley',
                      school='hogwarts'
                      )
</code>```

It stil went wrong.I had also tried some other means and  been searching for a long time on net. But no use. Do I misundersand the init(),the inherit or the '**(dict)'?Please help or try to give some ideas how to solve this. Thanks in advance.

答:
You don't have to repeat the self argument in calling parent __init__

Ie should be:
super().__init__(first_name, last_name, **profile)

ContentLicense: CC BY-SA 3.0

Body:
I've been having an issue with the following code:

class User:

def __init__(self, first_name, last_name, **profile):
    self.profile = profile
    self.first_name = first_name
    self.last_name = last_name`
    self.profile['first_name'] = first_name
    self.profile['last_name'] = last_name

def query(self, key):
    value = self.profile[key]
    print('Here is the result:' + '\n\t' + str(value))

class UserVip(User):
def __init__(self, first_name, last_name, **profile):
    super().__init__(self, first_name, last_name, **profile)

ron_weasley = UserVip('ron', 'weasley',
                  age=17,`enter code here
                  school='hogwarts'
                  )

And when I ran it，I got back this error message

TypeError: __init__() takes 3 positional arguments but 4 were given

But the '**profile'can recieve any number of arguments,can't it?Then I checked the arguments,and tried like this

ron_weasley = UserVip('ron', 'weasley',
                      school='hogwarts'
                      )

It stil went wrong.I had also tried some other means and  been searching for a long time on net. But no use. Do I misundersand the init(),the inherit or the '**(dict)'?Please help or try to give some ideas how to solve this. Thanks in advance.


问:
Return Array from Embedded document
I have a data like in mongodb collection name property.

```<code>{
            "_id": "593a3d828e2ef100d1496e77",
            "feature_type": "house",
            "features": [
                {
                    "name": "h1"
                },
                {
                    "name": "h2"
                }
            ]
        }
</code>```

I want only

```<code> [
            {
                "name": "h1"
            },
            {
                "name": "h2"
            }
        ]
</code>```

as result i tried this by

```<code>req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1});
</code>```

this give

```<code>{
    "_id": "593a3d828e2ef100d1496e77",
    "features": [
        {
            "name": "Hotel"
        },
        {
            "name": "Apartment"
        }
    ]
}
</code>```

what can i do to get result as given above.

答:
You have to exclude the _id from your projection like here: </p>

```<code>req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1, _id:0});
</code>```

Title: Return Array from Embedded document

Body:
I have a data like in mongodb collection name property.

{
            "_id": "593a3d828e2ef100d1496e77",
            "feature_type": "house",
            "features": [
                {
                    "name": "h1"
                },
                {
                    "name": "h2"
                }
            ]
        }

I want only

 [
            {
                "name": "h1"
            },
            {
                "name": "h2"
            }
        ]

as result i tried this by

req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1});

this give

{
    "_id": "593a3d828e2ef100d1496e77",
    "features": [
        {
            "name": "Hotel"
        },
        {
            "name": "Apartment"
        }
    ]
}

what can i do to get result as given above.

Body:
You have to exclude the _id from your projection like here:

req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1, _id:0});


答:
I think you shouldn't have used self in super().__init__(self, first_name, last_name, **profile).
Here is a code which is working :

```<code>class User:
    def __init__(self, first_name, last_name, **profile):
        self.profile = profile
        self.first_name = first_name
        self.last_name = last_name
        self.profile['first_name'] = first_name
        self.profile['last_name'] = last_name

    def query(self, key):
        value = self.profile[key]
        print('Here is the result:' + '\n\t' + str(value))

class UserVip(User):
    def __init__(self, first_name, last_name, **profile):
        super().__init__(first_name, last_name, **profile)

ron_weasley = UserVip('ron', 'weasley', age=17, school='hogwarts')
ron_weasley.query('age')
</code>```

Title: Why do I give correct positional arguments but still get back a error message?

Body:
I think you shouldn't have used self in super().__init__(self, first_name, last_name, **profile).
Here is a code which is working :

class User:
    def __init__(self, first_name, last_name, **profile):
        self.profile = profile
        self.first_name = first_name
        self.last_name = last_name
        self.profile['first_name'] = first_name
        self.profile['last_name'] = last_name

    def query(self, key):
        value = self.profile[key]
        print('Here is the result:' + '\n\t' + str(value))

class UserVip(User):
    def __init__(self, first_name, last_name, **profile):
        super().__init__(first_name, last_name, **profile)

ron_weasley = UserVip('ron', 'weasley', age=17, school='hogwarts')
ron_weasley.query('age')


问:
When to use NSInteger vs. int
When should I be using NSInteger vs. int when developing for iOS?  I see in the Apple sample code they use NSInteger (or NSUInteger) when passing a value as an argument to a function or returning a value from a function.

```<code>- (NSInteger)someFunc;...
- (void)someFuncWithInt:(NSInteger)value;...
</code>```

But within a function they're just using int to track a value

```<code>for (int i; i < something; i++)
...

int something;
something += somethingElseThatsAnInt;
...
</code>```

I've read (been told) that NSInteger is a safe way to reference an integer in either a 64-bit or 32-bit environment so why use int at all?

答:
If you dig into NSInteger's implementation:

```<code>#if __LP64__
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
</code>```

Simply, the NSInteger typedef does a step for you: if the architecture is 32-bit, it uses int, if it is 64-bit, it uses long. Using NSInteger, you don't need to worry about the architecture that the program is running on.

Title: When to use NSInteger vs. int

Body:
When should I be using NSInteger vs. int when developing for iOS?  I see in the Apple sample code they use NSInteger (or NSUInteger) when passing a value as an argument to a function or returning a value from a function.

- (NSInteger)someFunc;...
- (void)someFuncWithInt:(NSInteger)value;...

But within a function they're just using int to track a value

for (int i; i < something; i++)
...

int something;
something += somethingElseThatsAnInt;
...

I've read (been told) that NSInteger is a safe way to reference an integer in either a 64-bit or 32-bit environment so why use int at all?

Body:
If you dig into NSInteger's implementation:

#if __LP64__
typedef long NSInteger;
#else
typedef int NSInteger;
#endif

Simply, the NSInteger typedef does a step for you: if the architecture is 32-bit, it uses int, if it is 64-bit, it uses long. Using NSInteger, you don't need to worry about the architecture that the program is running on.

ContentLicense: CC BY-SA 2.5


问:
sap.m.Input change event is triggered when clicking on CheckBox
I have two controls in my page i.e. sap.m.Input and sap.m.CheckBox. There is a change event attached to input field which gives an error bar if input text is not matched with the regex. This change event is triggered on clicking out of focus of the input field. Clicking on checkbox will hide this input and show a third control. Now if i enter something in input field which will not match regex and click on checkbox, It is triggering changeEvent of Input and not even selecting the checkbox. I tried many things like checking in change event whether checkbox is ticked or not, attached a click event on checkbox but no solution.
Please help me so that i will be able to determine the click on checkbox if the current focus is on input field

Here is an example at jsbin. Here error will be thrown if input text contains @ and change event is triggered.

```<code>var textInput = new sap.m.Text({text:"Area:"})
var inputField =new sap.m.Input("inptId",{
  change:function(oEvent){

    sap.ui.getCore().byId("barId").setVisible(oEvent.getParameters().value.includes("@"));

  }
});

var select  = new sap.m.Select("select",
                               {visible:false,
                                items:[new sap.ui.core.Item({text:"India"}),
                                      new sap.ui.core.Item({text:"US"}),
                                       new sap.ui.core.Item({text:"UK"})
                                      ]
                               })
var hBox = new sap.m.HBox({items:[textInput,inputField,select]})

  var bar = new sap.m.Bar("barId",{
    visible:false,
    contentMiddle:new sap.m.Text({text:"Error"})
  });

  var chkBox = new sap.m.CheckBox("chkBxId",{
  text:"Select from dropdown",
  select:function(oEvent){
    var selected = oEvent.getParameters().selected;
    sap.ui.getCore().byId("inptId").setVisible(!selected);
     sap.ui.getCore().byId("select").setVisible(selected);
    sap.ui.getCore().byId("barId").setVisible(false);
  }
});
var vBox = new sap.m.VBox({
  items:[bar,hBox,chkBox]
});
</code>```

In this example it is happening sometimes not always but in my project its happening always as there are lot of validations are happening in change event.

答:
@Ashish for focus out try following code.

```<code>this.getView().byId("input").addEventDelegate({
  onfocusout: function() {
    console.log("focus lost !!");
  }
}
</code>```

and for enter key press use following code

```<code>.addEventDelegate({
  onkeypress: function(e) {
    if (e.which === 13) {
      do your stuff;
    }
  }
})
</code>```

once focus is out it will trigger function provide in onfocusout and while on focus if enter key is pressed it will trigger function provide in onkeypress event.
Also you can merge this in one.

```<code>addEventDelegate({
  onkeypress: function(e) {
    console.log("Enter pressed fouse out", e.which);
  },
  onfocusout: function() {
    do your stuff!
  }
})
</code>```

Body:
I have two controls in my page i.e. sap.m.Input and sap.m.CheckBox. There is a change event attached to input field which gives an error bar if input text is not matched with the regex. This change event is triggered on clicking out of focus of the input field. Clicking on checkbox will hide this input and show a third control. Now if i enter something in input field which will not match regex and click on checkbox, It is triggering changeEvent of Input and not even selecting the checkbox. I tried many things like checking in change event whether checkbox is ticked or not, attached a click event on checkbox but no solution.
Please help me so that i will be able to determine the click on checkbox if the current focus is on input field

Here is an example at jsbin. Here error will be thrown if input text contains @ and change event is triggered.

var textInput = new sap.m.Text({text:"Area:"})
var inputField =new sap.m.Input("inptId",{
  change:function(oEvent){

    sap.ui.getCore().byId("barId").setVisible(oEvent.getParameters().value.includes("@"));

  }
});

var select  = new sap.m.Select("select",
                               {visible:false,
                                items:[new sap.ui.core.Item({text:"India"}),
                                      new sap.ui.core.Item({text:"US"}),
                                       new sap.ui.core.Item({text:"UK"})
                                      ]
                               })
var hBox = new sap.m.HBox({items:[textInput,inputField,select]})

  var bar = new sap.m.Bar("barId",{
    visible:false,
    contentMiddle:new sap.m.Text({text:"Error"})
  });

  var chkBox = new sap.m.CheckBox("chkBxId",{
  text:"Select from dropdown",
  select:function(oEvent){
    var selected = oEvent.getParameters().selected;
    sap.ui.getCore().byId("inptId").setVisible(!selected);
     sap.ui.getCore().byId("select").setVisible(selected);
    sap.ui.getCore().byId("barId").setVisible(false);
  }
});
var vBox = new sap.m.VBox({
  items:[bar,hBox,chkBox]
});

In this example it is happening sometimes not always but in my project its happening always as there are lot of validations are happening in change event.

Body:
@Ashish for focus out try following code.

this.getView().byId("input").addEventDelegate({
  onfocusout: function() {
    console.log("focus lost !!");
  }
}

and for enter key press use following code

.addEventDelegate({
  onkeypress: function(e) {
    if (e.which === 13) {
      do your stuff;
    }
  }
})

once focus is out it will trigger function provide in onfocusout and while on focus if enter key is pressed it will trigger function provide in onkeypress event.
Also you can merge this in one.

addEventDelegate({
  onkeypress: function(e) {
    console.log("Enter pressed fouse out", e.which);
  },
  onfocusout: function() {
    do your stuff!
  }
})

ContentLicense: CC BY-SA 4.0


问:
how to Add current file to "delete list" except file with mp3 and mp4 extension?
i want to make delete-list but except mp3 and mp4 file

my code is

error
Fatal error: Call to undefined function endsWith() in E:\xampp\htdocs\tes\index.php on line 39

```<code>    $files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
        $zip->close();

        // Add current file to "delete list"
        // delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
        if ($file->getFilename().endsWith(".mp3")) error at this code
        {
            $filesToDelete[] = $filePath;
        }
    }
}
</code>```

anyone help me please

答:
Again, checking the file-extension is unreliable. You should check the mime-type of the file with: mime_content_type.

In your code, you can do something like this:

```<code>// Add current file to "delete list"
        // delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
        if (mime_content_type($filePath) == "audio/mp3"))
        {
            $filesToDelete[] = $filePath;
        }
</code>```

But be carefull because there're a lot of different mime-types for mp3, as you can see here.

edit:
If you wan't to check for multiple mime_types you can use in_array:

```<code>if(in_array(mime_content_type($filePath), ['audio/mp3','audio/mpeg']))
</code>```

Body:
i want to make delete-list but except mp3 and mp4 file

my code is

error
Fatal error: Call to undefined function endsWith() in E:\xampp\htdocs\tes\index.php on line 39

    $files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
        $zip->close();

        // Add current file to "delete list"
        // delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
        if ($file->getFilename().endsWith(".mp3")) error at this code
        {
            $filesToDelete[] = $filePath;
        }
    }
}

anyone help me please

Body:
Again, checking the file-extension is unreliable. You should check the mime-type of the file with: mime_content_type.

In your code, you can do something like this:

// Add current file to "delete list"
        // delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
        if (mime_content_type($filePath) == "audio/mp3"))
        {
            $filesToDelete[] = $filePath;
        }

But be carefull because there're a lot of different mime-types for mp3, as you can see here.

edit:
If you wan't to check for multiple mime_types you can use in_array:

if(in_array(mime_content_type($filePath), ['audio/mp3','audio/mpeg']))


问:
jquery .css script doesn't work
Morning,
I'm trying to display a div onmouseover. I created a function but i don't know what is wrong. Could you help me please.

The HTML code:

```<code><!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="utf-8">
    <title> PHOTOGALLERY</title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <link rel="stylesheet" href="css/smoothness/jquery-ui-
         1.9.2.custom.css"/>
    <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
    <script src="http://malsup.github.com/jquery.cycle2.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.9.2.custom.js">
    </script>
    <script>
        function show_img_container() {
            $("#image_container").css("display", "block");
        }
    </script>
</head>
<body>
    <div id="div_container">
        <div id="div_image" class="cycle-slideshow">
            <img src="images/2.jpg" style="height:100%; width:100%">
            <img src="images/3.jpg" style="height:100%; width:100%">
            <img src="images/4.jpg" style="height:100%; width:100%">
            <img src="images/5.jpg" style="height:100%; width:100%">
        </div>
        <div id="image_container" onmouseover="show_img_container()"></div>
    </div>
</body>
</html>
</code>```

In the css file i have a image_container id where the attribute display is set to 'none';

答: You cant hover on div if its display is sets to none. </p>

Title: jquery .css script doesn't work

Body:
Morning,
I'm trying to display a div onmouseover. I created a function but i don't know what is wrong. Could you help me please.

The HTML code:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title> PHOTOGALLERY</title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <link rel="stylesheet" href="css/smoothness/jquery-ui-
         1.9.2.custom.css"/>

In the css file i have a image_container id where the attribute display is set to 'none';


答:
You can try this to return only features array values.

```<code>req.db.collection('FeatureSettings')
 .findOne({feature_type: req.params.feature_type}, {features:1, _id:0}).features;
</code>```

OR

```<code>// if you use mongoose can use
return req.db.collection('FeatureSettings')
  .findOne({feature_type: req.params.feature_type}, {features:1, _id:0})
  .exec()
  .then((result) => {
     return result.features;
  });
</code>```

Title: Return Array from Embedded document

Body:
You can try this to return only features array values.

req.db.collection('FeatureSettings')
 .findOne({feature_type: req.params.feature_type}, {features:1, _id:0}).features;

OR

// if you use mongoose can use
return req.db.collection('FeatureSettings')
  .findOne({feature_type: req.params.feature_type}, {features:1, _id:0})
  .exec()
  .then((result) => {
     return result.features;
  });


问:
One directional view pager with one fragment
I am facing one problem i have one fragment in view pager which i need to update when user slides from right to left, slide animation should be there with one fragment, here are some code that i am trying, the thing is i have view pager inside fragment as well.

Any suggestions code help will be appreciated.

here are some code that i have tried for one directional view pager

```<code>public class CustomViewPager extends ViewPager {

    private float initialXValue;
    private SwipeDirection direction;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.direction = SwipeDirection.all;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    private boolean IsSwipeAllowed(MotionEvent event) {
        if (this.direction == SwipeDirection.all) return true;

        if (direction == SwipeDirection.none)//disable any swipe
            return false;

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            initialXValue = event.getX();
            return true;
        }

        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            try {
                float diffX = event.getX() - initialXValue;
                if (diffX > 0 && direction == SwipeDirection.right) {
                    // swipe from left to right detected
                    return false;
                } else if (diffX < 0 && direction == SwipeDirection.left) {
                    // swipe from right to left detected
                    return false;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }

        return true;
    }

    public void setAllowedSwipeDirection(SwipeDirection direction) {
        this.direction = direction;
    }
}
</code>```

答:
You can try ViewPager's PageTransformer. And here the code example :

```<code>mViewPager.setPageTransformer(false, new FadePageTransformer());
</code>```

/**
         * Page Transform for hiding the DPAN in the next card which is partially visible.*/

```<code>    private class FadePageTransformer implements ViewPager.PageTransformer {

            public void transformPage(View view, float position) {
   // you can do your work when page is transform
            }
        }
</code>```

Hope is will help.

Body:
I am facing one problem i have one fragment in view pager which i need to update when user slides from right to left, slide animation should be there with one fragment, here are some code that i am trying, the thing is i have view pager inside fragment as well.

Any suggestions code help will be appreciated.

here are some code that i have tried for one directional view pager

public class CustomViewPager extends ViewPager {

    private float initialXValue;
    private SwipeDirection direction;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.direction = SwipeDirection.all;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    private boolean IsSwipeAllowed(MotionEvent event) {
        if (this.direction == SwipeDirection.all) return true;

        if (direction == SwipeDirection.none)//disable any swipe
            return false;

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            initialXValue = event.getX();
            return true;
        }

        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            try {
                float diffX = event.getX() - initialXValue;
                if (diffX > 0 && direction == SwipeDirection.right) {
                    // swipe from left to right detected
                    return false;
                } else if (diffX < 0 && direction == SwipeDirection.left) {
                    // swipe from right to left detected
                    return false;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }

        return true;
    }

    public void setAllowedSwipeDirection(SwipeDirection direction) {
        this.direction = direction;
    }
}

Body:
You can try ViewPager's PageTransformer. And here the code example :

mViewPager.setPageTransformer(false, new FadePageTransformer());

/**
         * Page Transform for hiding the DPAN in the next card which is partially visible.*/

    private class FadePageTransformer implements ViewPager.PageTransformer {

            public void transformPage(View view, float position) {
   // you can do your work when page is transform
            }
        }

Hope is will help.


问:
JQuery UI Datepicker Disable Month on Select
I have a datepicker assigned to several fields with an array of specific dates already disabled in my beforeShowDay attribute.

```<code>.datepicker({ beforeShowDay: disablePaymentDates, minDate: 0, maxDate: afterSixMonths });
</code>```

I'm attempting to disable the month of the date the user selects across all datepickers. Is there anyway to do this?

答:
Or you can disable date range with using moment.js</p>

```<code>var disableRangeStartDate = '2017-10-29';
var disableRangeEndDate = '2018-04-18';

.datepicker({
isInvalidDate: function(arg){
      var thisMonth = arg._d.getMonth()+1;
      if (thisMonth<10){thisMonth = "0"+thisMonth;}
      var thisDate = arg._d.getDate();
      if (thisDate<10){thisDate = "0"+thisDate;}
      var thisYear = arg._d.getYear()+1900;
      var thisCompare = thisYear +"-"+ thisMonth +"-"+ thisDate;

     return moment(thisCompare).isBetween(disableRangeStartDate, disableRangeEndDate);
      }
});
</code>```

Body:
I have a datepicker assigned to several fields with an array of specific dates already disabled in my beforeShowDay attribute.

.datepicker({ beforeShowDay: disablePaymentDates, minDate: 0, maxDate: afterSixMonths });

I'm attempting to disable the month of the date the user selects across all datepickers. Is there anyway to do this?

Body:
Or you can disable date range with using moment.js

var disableRangeStartDate = '2017-10-29';
var disableRangeEndDate = '2018-04-18';

.datepicker({
isInvalidDate: function(arg){
      var thisMonth = arg._d.getMonth()+1;
      if (thisMonth<10){thisMonth = "0"+thisMonth;}
      var thisDate = arg._d.getDate();
      if (thisDate<10){thisDate = "0"+thisDate;}
      var thisYear = arg._d.getYear()+1900;
      var thisCompare = thisYear +"-"+ thisMonth +"-"+ thisDate;

     return moment(thisCompare).isBetween(disableRangeStartDate, disableRangeEndDate);
      }
});


问:
Spring Boot use SystemTray Icons
I am setting up a Spring Boot Application and would like to have the host have access to a System Tray Icon with access to some bean Information.

I currently Tried to Create a Bean for my SystemTrayIcon with the @Autowired details. However When I try to add the SystemTrayIcon I get the following Exception:

```<code>Caused by: java.awt.HeadlessException
    at java.awt.TrayIcon.<init>(Unknown Source)
    at java.awt.TrayIcon.<init>(Unknown Source)
    at java.awt.TrayIcon.<init>(Unknown Source)
    at hermes.subsrciber.systemTray.HermesTrayIcon.<init>(HermesTrayIcon.java:36)
    at hermes.subscriber.boot.AppStarter.trayIcon(AppStarter.java:83)
    at hermes.subscriber.boot.AppStarter$$EnhancerBySpringCGLIB$$c4f80849.CGLIB$trayIcon$3(<generated>)
    at hermes.subscriber.boot.AppStarter$$EnhancerBySpringCGLIB$$c4f80849$$FastClassBySpringCGLIB$$d62ab0bd.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
    at hermes.subscriber.boot.AppStarter$$EnhancerBySpringCGLIB$$c4f80849.trayIcon(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
    ... 17 more
</code>```

Is there any way that a SpringBoot Application can have access to System Tray Icons?

I believe I CAN simply define it in the Main method (alongisde the SpringApplication.run) however I would not be able to autowire my properties.

Is this setup possible?

答:
If anyone wants the full code...

```<code>import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.annotation.PostConstruct;
import javax.swing.ImageIcon;

import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

public class MyTrayIcon extends TrayIcon {

    private static final String IMAGE_PATH = "/PATH.png";
    private static final String TOOLTIP = "Running";
    private PopupMenu popup;
    final SystemTray tray;

    public MyTrayIcon(){
        super(createImage(IMAGE_PATH,TOOLTIP),TOOLTIP);
        popup = new PopupMenu();
        tray = SystemTray.getSystemTray();
        try {
            setup();
        } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @PostConstruct
    private void setup() throws AWTException{
        // Create a pop-up menu components
        MenuItem exitItem = new MenuItem("Exit");
        popup.add(exitItem);
        exitItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                final int exitCode = 0;
                ExitCodeGenerator exitCodeGenerator = new ExitCodeGenerator() {

                    @Override
                    public int getExitCode() {
                      return exitCode;
                    }

                  };

                  tray.remove(MyTrayIcon.this);
                  SpringApplication.exit(Application.context, exitCodeGenerator);
            }
        });
        // popup.addSeparator();
        setPopupMenu(popup);
        tray.add(this);

    }

    protected static Image createImage(String path, String description){

        URL imageURL = MyTrayIcon.class.getResource(path);
        if(imageURL == null){
            System.err.println("Failed Creating Image. Resource not found: "+path);
            return null;
        }else {
            return new ImageIcon(imageURL,description).getImage();
        }
    }
}
</code>```

And in your Application.java:

```<code>import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static ConfigurableApplicationContext context;

    public static void main(String[] args) {
        //SpringApplication.run(Application.class, args);

        SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class);
        builder.headless(false);
        context = builder.run(args);

        MyTrayIcon m = new MyTrayIcon();
    }
}
</code>```

Title: Spring Boot use SystemTray Icons

Body:
I am setting up a Spring Boot Application and would like to have the host have access to a System Tray Icon with access to some bean Information.

I currently Tried to Create a Bean for my SystemTrayIcon with the @Autowired details. However When I try to add the SystemTrayIcon I get the following Exception:

Caused by: java.awt.HeadlessException
    at java.awt.TrayIcon.<init>(Unknown Source)
    at java.awt.TrayIcon.<init>(Unknown Source)
    at java.awt.TrayIcon.<init>(Unknown Source)
    at hermes.subsrciber.systemTray.HermesTrayIcon.<init>(HermesTrayIcon.java:36)
    at hermes.subscriber.boot.AppStarter.trayIcon(AppStarter.java:83)
    at hermes.subscriber.boot.AppStarter$$EnhancerBySpringCGLIB$$c4f80849.CGLIB$trayIcon$3(<generated>)
    at hermes.subscriber.boot.AppStarter$$EnhancerBySpringCGLIB$$c4f80849$$FastClassBySpringCGLIB$$d62ab0bd.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
    at hermes.subscriber.boot.AppStarter$$EnhancerBySpringCGLIB$$c4f80849.trayIcon(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
    ... 17 more

Is there any way that a SpringBoot Application can have access to System Tray Icons?

I believe I CAN simply define it in the Main method (alongisde the SpringApplication.run) however I would not be able to autowire my properties.

Is this setup possible?

Body:
If anyone wants the full code...

import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.annotation.PostConstruct;
import javax.swing.ImageIcon;

import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

public class MyTrayIcon extends TrayIcon {

    private static final String IMAGE_PATH = "/PATH.png";
    private static final String TOOLTIP = "Running";
    private PopupMenu popup;
    final SystemTray tray;

    public MyTrayIcon(){
        super(createImage(IMAGE_PATH,TOOLTIP),TOOLTIP);
        popup = new PopupMenu();
        tray = SystemTray.getSystemTray();
        try {
            setup();
        } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @PostConstruct
    private void setup() throws AWTException{
        // Create a pop-up menu components
        MenuItem exitItem = new MenuItem("Exit");
        popup.add(exitItem);
        exitItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                final int exitCode = 0;
                ExitCodeGenerator exitCodeGenerator = new ExitCodeGenerator() {

                    @Override
                    public int getExitCode() {
                      return exitCode;
                    }

                  };

                  tray.remove(MyTrayIcon.this);
                  SpringApplication.exit(Application.context, exitCodeGenerator);
            }
        });
        // popup.addSeparator();
        setPopupMenu(popup);
        tray.add(this);

    }

    protected static Image createImage(String path, String description){

        URL imageURL = MyTrayIcon.class.getResource(path);
        if(imageURL == null){
            System.err.println("Failed Creating Image. Resource not found: "+path);
            return null;
        }else {
            return new ImageIcon(imageURL,description).getImage();
        }
    }
}

And in your Application.java:

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static ConfigurableApplicationContext context;

    public static void main(String[] args) {
        //SpringApplication.run(Application.class, args);

        SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class);
        builder.headless(false);
        context = builder.run(args);

        MyTrayIcon m = new MyTrayIcon();
    }
}


问:
How can I compare two arrays to fill a third?
Imagine I have an array containing the following values:

```<code>$indexes = [ 'Hello' , 'Hoi', 'Ola' , 'Shalom' , 'Salaam'];
</code>```

Furthermore I also have  an incomplete array:

```<code>$values = ['Hello' => 2, 'Ola' => 20 ];
</code>```

How can I merge these arrays to get a result displaying all indexes with their values, and 0 when no value is found?

```<code>$desiredResult = [
 'Hello' => 2,
 'Hoi' => 0,
 'Ola' => 20 ,
 'Shalom' => 0,
 'Salaam' => 0
]
</code>```

答:
The function you're looking for is array_combine which works like
array_combine($indexes, $values)

Body:
Imagine I have an array containing the following values:

$indexes = [ 'Hello' , 'Hoi', 'Ola' , 'Shalom' , 'Salaam'];

Furthermore I also have  an incomplete array:

$values = ['Hello' => 2, 'Ola' => 20 ];

How can I merge these arrays to get a result displaying all indexes with their values, and 0 when no value is found?

$desiredResult = [
 'Hello' => 2,
 'Hoi' => 0,
 'Ola' => 20 ,
 'Shalom' => 0,
 'Salaam' => 0
]


问:
Guava EventBus Multiple subscribers same tpe
```<code>import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

public class Test {

    public static class Processing { }
    public static class ProcessingResults { }
    public static class ProcessingFinished { }

    public static EventBus bus = new EventBus();

    @Subscribe
    public void receiveStartRequest(Processing evt) {
        System.out.println("Got processing request - starting processing");
    }

    @Subscribe
    public void processingStarted(Processing evt) {
        System.out.println("Processing has started");
    }

    @Subscribe
    public void resultsReceived(ProcessingResults evt) {
        System.out.println("got results");
    }

    @Subscribe
    public void processingComplete(ProcessingFinished evt) {
        System.out.println("Processing has completed");
    }

    public static void main(String[] args) {
        Test t = new Test();
        bus.register(t);
        bus.post(new Processing());
    }
}
</code>```

So, in above example, it can be seen that there are 2 subscribers accepting same type Processing. Now, at the time of post(), which all functions will get called? If the 2 functions receiveStartRequest and processingStarted will get called, then in which order they will be get called?

答:
Both your methods will be called and in no predefinite order.

To counter this, just create two extra classes: ProcessingStarted and ProcessingRequested.

```<code>public class ProcessingStarted {
  private Processing processing;
  // Constructors
  // Getters/Setters
}

public class ProcessingStarted {
  private Processing processing;
  // Constructors
  // Getters/Setters
}
</code>```

Then call post(new ProcessingRequested(processing)) and post(new ProcessingStarted(processing)) when needed, instead of a single post(processing).

Body:
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

public class Test {

    public static class Processing { }
    public static class ProcessingResults { }
    public static class ProcessingFinished { }

    public static EventBus bus = new EventBus();

    @Subscribe
    public void receiveStartRequest(Processing evt) {
        System.out.println("Got processing request - starting processing");
    }

    @Subscribe
    public void processingStarted(Processing evt) {
        System.out.println("Processing has started");
    }

    @Subscribe
    public void resultsReceived(ProcessingResults evt) {
        System.out.println("got results");
    }

    @Subscribe
    public void processingComplete(ProcessingFinished evt) {
        System.out.println("Processing has completed");
    }

    public static void main(String[] args) {
        Test t = new Test();
        bus.register(t);
        bus.post(new Processing());
    }
}

So, in above example, it can be seen that there are 2 subscribers accepting same type Processing. Now, at the time of post(), which all functions will get called? If the 2 functions receiveStartRequest and processingStarted will get called, then in which order they will be get called?

Body:
Both your methods will be called and in no predefinite order.

To counter this, just create two extra classes: ProcessingStarted and ProcessingRequested.

public class ProcessingStarted {
  private Processing processing;
  // Constructors
  // Getters/Setters
}

public class ProcessingStarted {
  private Processing processing;
  // Constructors
  // Getters/Setters
}

Then call post(new ProcessingRequested(processing)) and post(new ProcessingStarted(processing)) when needed, instead of a single post(processing).


问:
How to make_pair or make_tuple with one of the elements being a union?
I have a union declaration, It is simple:

```<code>union VariableType
{
    bool Bool;
    int64_t Int;
    double Double;
    std::string* String;
};
</code>```

In my header file I use this union inside some complex data types like this:

```<code>extern std::map<std::string, std::tuple<uint8_t, VariableType, VariableType>> PredefinedVariables;
extern std::map<std::string, std::pair<uint8_t, VariableType>> UserVariables;
</code>```

in a cpp file I try to initialize the maps with brace initialization as follows:

```<code>std::map<std::string, std::tuple<uint8_t, VariableType, VariableType>> PredefinedVariables
{
    {"num_threads", std::make_tuple(1, {.Int = 1}, {.Int = 1})},
    {"commands_logging", std::make_tuple(0, {.Bool = false}, {.Bool = false})}
};
</code>```

I get the following error:

```<code>error: too many arguments to function ‘constexpr std::tuple<typename std::__decay_and_strip<_Elements>::__type ...> std::make_tuple(_Elements&& ...)
[with _Elements = {}]’
         {"num_threads", std::make_tuple(1, {.Int = 1}, {.Int = 1})},
</code>```

I tried to narrow it down, so I tested initializing a map of simpler types std::map<std::string, std::tuple<uint8_t, uint64_t, uint64_t>> with brace initialization and it works fine. I also tried initializing just a tuple or pair of the union type and it didn't work:

```<code>std::pair<uint8_t, VariableType> Tmp = std::make_pair(5, {.Int = 4});

error: no matching function for call to ‘make_pair(int, <brace-enclosed initializer list>)’
         std::pair<uint8_t, VariableType> Tmp = std::make_pair(5, {.Int = 4});
</code>```

I have also tried initializing the union on its own using the same way, no complaints!

So why is the union initialization illegal inside std::make_pair or std::make_tuple but legal elsewhere? and how do I work around this?

I'm using g++ version 6.2.0 with Ubuntu GLIBC 2.24-3ubuntu2.

答:
I followed the comment of of @PasserBy. I just added union constructors and used them to assign values instead of the brace initialization.

Worked like a charm.

Body:
I have a union declaration, It is simple:

union VariableType
{
    bool Bool;
    int64_t Int;
    double Double;
    std::string* String;
};

In my header file I use this union inside some complex data types like this:

extern std::map<std::string, std::tuple<uint8_t, VariableType, VariableType>> PredefinedVariables;
extern std::map<std::string, std::pair<uint8_t, VariableType>> UserVariables;

in a cpp file I try to initialize the maps with brace initialization as follows:

std::map<std::string, std::tuple<uint8_t, VariableType, VariableType>> PredefinedVariables
{
    {"num_threads", std::make_tuple(1, {.Int = 1}, {.Int = 1})},
    {"commands_logging", std::make_tuple(0, {.Bool = false}, {.Bool = false})}
};

I get the following error:

error: too many arguments to function ‘constexpr std::tuple<typename std::__decay_and_strip<_Elements>::__type ...> std::make_tuple(_Elements&& ...)
[with _Elements = {}]’
         {"num_threads", std::make_tuple(1, {.Int = 1}, {.Int = 1})},

I tried to narrow it down, so I tested initializing a map of simpler types std::map<std::string, std::tuple<uint8_t, uint64_t, uint64_t>> with brace initialization and it works fine. I also tried initializing just a tuple or pair of the union type and it didn't work:

std::pair<uint8_t, VariableType> Tmp = std::make_pair(5, {.Int = 4});

error: no matching function for call to ‘make_pair(int, <brace-enclosed initializer list>)’
         std::pair<uint8_t, VariableType> Tmp = std::make_pair(5, {.Int = 4});

I have also tried initializing the union on its own using the same way, no complaints!

So why is the union initialization illegal inside std::make_pair or std::make_tuple but legal elsewhere? and how do I work around this?

I'm using g++ version 6.2.0 with Ubuntu GLIBC 2.24-3ubuntu2.


问:
Replace a String in Javascript using regex
my input is
var email = "xyz+wex+rr%40gmail.com";

i need output as

xyz wex rr @ gmail.com

i have tried with this below regex , i can only remove + from my string how to replace %40 with @

email .replace(/+/g, " ");

答:
You can use unescape function to first unescape the string and than replace +with

Try this one

var email = unescape("xyz+wex+rr%40gmail.com").replace(/[+]/g, " ");
console.log(email)```

As @Florian Albrecht said that unescape is deprecated so deprecated Florian's answer is better

Body:
You can use unescape function to first unescape the string and than replace +with

Try this one

var email = unescape("xyz+wex+rr%40gmail.com").replace(/[+]/g, " ");
console.log(email)

As @Florian Albrecht said that unescape is deprecated so deprecated Florian's answer is better


问:
In android studio why layout width matchparent changes to 368dp automatically?
I am doing a project using android studio. In android studio when I fix layout width as matchparentit automatically changes to 368dp. I need layoutwidth as matchparent but changes by default.

why?

kindly help me to fix this problem.

答:
Probably because one of your parents is a ConstraintLayout.

https://developer.android.com/training/constraint-layout/index.html

If you don't want to deal with constraints just replace your ConstraintLayout with a FrameLayout or similar.


问:
Restoring files on a version enabled amazon s3 bucket
I am trying to enable versioning and lifecycle policies on my Amazon S3 buckets. I understand that it is possible to enable Versioning first and then apply LifeCycle policy on that bucket. If you see the image below, that will confirm this idea.

I have then uploaded a file several times which created several versions of the same file. I then deleted the file and still able to see several versions. However, if I try to restore a file, I see that the Initiate Restore option is greyed out.

I would like to ask anyone who had any similar issue or let me know what I am doing wrong.

Thanks,

答:
If you have a lot of deleted files to restore. You might want to use a script to do the job for you.

The script should

Get the versions of objects in your bucket using the Get object versions API

Inspect the versions data to get Delete Marker (i.e. delete objects) name and version id

Delete the markers found using the marker names and version ids using Delete object API

Python example with boto:

This example script deletes delete markers found one by one once.

```<code>#!/usr/bin/env python
import boto

BUCKET_NAME = "examplebucket"
DELETE_DATE = "2015-06-08"

bucket = boto.connect_s3().get_bucket(BUCKET_NAME)

for v in bucket.list_versions():
    if (isinstance(v, boto.s3.deletemarker.DeleteMarker) and
            v.is_latest and
            DELETE_DATE in v.last_modified):
        bucket.delete_key(v.name, version_id=v.version_id)
</code>```

Python example with boto3:

However, if you have thousands of objects, this could be a slow process. AWS does provide a way to batch delete objects with a maximum batch size of 1000.

The following example script searches your objects with a prefix, and test them if they are deleted ( i.e. current version is a delete marker ) and them batch delete them. It is set to search 500 objects in your bucket in each batch, and try to delete multiple object with a batch no more than 1000 objects.

```<code>import boto3

client = boto3.client('s3')

def get_object_versions(bucket, prefix, max_key, key_marker):
    kwargs = dict(
        Bucket=bucket,
        EncodingType='url',
        MaxKeys=max_key,
        Prefix=prefix
    )

    if key_marker:
        kwargs['KeyMarker'] = key_marker

    response = client.list_object_versions(**kwargs)

    return response

def get_delete_markers_info(bucket, prefix, key_marker):
    markers = []
    max_markers = 500
    version_batch_size = 500

    while True:
        response = get_object_versions(bucket, prefix, version_batch_size, key_marker)
        key_marker = response.get('NextKeyMarker')
        delete_markers = response.get('DeleteMarkers', [])

        markers = markers + [dict(Key=x.get('Key'), VersionId=x.get('VersionId')) for x in delete_markers if
                             x.get('IsLatest')]

        print '{0} -- {1} delete markers ...'.format(key_marker, len(markers))

        if len(markers) >= max_markers or key_marker is None:
            break

    return {"delete_markers": markers, "key_marker": key_marker}

def delete_delete_markers(bucket, prefix):
    key_marker = None

    while True:
        info = get_delete_markers_info(bucket, prefix, key_marker)
        key_marker = info.get('key_marker')
        delete_markers = info.get('delete_markers', [])

        if len(delete_markers) > 0:
            response = client.delete_objects(
                Bucket=bucket,
                Delete={
                    'Objects': delete_markers,
                    'Quiet': True
                }
            )

            print 'Deleting {0} delete markers ... '.format(len(delete_markers))
            print 'Done with status {0}'.format(response.get('ResponseMetadata', {}).get('HTTPStatusCode'))
        else:
            print 'No more delete markers found\n'
            break

delete_delete_markers(bucket='data-global', prefix='2017/02/18')
</code>```

Body:
If you have a lot of deleted files to restore. You might want to use a script to do the job for you.

The script should

Get the versions of objects in your bucket using the Get object versions API

Inspect the versions data to get Delete Marker (i.e. delete objects) name and version id

Delete the markers found using the marker names and version ids using Delete object API

Python example with boto:

This example script deletes delete markers found one by one once.

#!/usr/bin/env python
import boto

BUCKET_NAME = "examplebucket"
DELETE_DATE = "2015-06-08"

bucket = boto.connect_s3().get_bucket(BUCKET_NAME)

for v in bucket.list_versions():
    if (isinstance(v, boto.s3.deletemarker.DeleteMarker) and
            v.is_latest and
            DELETE_DATE in v.last_modified):
        bucket.delete_key(v.name, version_id=v.version_id)

Python example with boto3:

However, if you have thousands of objects, this could be a slow process. AWS does provide a way to batch delete objects with a maximum batch size of 1000.

The following example script searches your objects with a prefix, and test them if they are deleted ( i.e. current version is a delete marker ) and them batch delete them. It is set to search 500 objects in your bucket in each batch, and try to delete multiple object with a batch no more than 1000 objects.

import boto3

client = boto3.client('s3')

def get_object_versions(bucket, prefix, max_key, key_marker):
    kwargs = dict(
        Bucket=bucket,
        EncodingType='url',
        MaxKeys=max_key,
        Prefix=prefix
    )

    if key_marker:
        kwargs['KeyMarker'] = key_marker

    response = client.list_object_versions(**kwargs)

    return response

def get_delete_markers_info(bucket, prefix, key_marker):
    markers = []
    max_markers = 500
    version_batch_size = 500

    while True:
        response = get_object_versions(bucket, prefix, version_batch_size, key_marker)
        key_marker = response.get('NextKeyMarker')
        delete_markers = response.get('DeleteMarkers', [])

        markers = markers + [dict(Key=x.get('Key'), VersionId=x.get('VersionId')) for x in delete_markers if
                             x.get('IsLatest')]

        print '{0} -- {1} delete markers ...'.format(key_marker, len(markers))

        if len(markers) >= max_markers or key_marker is None:
            break

    return {"delete_markers": markers, "key_marker": key_marker}

def delete_delete_markers(bucket, prefix):
    key_marker = None

    while True:
        info = get_delete_markers_info(bucket, prefix, key_marker)
        key_marker = info.get('key_marker')
        delete_markers = info.get('delete_markers', [])

        if len(delete_markers) > 0:
            response = client.delete_objects(
                Bucket=bucket,
                Delete={
                    'Objects': delete_markers,
                    'Quiet': True
                }
            )

            print 'Deleting {0} delete markers ... '.format(len(delete_markers))
            print 'Done with status {0}'.format(response.get('ResponseMetadata', {}).get('HTTPStatusCode'))
        else:
            print 'No more delete markers found\n'
            break

delete_delete_markers(bucket='data-global', prefix='2017/02/18')


问:
Implementing a DSL in Ruby for generating domain specific XML
I'd like to implement a DSL in Ruby for generating domain specific XML documents (i.e. XML which conforms to a specific schema). I can use e.g. Builder to write the XML in Ruby, which is already a great improvement on writing the XML manually, but I'd also like:

convenience methods that would generate a whole bunch of XML for me

and possibly a way to restrict the generator to a schema (not necessarily an XSD or a DTD, but the implementation could possibly generate only certain tags)

So my plan at the moment is to extend Builder with the convenience methods and ignore the schema restriction side of things for now.

My questions to the community are does this sounds like a reasonable plan, and more importantly, are there any DSLs out there that extend Builder in some fashion that I could use for inspiration.

Unfortunately googling for ruby, xml, builder, extend, dsl, ... doesn't return very interesting results.

答:
I don't know if it uses Builder, but haml is certainly worth looking.

I also found this article wich mentions many more, of those, probably Markaby is the closest to your idea, but the last commit on github is from 2008. Surely looking at _why's code should be entertaining.


答:
```<code>$indexes = [ 'Hello' , 'Hoi', 'Ola' , 'Shalom' , 'Salaam'];
$values = ['Hello' => 2, 'Ola' => 20 ];

$default = array_combine($indexes, array_fill(0, count($indexes), 0));

$result = array_replace($default, $values);

var_dump($result);
</code>```

The result would be:

```<code>array(5) {
  ["Hello"]=>
  int(2)
  ["Hoi"]=>
  int(0)
  ["Ola"]=>
  int(20)
  ["Shalom"]=>
  int(0)
  ["Salaam"]=>
  int(0)
}
</code>```

Title: How can I compare two arrays to fill a third?

Body:
$indexes = [ 'Hello' , 'Hoi', 'Ola' , 'Shalom' , 'Salaam'];
$values = ['Hello' => 2, 'Ola' => 20 ];

$default = array_combine($indexes, array_fill(0, count($indexes), 0));

$result = array_replace($default, $values);

var_dump($result);

The result would be:

array(5) {
  ["Hello"]=>
  int(2)
  ["Hoi"]=>
  int(0)
  ["Ola"]=>
  int(20)
  ["Shalom"]=>
  int(0)
  ["Salaam"]=>
  int(0)
}


问:
xcode 8 simulators are not showing after install xcode 8.1
After installing xcode 8.1

I had created one project with it. And its shows all simulators.
But when I open same project with xcode 8. It not showing any simulators.

I tried many solution like,

window->device -> add simulator (all simulor are shown in list but not get open to run with simulators). Refer images

restart xcode and system also.

答:
I find one solution that if you are installing using .xip than follow this steps.

quit any running Xcode or simulator

move .xip file to application Folder where all installed app exist

Extract xip file over there

After extraction open New xcode

Install addition components if this option window comes.

Check there should be all simulator listed on your new Xcode.


问:
Convert Angular2 app to ios
I have an angular 2 web application which uses webpack.

how can I generate an iOS application from this app?

答: You can use Ionic for this. Ionic is a framework that let's you deploy Angular Apps for Android, iOS, etc. Take a look here.</p>

Title: Convert Angular2 app to ios


答:
Here is required solution,

email.replace(/\+/g, " ").replace(/\%40/g, "@")

var email = "xyz+wex+rr%40gmail.com";
console.log(email.replace(/\+/g, " ").replace(/\%40/g, "@"))```

Result: xyz wex rr@gmail.com

Please run the above snippet

Title: Replace a String in Javascript using regex

Body:
my input is
var email = "xyz+wex+rr%40gmail.com";

i need output as

xyz wex rr @ gmail.com

i have tried with this below regex , i can only remove + from my string how to replace %40 with @

email .replace(/+/g, " ");

Body:
Here is required solution,

email.replace(/\+/g, " ").replace(/\%40/g, "@")

var email = "xyz+wex+rr%40gmail.com";
console.log(email.replace(/\+/g, " ").replace(/\%40/g, "@"))

Result: xyz wex rr@gmail.com

Please run the above snippet


问:
Poll Interval for Kafka Connect SourceTask
I'm implementing a custom Source Connector using the Kafka-Connect API, that can be used to poll REST-APIs and sink the JSON response into a Kafka topic.

Now I'm wondering how to realize a polling interval for the SourceTask, how the JDBC Connector offers one. Somewhere I have to set the thread to sleep, but where do I have to do this?

答: I solved this use case in my SourceTask implementation by adding a private field of type long to store a time stamp. At the first poll() invocation the field is not yet initialized, therefore the configured REST-APIs get polled. While this first invocation the mentioned long field get's initialized with the current time stamp. In all following poll() invocations this time stamp of the previous invocation get's checked. If the amount of elapsed milliseconds since the previous poll() is smaller than the configured interval between two polls, I send the thread to sleep since the configured milliseconds are elapsed.


问:
In kibana-TimeLion can we change y-axis?
I am using Kibana-4.6.4

My json is

```<code>{"ExchangeName":"BITFINEX",
 "CurrencyPair":"ETHBTC",
 "MachineTime":"2017-06-01T14:24:17.099141+05:30",
 "OrderSide":"bids",
 "OrderId":"2685192234",
 "Price":0.09369,
 "Quantity":7.40463042
}
</code>```

In kibana Timelion I want to change yaxis as a price, any query is there? Is it possible?

答:
.es(metric='max:Price')

Now this is showing correct values

Body:
I am using Kibana-4.6.4

My json is

{"ExchangeName":"BITFINEX",
 "CurrencyPair":"ETHBTC",
 "MachineTime":"2017-06-01T14:24:17.099141+05:30",
 "OrderSide":"bids",
 "OrderId":"2685192234",
 "Price":0.09369,
 "Quantity":7.40463042
}

In kibana Timelion I want to change yaxis as a price, any query is there? Is it possible?


问:
CSS - Line height property, how it works (simple)
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

```<code>line-height:100px;
</code>```

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!

答:
Ok I'm quite sure I got it now, I'll answer my own question, thanks to all you answers this would be a more graphical explanation (which always helps me):

This is just a complement to jarret's answer (the first one to nail it IMHO)

Thanks for all the helpful answers

BTW: Sorry for the horrid artwork.

Body:
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

line-height:100px;

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!


问:
Reading text file into arraylist
I really new to Java so I'm having some trouble figuring this out. So basically I have a text file that looks like this:

```<code>1:John:false
2:Bob:false
3:Audrey:false
</code>```

How can I create an ArrayList from the text file for each line?

答:
If you know how to read a file line by line, either by using Scanner or by using BufferedReader then reading a text file into ArrayList is not difficult for you. All you need to do is read each line and store that into ArrayList, as shown in following example:

```<code>BufferedReader bufReader = new BufferedReader(new
FileReader("file.txt"));
ArrayList<String> listOfLines = new ArrayList<>);
String line = bufReader.readLine(); while (line != null)
{
    listOfLines.add(line);
    line = bufReader.readLine();
}
bufReader.close();
</code>```

Just remember to close the BufferedReader once you are done to prevent resource leak, as you don't have try-with-resource statement

Title: Reading text file into arraylist

Body:
I really new to Java so I'm having some trouble figuring this out. So basically I have a text file that looks like this:

1:John:false
2:Bob:false
3:Audrey:false

How can I create an ArrayList from the text file for each line?

Body:
If you know how to read a file line by line, either by using Scanner or by using BufferedReader then reading a text file into ArrayList is not difficult for you. All you need to do is read each line and store that into ArrayList, as shown in following example:

BufferedReader bufReader = new BufferedReader(new
FileReader("file.txt"));
ArrayList<String> listOfLines = new ArrayList<>);
String line = bufReader.readLine(); while (line != null)
{
    listOfLines.add(line);
    line = bufReader.readLine();
}
bufReader.close();

Just remember to close the BufferedReader once you are done to prevent resource leak, as you don't have try-with-resource statement


问:
Oracle: Sql to update row of the same table based on value from another row of the same table
I need a sql to update the price column to 999 for the item records which meet the following condition:

The location of the ITEM should not be null for both the records.

Update the price to 999 for which one of the 2 records has location as null.

```
ID   LOCATION   ITEM   PRICE
1    NULL       101    0
2    123        101    0
3    NULL       102    0
4    NULL       102    0
5    124        103    0
6    NULL       103    0
```

OUTPUT TABLE SAMPLE

```
ID   LOCATION   ITEM   PRICE
1    NULL       101    999
2    123        101    0
3    NULL       102    0
4    NULL       102    0
5    124        103    0
6    NULL       103    999
```

答:
I have created a table. Please find the query below. Just execute and check. You should get the desired result as per your ask.</p>

```<code>CREATE TABLE TABLE1(ID INT, LOCATION INT, ITEM INT, PRICE INT)
INSERT INTO TABLE1 VALUES
(1, NULL, 101, 0),
(2, 123 , 101, 0),
(3, NULL, 102, 0),
(4, NULL, 102, 0),
(5, 124 , 103, 0),
(6, NULL, 103, 0);

SELECT* FROM TABLE1;

WITH CTE AS
(
SELECT ITEM, COUNT(*) AS COUNTLOC FROM TABLE1 WHERE LOCATION IS NULL GROUP BY ITEM
)
UPDATE TABLE1
SET PRICE = 999 WHERE ITEM IN(SELECT ITEM FROM CTE WHERE COUNTLOC<2) AND LOCATION IS NULL;
</code>```

Body:
I need a sql to update the price column to 999 for the item records which meet the following condition:

The location of the ITEM should not be null for both the records.

Update the price to 999 for which one of the 2 records has location as null.

ID   LOCATION   ITEM   PRICE
1    NULL       101    0
2    123        101    0
3    NULL       102    0
4    NULL       102    0
5    124        103    0
6    NULL       103    0

OUTPUT TABLE SAMPLE

ID   LOCATION   ITEM   PRICE
1    NULL       101    999
2    123        101    0
3    NULL       102    0
4    NULL       102    0
5    124        103    0
6    NULL       103    999

Body:
I have created a table. Please find the query below. Just execute and check. You should get the desired result as per your ask.

CREATE TABLE TABLE1(ID INT, LOCATION INT, ITEM INT, PRICE INT)
INSERT INTO TABLE1 VALUES
(1, NULL, 101, 0),
(2, 123 , 101, 0),
(3, NULL, 102, 0),
(4, NULL, 102, 0),
(5, 124 , 103, 0),
(6, NULL, 103, 0);

SELECT* FROM TABLE1;

WITH CTE AS
(
SELECT ITEM, COUNT(*) AS COUNTLOC FROM TABLE1 WHERE LOCATION IS NULL GROUP BY ITEM
)
UPDATE TABLE1
SET PRICE = 999 WHERE ITEM IN(SELECT ITEM FROM CTE WHERE COUNTLOC<2) AND LOCATION IS NULL;


问:
El implementation is not found for hibernate-validator in osgi-container
I try to run Hibernate validator in osgi container.

```<code><dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>2.2.4</version>
</dependency>
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>javax.el</artifactId>
    <version>2.2.4</version>
</dependency>

<dependency>
    <groupId>org.apache.servicemix.bundles</groupId>
    <artifactId>org.apache.servicemix.bundles.hibernate-validator</artifactId>
    <version>5.0.2.Final_1</version>
</dependency>

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.7</version>
</dependency>

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.8.1</version>
</dependency>

public class HibernateValidationProviderResolver implements ValidationProviderResolver {
    @Override
    public List<ValidationProvider<?>> getValidationProviders() {
        List<ValidationProvider<?>> list = new ArrayList<>(1);
        list.add(new HibernateValidator());
        return list;
    }
}

Configuration<?> configuration = Validation.byDefaultProvider().providerResolver(
    new HibernateValidationProviderResolver()
).configure();

ValidatorFactory validatorFactory = configuration.buildValidatorFactory();
Validator validator = validatorFactory.getValidator();
Set<ConstraintViolation<Group>> constraintViolations = validator.validate(group);

public class Group {
    @NotNull
    @Size(min=2)
    private String title;
}
</code>```

Try to run, equinox console is okay:

```<code>10      RESOLVED    org.glassfish.web.javax.el_2.2.4
39      RESOLVED    org.apache.servicemix.bundles.hibernate-validator_5.0.2.Final_1
47      RESOLVED    javax.validation.api_1.1.0.Final
49      RESOLVED    javax.el-api_2.2.4
</code>```

If I pass Group class instance with title = null, then validation is okay and constraintViolations contains one violation "not null".
If I pass Group class instance with title = "A" (one character against minimal length = 2), then it throws an exception

```<code>Caused by: javax.el.ELException: Provider com.sun.el.ExpressionFactoryImpl not found
Caused by: java.lang.ClassNotFoundException: com.sun.el.ExpressionFactoryImpl
</code>```

It 100% caused by osgi, but how I should setup hibernate-validator in osgi? All articles what I can found describes creating of HibernateValidationProviderResolver and that's all.

UPDATE 1

```<code>Maven: javax.el:javax.el-api:2.2.4

Export-Package: javax.el;version="2.2.4"
Import-Package: javax.el;version="2.2.4"

Maven: org.glassfish.web:javax.el:2.2.4 MANIFEST.MF

Export-Package: com.sun.el;uses:="javax.el";version="2.2.4"
Private-Package: com.sun.el.lang;version="2.2.4",com.sun.el.parser;version="2.2.4",com.sun.el.util;version="2.2.4"
Import-Package: com.sun.el;version="2.2.4",javax.el;version="2.2"

Maven: org.apache.servicemix.bundles:org.apache.servicemix.bundles.hibernate-validator:5.0.2.Final_1

Implementation-Version: 5.0.2.Final
Import-Package: javax.el,javax.persistence;resolution:=optional, ...

Export-Package: org.hibernate.validator.internal.engine.messageinterpola
tion.el;uses:="javax.el,javax.validation,org.hibernate.validator.intern
al.engine.messageinterpolation";version="5.0.2.Final",org.hibernate.val
idator.internal.engine.messageinterpolation;uses:="javax.validation.met
adata,org.hibernate.validator.internal.engine.messageinterpolation.el,j
avax.el,javax.validation,org.hibernate.validator.internal.util.logging"
;version="5.0.2.Final", ...
</code>```

Any version for import in hibernate bundle, 2.2.4 in export of el-api and el-impl and el-impl imports el-api as 2.2, not a 2.2.4. All bundles are resolved.

Update 2

Decision 1

my implementation of @hwellmann's idea. @hwellmann, is it correct?

```<code>public void createGroup(Group group) {
    ClassLoader prevClassLoader = Thread.currentThread().getContextClassLoader();

    try {
        ClassLoader[] classLoaders = new ClassLoader[] {
            prevClassLoader,
            ExpressionFactoryImpl.class.getClassLoader()
        };

        // build composite classloader

        Thread.currentThread().setContextClassLoader(compositeClassLoader);

        Set<ConstraintViolation<Group>> constraintViolations = validator.validate(group);

    } finally {
        Thread.currentThread().setContextClassLoader(prevClassLoader);
    }
}
</code>```

It works but looks strange. And change TCCL on each validation processing looks as some overhead.

Decision 2

The error has gone when I add my own message attribute to each validation annotation, for example for Group:

```<code>public class Group {
    @NotNull
    @Size(min=2, message="field.too_short")
    private String title;
}
</code>```

It seems in this case hibernate interpolator is not started so ExpressionFactoryImpl is not retrieved from TCCL (previously we read min=2 value, now we don't). If it is okay for us, this decision is simplest.
I will investigate this area futhermore and share my observations there.

答: I had a similar issue with Hibernate 5.2.5 and Jetty 9.x. Basically, it looked like Hibernate didn't check if there was already an EL implementation on the classpath and tried to use javax.el-api instead of Jetty 9's apache-el. An upgrade to Hibernate 5.2.10 solved the issue for me. No conflicting el-api on the classpath any more.</p>

Body:
I try to run Hibernate validator in osgi container.

<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>2.2.4</version>
</dependency>
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>javax.el</artifactId>
    <version>2.2.4</version>
</dependency>

<dependency>
    <groupId>org.apache.servicemix.bundles</groupId>
    <artifactId>org.apache.servicemix.bundles.hibernate-validator</artifactId>
    <version>5.0.2.Final_1</version>
</dependency>

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.7</version>
</dependency>

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.8.1</version>
</dependency>

public class HibernateValidationProviderResolver implements ValidationProviderResolver {
    @Override
    public List<ValidationProvider<?>> getValidationProviders() {
        List<ValidationProvider<?>> list = new ArrayList<>(1);
        list.add(new HibernateValidator());
        return list;
    }
}

Configuration<?> configuration = Validation.byDefaultProvider().providerResolver(
    new HibernateValidationProviderResolver()
).configure();

ValidatorFactory validatorFactory = configuration.buildValidatorFactory();
Validator validator = validatorFactory.getValidator();
Set<ConstraintViolation<Group>> constraintViolations = validator.validate(group);

public class Group {
    @NotNull
    @Size(min=2)
    private String title;
}

Try to run, equinox console is okay:

10      RESOLVED    org.glassfish.web.javax.el_2.2.4
39      RESOLVED    org.apache.servicemix.bundles.hibernate-validator_5.0.2.Final_1
47      RESOLVED    javax.validation.api_1.1.0.Final
49      RESOLVED    javax.el-api_2.2.4

If I pass Group class instance with title = null, then validation is okay and constraintViolations contains one violation "not null".
If I pass Group class instance with title = "A" (one character against minimal length = 2), then it throws an exception

Caused by: javax.el.ELException: Provider com.sun.el.ExpressionFactoryImpl not found
Caused by: java.lang.ClassNotFoundException: com.sun.el.ExpressionFactoryImpl

It 100% caused by osgi, but how I should setup hibernate-validator in osgi? All articles what I can found describes creating of HibernateValidationProviderResolver and that's all.

UPDATE 1

Maven: javax.el:javax.el-api:2.2.4

Export-Package: javax.el;version="2.2.4"
Import-Package: javax.el;version="2.2.4"

Maven: org.glassfish.web:javax.el:2.2.4 MANIFEST.MF

Export-Package: com.sun.el;uses:="javax.el";version="2.2.4"
Private-Package: com.sun.el.lang;version="2.2.4",com.sun.el.parser;version="2.2.4",com.sun.el.util;version="2.2.4"
Import-Package: com.sun.el;version="2.2.4",javax.el;version="2.2"

Maven: org.apache.servicemix.bundles:org.apache.servicemix.bundles.hibernate-validator:5.0.2.Final_1

Implementation-Version: 5.0.2.Final
Import-Package: javax.el,javax.persistence;resolution:=optional, ...

Export-Package: org.hibernate.validator.internal.engine.messageinterpola
tion.el;uses:="javax.el,javax.validation,org.hibernate.validator.intern
al.engine.messageinterpolation";version="5.0.2.Final",org.hibernate.val
idator.internal.engine.messageinterpolation;uses:="javax.validation.met
adata,org.hibernate.validator.internal.engine.messageinterpolation.el,j
avax.el,javax.validation,org.hibernate.validator.internal.util.logging"
;version="5.0.2.Final", ...

Any version for import in hibernate bundle, 2.2.4 in export of el-api and el-impl and el-impl imports el-api as 2.2, not a 2.2.4. All bundles are resolved.

Update 2

Decision 1

my implementation of @hwellmann's idea. @hwellmann, is it correct?

public void createGroup(Group group) {
    ClassLoader prevClassLoader = Thread.currentThread().getContextClassLoader();

    try {
        ClassLoader[] classLoaders = new ClassLoader[] {
            prevClassLoader,
            ExpressionFactoryImpl.class.getClassLoader()
        };

        // build composite classloader

        Thread.currentThread().setContextClassLoader(compositeClassLoader);

        Set<ConstraintViolation<Group>> constraintViolations = validator.validate(group);

    } finally {
        Thread.currentThread().setContextClassLoader(prevClassLoader);
    }
}

It works but looks strange. And change TCCL on each validation processing looks as some overhead.

Decision 2

The error has gone when I add my own message attribute to each validation annotation, for example for Group:

public class Group {
    @NotNull
    @Size(min=2, message="field.too_short")
    private String title;
}

It seems in this case hibernate interpolator is not started so ExpressionFactoryImpl is not retrieved from TCCL (previously we read min=2 value, now we don't). If it is okay for us, this decision is simplest.
I will investigate this area futhermore and share my observations there.


问:
C# How to find a 1x1 image tag in HTML
I would like to know how to find an image tag in a string of HTML that has dimensions of 1x1, basically I am looking for tracking pixels. So for example:

```<code><img src=\"http://somewhere.com\" width=\"1\" height=\"1\" style=\"display:none!important;\">
</code>```

My end goal is to be able to find this part of the code and remove it from the string.

I have read few a few posts already on how to find all img tags but that is not what I am looking for. I only want the img tags that are 1x1.

Can anyone help with this?

答:
If you just want to remove this img tags from your string, you can do that with regexp:

```<code> string result = Regex.Replace(html, "<img.+?(width|height)=[\"']1[\"'].+?(width|height)=[\"']1[\"'].*>", "", RegexOptions.IgnoreCase);
</code>```

Title: C# How to find a 1x1 image tag in HTML

Body:
I would like to know how to find an image tag in a string of HTML that has dimensions of 1x1, basically I am looking for tracking pixels. So for example:

My end goal is to be able to find this part of the code and remove it from the string.

I have read few a few posts already on how to find all img tags but that is not what I am looking for. I only want the img tags that are 1x1.

Can anyone help with this?

Body:
If you just want to remove this img tags from your string, you can do that with regexp:

 string result = Regex.Replace(html, "<img.+?(width|height)=[\"']1[\"'].+?(width|height)=[\"']1[\"'].*>", "", RegexOptions.IgnoreCase);


问:
how to integrate coinbase api in php for transfer bitcoine
I want to transfer bitcoin through bitcoin address in PHP please share the proper link.

https://developers.coinbase.com/docs/merchants/payment-buttons

答:
Try This code for transfer btc

```<code>$transaction = Transaction::send();
$transaction->setToBitcoinAddress('here btc address to transfer');
$transaction->setAmount(new Money(0.0010, CurrencyCode::BTC));
$transaction->setDescription('this is optional');
</code>```

Hope it will work :

https://github.com/coinbase/coinbase-php

Body:
Try This code for transfer btc

$transaction = Transaction::send();
$transaction->setToBitcoinAddress('here btc address to transfer');
$transaction->setAmount(new Money(0.0010, CurrencyCode::BTC));
$transaction->setDescription('this is optional');

Hope it will work :

https://github.com/coinbase/coinbase-php


问:
spread syntax with map doesn't work
```<code>data.map(obj =>
        {person_name: obj.user.name,
        ...obj})
</code>```

Why above code failed?

my data look like this

```<code>[{user:{name:'hello'},age:1},{user:{name:'world'},age:1,{user:{name:'another_name'},age:1]
</code>```

I want to 'pull' the obj.user.name out from the nested obj.

答:
With babel, you could use rest syntax (parameters) ... for getting the rest of the object and store name property directly.

var data = [{ user: { name: 'hello' }, age: 1 }, { user: { name: 'world' }, age: 1 }, { user: { name: 'another_name' }, age: 1 }];

console.log(data.map(({ user, ...obj }) => Object.assign(obj, { person_name: user.name })));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: spread syntax with map doesn't work

Body:
data.map(obj =>
        {person_name: obj.user.name,
        ...obj})

Why above code failed?

my data look like this

[{user:{name:'hello'},age:1},{user:{name:'world'},age:1,{user:{name:'another_name'},age:1]

I want to 'pull' the obj.user.name out from the nested obj.

Body:
With babel, you could use rest syntax (parameters) ... for getting the rest of the object and store name property directly.

var data = [{ user: { name: 'hello' }, age: 1 }, { user: { name: 'world' }, age: 1 }, { user: { name: 'another_name' }, age: 1 }];

console.log(data.map(({ user, ...obj }) => Object.assign(obj, { person_name: user.name })));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Count of combinations of values in rows across the entire table
Using the following data in a table:

```<code>|   name |    d1 |     d2 |     d3 |     d4 |     d5 |     d6 |     d7 |     d8 |
|--------|-------|--------|--------|--------|--------|--------|--------|--------|
|  matty | 116.7 |  17.88 |   16.1 |  9.731 | (null) | (null) | (null) | (null) |
|   jana | 17.88 |  116.7 |  65.45 |   72.1 | (null) | (null) | (null) | (null) |
|  chris |  72.1 | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
| khaled | 9.731 |  116.7 |  17.88 |   53.1 |      2 |   85.2 | (null) | (null) |
|    "   |   "   |   "    |   "    |   "    |   "    |   "    |   "    |   "    |
|    n   |   "   |   "    |   "    |   "    |   "    |   "    |   "    |   "    |
</code>```

how is it possible to identify the count of times that combination of values did appear amongst all rows in SQL?

The following is the output sample required:

116.7, 17.88 (3)

116.7, 17.88, 9.731 (2)

72.1 (2)

16.1 (1)

65.45 (1)

53.1 (1)

2 (1)

85.2 (1)

If it is not possible with SQL, any alternative method could do it?

答:
In below case I am not imagining different combination for d1,d2. If both are same, you will get one value with count of 2.

So assuming that the number of columns are finite and fixed, then you can do it with help of union

Rextester Demo

```<code>select concat(array_to_string(array_agg(col),',')   ,' (',  cnt ,')' ) as result
from
(
    select col,count(*) cnt
    from
    (   select d1 as col from table1
        union all
        select d2 from table1
        union all
        select d3 from table1
         --similarly add other columns
    ) t
    where col is not null
    group by col
) t1
group by cnt
order by cnt desc;
</code>```

Output

```<code>result
--------------------------
17.88,116.7 (3)
72.1,16.1,65.45,9.731 (1)
</code>```

Else you have to create a procedure to get all the columns in a union and then do group by and count like above.

Body:
Using the following data in a table:

|   name |    d1 |     d2 |     d3 |     d4 |     d5 |     d6 |     d7 |     d8 |
|--------|-------|--------|--------|--------|--------|--------|--------|--------|
|  matty | 116.7 |  17.88 |   16.1 |  9.731 | (null) | (null) | (null) | (null) |
|   jana | 17.88 |  116.7 |  65.45 |   72.1 | (null) | (null) | (null) | (null) |
|  chris |  72.1 | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
| khaled | 9.731 |  116.7 |  17.88 |   53.1 |      2 |   85.2 | (null) | (null) |
|    "   |   "   |   "    |   "    |   "    |   "    |   "    |   "    |   "    |
|    n   |   "   |   "    |   "    |   "    |   "    |   "    |   "    |   "    |

how is it possible to identify the count of times that combination of values did appear amongst all rows in SQL?

The following is the output sample required:

116.7, 17.88 (3)

116.7, 17.88, 9.731 (2)

72.1 (2)

16.1 (1)

65.45 (1)

53.1 (1)

2 (1)

85.2 (1)

If it is not possible with SQL, any alternative method could do it?

Body:
In below case I am not imagining different combination for d1,d2. If both are same, you will get one value with count of 2.

So assuming that the number of columns are finite and fixed, then you can do it with help of union

Rextester Demo

select concat(array_to_string(array_agg(col),',')   ,' (',  cnt ,')' ) as result
from
(
    select col,count(*) cnt
    from
    (   select d1 as col from table1
        union all
        select d2 from table1
        union all
        select d3 from table1
         --similarly add other columns
    ) t
    where col is not null
    group by col
) t1
group by cnt
order by cnt desc;

Output

result
--------------------------
17.88,116.7 (3)
72.1,16.1,65.45,9.731 (1)

Else you have to create a procedure to get all the columns in a union and then do group by and count like above.