问:
PHP and Python static methods in objects, two different worlds...?
i'm php coder, trying to get into python world, and it's very hard for me.

Biggest enjoy of static methods in php is automatic builder of instance. No need to declare object, if you needed it once, in every file (or with different constructor params , in one line)

```<code><?php
class Foo {
    function __constructor__(){
        $this->var = 'blah';
    }
   public static function aStaticMethod() {
       return $this->var;
   }
}

echo Foo::aStaticMethod();
?>
</code>```

we can call constructor from static method don't we? and we can access everything in class as it would be simple method ... we can even have STATIC CONSTRUCTOR in php class and call it like so: Object::construct()->myMethod(); (to pass different params every time)

but not in python???? @staticmethod makes method in class a simple function that doesn't see totally anything ??

```<code>class socket(object):

def __init__(self):
    self.oclass = otherclass()
    print 'test' # does this constructor called at all when calling static method??

@staticmethod
def ping():
    return self.oclass.send('PING') # i can't access anything!!!

print Anidb.ping()
</code>```

I can't access anything from that god damned static method, it's like a standalone function or something like this..??

Maybe I'm using the wrong decorator? Maybe there's something like php offers with static methods in python?

1) Please tell why static methods is isolated
2) Please tell me how to make the same behavior like php static methods have.
3) Please tell me alternative practical use of this, if php static methods behavior is a bad thing

P.s. the goal of all this to write totally less code as much as possible.
P.p.s Heavy commenting of sample code is appreciated

Thank you.

答:
I see you've already accepted another answer, but I'm not sure that it will work with your code. Specifically, the oclass variable is only created for instances of the class, not for the class itself. You could do it like this:

```<code>class socket(object):
    oclass = otherclass()

    @classmethod
    def ping(cls):
        return cls.oclass.send('PING')

socket.ping()
</code>```

However, using your existing code and removing all decorators, you could simply instantiate it and use a method on the same line:

```<code>socket().ping()
</code>```

Body:
i'm php coder, trying to get into python world, and it's very hard for me.

Biggest enjoy of static methods in php is automatic builder of instance. No need to declare object, if you needed it once, in every file (or with different constructor params , in one line)

<?php
class Foo {
    function __constructor__(){
        $this->var = 'blah';
    }
   public static function aStaticMethod() {
       return $this->var;
   }
}

echo Foo::aStaticMethod();
?>

we can call constructor from static method don't we? and we can access everything in class as it would be simple method ... we can even have STATIC CONSTRUCTOR in php class and call it like so: Object::construct()->myMethod(); (to pass different params every time)

but not in python???? @staticmethod makes method in class a simple function that doesn't see totally anything ??

class socket(object):

def __init__(self):
    self.oclass = otherclass()
    print 'test' # does this constructor called at all when calling static method??

@staticmethod
def ping():
    return self.oclass.send('PING') # i can't access anything!!!

print Anidb.ping()

I can't access anything from that god damned static method, it's like a standalone function or something like this..??

Maybe I'm using the wrong decorator? Maybe there's something like php offers with static methods in python?

1) Please tell why static methods is isolated
2) Please tell me how to make the same behavior like php static methods have.
3) Please tell me alternative practical use of this, if php static methods behavior is a bad thing

P.s. the goal of all this to write totally less code as much as possible.
P.p.s Heavy commenting of sample code is appreciated

Thank you.

Body:
I see you've already accepted another answer, but I'm not sure that it will work with your code. Specifically, the oclass variable is only created for instances of the class, not for the class itself. You could do it like this:

class socket(object):
    oclass = otherclass()

    @classmethod
    def ping(cls):
        return cls.oclass.send('PING')

socket.ping()

However, using your existing code and removing all decorators, you could simply instantiate it and use a method on the same line:

socket().ping()


来源: stackexchange

问:
Referer sub array?
I have an array orig[].
Now I want to create another array ref[] that refer to only specific elements in orig[].
By implying it is referrer I mean any change in element of ref[] will change the corresponding element of orig[].

F.e. pseudo code :

```<code>orig = [ 1,2,3,4,5 ]
ref[0] ==> orig[2]
ref[1] ==> orig[4]
</code>```

now if I do :

```<code> ref[0] = 11
 ref[1] = 22
</code>```

orig will become :

```<code>[ 1,2,11,4,22 ]
</code>```

also when I ca do : for x in ref : ....

答:
You can do this by building a simple class and having your lists contain objects of the class.  Your code would look something like

```<code>Class my_ref():
    def __init__(self, value):
        self.value = value

orig = [my_ref(n) for n in range(1,6)]
</code>```

... and I expect that you can see from here how it works.

ContentLicense: CC BY-SA 3.0

Title: Referer sub array?

Body:
I have an array orig[].
Now I want to create another array ref[] that refer to only specific elements in orig[].
By implying it is referrer I mean any change in element of ref[] will change the corresponding element of orig[].

F.e. pseudo code :

orig = [ 1,2,3,4,5 ]
ref[0] ==> orig[2]
ref[1] ==> orig[4]

now if I do :

 ref[0] = 11
 ref[1] = 22

orig will become :

[ 1,2,11,4,22 ]

also when I ca do : for x in ref : ....

Body:
You can do this by building a simple class and having your lists contain objects of the class.  Your code would look something like

Class my_ref():
    def __init__(self, value):
        self.value = value

orig = [my_ref(n) for n in range(1,6)]

... and I expect that you can see from here how it works.


问:
Mockwebserver in gradle build throwing error
This entry in my gradle file :

```<code>androidTestCompile ('com.squareup.okhttp:mockwebserver:2.7.0')
</code>```

is throwing error:

```<code>Warning:Conflict with dependency 'com.squareup.okio:okio'. Resolved versions for app (1.8.0) and test app (1.6.0) differ. See http://g.co/androidstudio/app-test-app-conflict for details.
</code>```

I tried commenting out different compile entries in my gradle file to find out which one was conflicting but I just can't find which one uses com.squareup.okio:okio.

UPDATE:
I was able to get the dependencies by running: gradlew.bat app:dependencies >  c:\tmp\output.txt

```<code>+--- com.squareup.retrofit2:retrofit:2.0.0 -> 2.1.0
|    \--- com.squareup.okhttp3:okhttp:3.3.0
|         \--- com.squareup.okio:okio:1.8.0

--- com.squareup.okhttp:mockwebserver:2.7.0
|    +--- com.squareup.okhttp:okhttp:2.7.0
|    |    \--- com.squareup.okio:okio:1.6.0
</code>```

So as you can see, retrofit 2.0 uses okhttp3 which uses okio:1.8.0. On the other hand mockwebserver:2.7.0 uses okhttp:2.7.0 which uses okio:1.6.0. So how can I resolve this?

Here are the entries in "dependencies" section of my gradle file:

```<code>compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:24.2.1'

        //retrofit
        compile 'com.squareup.retrofit2:retrofit:2.0.0'
        compile 'com.squareup.retrofit2:converter-gson:2.+'
        compile 'com.squareup.retrofit2:adapter-rxjava:2.+'
        compile 'com.squareup.retrofit2:retrofit-mock:2.+'

        //recycler view
        compile 'com.android.support:recyclerview-v7:+'

        //picasso image caching
        compile 'com.squareup.picasso:picasso:2.5.2'

        //jackson parser
        compile (
            [group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.4.1']
        )

        //Dagger
        compile 'com.google.dagger:dagger:2.7'
        apt 'com.google.dagger:dagger-compiler:2.7'

        //constraint based layouts
        compile 'com.android.support:design:24.1.1'
        compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'

        //for chrome debugging
        compile 'com.facebook.stetho:stetho:1.4.1'
        compile 'com.facebook.stetho:stetho-okhttp3:1.4.1' //for retrofit

        //RxJava
        compile 'io.reactivex:rxandroid:1.2.1'
        // Because RxAndroid releases are few and far between, it is recommended you also
        // explicitly depend on RxJava's latest version for bug fixes and new features.
        compile 'io.reactivex:rxjava:1.1.6'

        //--- For Testing ---
        //robolectric:
        testCompile "org.robolectric:robolectric:3.2.2"

        //mockito
        testCompile "org.mockito:mockito-core:2.+"
        testCompile('org.hamcrest:hamcrest-core:1.3')
        testCompile('org.hamcrest:hamcrest-library:1.3')

        testCompile 'junit:junit:4.12'

        androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })

        // Espresso-web for WebView support
        androidTestCompile( 'com.android.support.test.espresso:espresso-web:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })

        androidTestCompile( 'com.android.support.test:runner:0.5', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })
        androidTestCompile( 'com.android.support.test:rules:0.5', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })

        testCompile ('org.powermock:powermock-api-mockito:1.6.2') {
            exclude module: 'hamcrest-core'
            exclude module: 'objenesis'
        }

        //mockwebserver
        //testCompile 'com.squareup.okhttp3:mockwebserver:3.3.0'
        androidTestCompile ('com.squareup.okhttp:mockwebserver:2.7.0')
        androidTestCompile 'com.squareup.spoon:spoon-client:1.2.0'
</code>```

答:
The dependency versions for these two versions of Retrofit and MockWebServer line up:

```<code>com.squareup.retrofit2:retrofit:2.2.0
com.squareup.okhttp3:mockwebserver:3.6.0
</code>```

Rather than deal with dependency conflicts, I'd recommend using these two versions.

Body:
This entry in my gradle file :

androidTestCompile ('com.squareup.okhttp:mockwebserver:2.7.0')

is throwing error:

Warning:Conflict with dependency 'com.squareup.okio:okio'. Resolved versions for app (1.8.0) and test app (1.6.0) differ. See http://g.co/androidstudio/app-test-app-conflict for details.

I tried commenting out different compile entries in my gradle file to find out which one was conflicting but I just can't find which one uses com.squareup.okio:okio.

UPDATE:
I was able to get the dependencies by running: gradlew.bat app:dependencies >  c:\tmp\output.txt

+--- com.squareup.retrofit2:retrofit:2.0.0 -> 2.1.0
|    \--- com.squareup.okhttp3:okhttp:3.3.0
|         \--- com.squareup.okio:okio:1.8.0

--- com.squareup.okhttp:mockwebserver:2.7.0
|    +--- com.squareup.okhttp:okhttp:2.7.0
|    |    \--- com.squareup.okio:okio:1.6.0

So as you can see, retrofit 2.0 uses okhttp3 which uses okio:1.8.0. On the other hand mockwebserver:2.7.0 uses okhttp:2.7.0 which uses okio:1.6.0. So how can I resolve this?

Here are the entries in "dependencies" section of my gradle file:

compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:24.2.1'

        //retrofit
        compile 'com.squareup.retrofit2:retrofit:2.0.0'
        compile 'com.squareup.retrofit2:converter-gson:2.+'
        compile 'com.squareup.retrofit2:adapter-rxjava:2.+'
        compile 'com.squareup.retrofit2:retrofit-mock:2.+'

        //recycler view
        compile 'com.android.support:recyclerview-v7:+'

        //picasso image caching
        compile 'com.squareup.picasso:picasso:2.5.2'

        //jackson parser
        compile (
            [group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.4.1']
        )

        //Dagger
        compile 'com.google.dagger:dagger:2.7'
        apt 'com.google.dagger:dagger-compiler:2.7'

        //constraint based layouts
        compile 'com.android.support:design:24.1.1'
        compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'

        //for chrome debugging
        compile 'com.facebook.stetho:stetho:1.4.1'
        compile 'com.facebook.stetho:stetho-okhttp3:1.4.1' //for retrofit

        //RxJava
        compile 'io.reactivex:rxandroid:1.2.1'
        // Because RxAndroid releases are few and far between, it is recommended you also
        // explicitly depend on RxJava's latest version for bug fixes and new features.
        compile 'io.reactivex:rxjava:1.1.6'

        //--- For Testing ---
        //robolectric:
        testCompile "org.robolectric:robolectric:3.2.2"

        //mockito
        testCompile "org.mockito:mockito-core:2.+"
        testCompile('org.hamcrest:hamcrest-core:1.3')
        testCompile('org.hamcrest:hamcrest-library:1.3')

        testCompile 'junit:junit:4.12'

        androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })

        // Espresso-web for WebView support
        androidTestCompile( 'com.android.support.test.espresso:espresso-web:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })

        androidTestCompile( 'com.android.support.test:runner:0.5', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })
        androidTestCompile( 'com.android.support.test:rules:0.5', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })

        testCompile ('org.powermock:powermock-api-mockito:1.6.2') {
            exclude module: 'hamcrest-core'
            exclude module: 'objenesis'
        }

        //mockwebserver
        //testCompile 'com.squareup.okhttp3:mockwebserver:3.3.0'
        androidTestCompile ('com.squareup.okhttp:mockwebserver:2.7.0')
        androidTestCompile 'com.squareup.spoon:spoon-client:1.2.0'

Body:
The dependency versions for these two versions of Retrofit and MockWebServer line up:

com.squareup.retrofit2:retrofit:2.2.0
com.squareup.okhttp3:mockwebserver:3.6.0

Rather than deal with dependency conflicts, I'd recommend using these two versions.


问:
Send parameters to a URL and get output from that page
I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:

abc.php:

```<code> <?php
  $id="123";
  $name="blahblah";
   //need to send the value to def.php & get value from that page
  // echo $value=Print the "Value received" msg from def.php;
 ?>
</code>```

def.php:

```<code> <?php
  $id=$_GET['id'];
  $name=$_GET['name'];
  if(!is_null($id)&&!is_null($name))
  {  echo "Value received";}
  else{echo "Not ok";}
 ?>
</code>```

Is there any kind heart who can help me solve the issue?

答:
First make up your mind : do you want GET or POST parameters.

Your script currently expects them to be GET parameters, so you can simply call it (provided that URL wrappers are enabled anyway) using :

```<code>$f = file_get_contents('http://your.domain/def.php?id=123&name=blahblah');
</code>```

To use the curl examples posted here in other answers you'll have to alter your script to use $_POST instead of $_GET.

Body:
I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:

abc.php:

 <?php
  $id="123";
  $name="blahblah";
   //need to send the value to def.php & get value from that page
  // echo $value=Print the "Value received" msg from def.php;
 ?>

def.php:

 <?php
  $id=$_GET['id'];
  $name=$_GET['name'];
  if(!is_null($id)&&!is_null($name))
  {  echo "Value received";}
  else{echo "Not ok";}
 ?>

Is there any kind heart who can help me solve the issue?

Body:
First make up your mind : do you want GET or POST parameters.

Your script currently expects them to be GET parameters, so you can simply call it (provided that URL wrappers are enabled anyway) using :

$f = file_get_contents('http://your.domain/def.php?id=123&name=blahblah');

To use the curl examples posted here in other answers you'll have to alter your script to use $_POST instead of $_GET.

ContentLicense: CC BY-SA 2.5


问:
implement async in a foreach .net 4.5 mvc
in working to develop a new post method. I found that I am running into extremely long wait times on a bottleneck foreach statement. I am saving between 5 and 8k(depending on the items being sent) to the database. The method succeeds, but usually takes upwards of a full 60 seconds. I have been looking into how to actually execute an async method, but I am not sure this will actually solve the problem.

This is the full method

```<code>[HttpPost]
        public ActionResult ConfirmSend(int? SystemGeneralAnnouncementId) {
        var systemGeneralAnnouncement = (SystemGeneralAnnouncementId == null) ? null : _uow.SystemGeneralAnnouncementRepository.GetById(SystemGeneralAnnouncementId.Value);
        List<Status> status = new List<Status>();

            if (systemGeneralAnnouncement.Statuses.Length > 0)
            {
                status.AddRange(systemGeneralAnnouncement.Statuses.Split(',').Select(item => (Status) Enum.Parse(typeof (Status), item)));
            }

            var allEmailAddresses = new List<PointOfContact>();
            var EmailAddresses = new List<PointOfContact>();

            var result = new List<PointOfContact>();
            foreach (var item in status)
            {
                result = _uow.PointOfContactRepository.GetAllByStatus(item).ToList();
                allEmailAddresses.AddRange(result);
            }

            if (systemGeneralAnnouncement.SendToRecipients.Contains("(1) All Three Contact Types"))
            {
                mailAddresses = allEmailAddresses;
            }
            else
            {
                if (systemGeneralAnnouncement.SendToRecipients.Contains("(2) All Contacts "))
                {
                    EmailAddresses.AddRange(allEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.Primary).ToList());
                }
                if (systemGeneralAnnouncement.SendToRecipients.Contains("(3) All Compliance contacts"))
                {
                    pocEmailAddresses.AddRange(allEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.Secondary).ToList());
                }
                if (systemGeneralAnnouncement.SendToRecipients.Contains("(4) All Authorities"))
                {
                    pocEmailAddresses.AddRange(allEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.SigningAuthority).ToList());
                }
                if (systemGeneralAnnouncement.SendToRecipients.Contains("(5) All Rate Contacts"))
                {
                    EmailAddresses.AddRange(allEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.TuitionRates).ToList());
                }
                if (systemGeneralAnnouncement.SendToRecipients.Contains("(6) Specified Email Address"))
                {
                    var pocs = new List<PointOfContact>();

                    string[] emails = systemGeneralAnnouncement.EmailAddresses.Split(',');

                    foreach (string email in emails)
                    {
                        var addContact = new InstitutionPointOfContact { Email = email };

                        User user = _uow.UserRepository.GetByEmail(email);

                        if (user == null)
                        {
                            addContact.FirstName = "Not Created Account Yet";
                        }
                        else
                        {
                            addContact.FirstName = user.FirstName;
                            addContact.LastName = user.LastName;
                        }

                        List<PointOfContact> idAssociatedToUser =
                            _uow.PointOfContactRepository
                                .GetAllByEmail(email)
                                .ToList();

                        if (idAssociatedToUser.Count == 0)
                        {
                            addContact.IDNumber = "N/A";
                        }
                        else
                        {
                            string[] opeidArray = opeidAssociatedToUser
                                .Select(x => x.OPEIDNumber)
                                .ToArray();

                            addContact.OPEIDNumber = string.Join(",", opeidArray);
                        }
                        Contacts.Add(addContact);
                    }
                    EmailAddresses.AddRange(Contacts);
                }
            }
</code>```

The Specific Foreach

```<code>    if (EmailAddresses.Count > 0)
                {
                    foreach (PointOfContact emailAddress in EmailAddresses.Where(x => x.Email != "").ToList())
                    {
                        string firstName = emailAddress.FirstName == null ? "" : emailAddress.FirstName.Trim();
                        string lastName = emailAddress.LastName == null ? "" : emailAddress.LastName.Trim();

                        string userName = firstName + " " + lastName;

                        string emailBody = WebUtility.HtmlDecode(systemGeneralAnnouncement.EmailBody);

                        SaveToDatabase(emailAddress.Email, emailBody, systemGeneralAnnouncement.Subject, UserIdentityHelper.GetUserEmailAddress + " (" + UserIdentityHelper.GetUserId + ")", systemGeneralAnnouncement.SystemGeneralAnnouncementId, userName, emailAddress.OPEIDNumber);
                        LogInstitutionEmail(systemGeneralAnnouncement.Subject, emailBody, emailAddress.Email, emailAddress.OPEIDNumber, systemGeneralAnnouncement.EmailAttachmentLocation);
                    }
                }
                return View("GeneralAnnouncementGeneratedConfirmation");
            }
</code>```

And the Database methods:

```<code>        private void LogInstitutionEmail(string subject, string emailBody, string email, string opeidNumber, string emailAttachment)
        {
            try
            {
                using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MasterContext"].ConnectionString))
                {
                    conn.Open();
                    var cmd = new SqlCommand("Insert Into InstitutionEmails (Since, Subject, Email, EmailAddress, OpeidNumber, FirstReadDateTime, Attachment) VALUES(@Since, @Subject, @Email, @EmailAddress, @idNumber, NULL, @Attachment)", conn);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Since", Value = DateTime.Now });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Subject", Value = subject });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Email", Value = emailBody });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@EmailAddress", Value = email });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@idNumber", Value = idNumber });

                    if (!string.IsNullOrEmpty(emailAttachment))
                    {
                        cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Attachment", Value = emailAttachment });
                    }

                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void SaveToDatabase(string emailRecipient, string emailBody, string subject, string userWhoSentIt, int systemGeneralAnnouncementId, string userName, string opeidNumber)
        {
            try
            {
                using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MasterContext"].ConnectionString))
                {
                    conn.Open();
                    var cmd = new SqlCommand("Insert Into EmailQueue (EmailRecipients, EmailBody, EmailSubject, UserWhoSentIt, QueueDate, SystemGeneralAnnouncementId, UserName, idNumber) VALUES(@EmailRecipients, @EmailBody, @EmailSubject, @UserWhoSentIt, @QueueDate, @SystemGeneralAnnouncementId, @UserName, @idNumber)", conn);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add(new SqlParameter() {ParameterName = "@EmailRecipients", Value = emailRecipient });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@EmailBody", Value = emailBody });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@EmailSubject", Value = subject });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@UserWhoSentIt", Value = userWhoSentIt });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@QueueDate", Value = DateTime.Now });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@SystemGeneralAnnouncementId", Value = systemGeneralAnnouncementId });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@UserName", Value = userName });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@idNumber", Value = idNumber });

                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
</code>```

My Question is two fold. First, is async a viable option with this type of Code (Using Sql server 2012) as I noticed in my research that if you have a database level bottleneck, async could potentially cause dead lock. Second, If Async/await is viable, what would be the best way to actually implement it?

Update: The post method is only retrieving the Id of the SystemGeneralAnnouncement, and the confirmation to start the method. All of the actual execution is being handled inside the method itself.

Update 2: For clarifications Sake, these items are being passed to a task scheduler that fires at a later date, and takes all the stored items in the queue, then delivers them in the background. This is why I am using the SQL call.

答:
if you have a database level bottleneck, async could potentially cause dead lock

Not at all.

However, async won't help you run faster - that's a common misconception.

What you want to do is a batch update.

Body:
in working to develop a new post method. I found that I am running into extremely long wait times on a bottleneck foreach statement. I am saving between 5 and 8k(depending on the items being sent) to the database. The method succeeds, but usually takes upwards of a full 60 seconds. I have been looking into how to actually execute an async method, but I am not sure this will actually solve the problem.

This is the full method

[HttpPost]
        public ActionResult ConfirmSend(int? SystemGeneralAnnouncementId) {
        var systemGeneralAnnouncement = (SystemGeneralAnnouncementId == null) ? null : _uow.SystemGeneralAnnouncementRepository.GetById(SystemGeneralAnnouncementId.Value);
        List<Status> status = new List<Status>();

            if (systemGeneralAnnouncement.Statuses.Length > 0)
            {
                status.AddRange(systemGeneralAnnouncement.Statuses.Split(',').Select(item => (Status) Enum.Parse(typeof (Status), item)));
            }

            var allEmailAddresses = new List<PointOfContact>();
            var EmailAddresses = new List<PointOfContact>();

            var result = new List<PointOfContact>();
            foreach (var item in status)
            {
                result = _uow.PointOfContactRepository.GetAllByStatus(item).ToList();
                allEmailAddresses.AddRange(result);
            }

            if (systemGeneralAnnouncement.SendToRecipients.Contains("(1) All Three Contact Types"))
            {
                mailAddresses = allEmailAddresses;
            }
            else
            {
                if (systemGeneralAnnouncement.SendToRecipients.Contains("(2) All Contacts "))
                {
                    EmailAddresses.AddRange(allEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.Primary).ToList());
                }
                if (systemGeneralAnnouncement.SendToRecipients.Contains("(3) All Compliance contacts"))
                {
                    pocEmailAddresses.AddRange(allEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.Secondary).ToList());
                }
                if (systemGeneralAnnouncement.SendToRecipients.Contains("(4) All Authorities"))
                {
                    pocEmailAddresses.AddRange(allEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.SigningAuthority).ToList());
                }
                if (systemGeneralAnnouncement.SendToRecipients.Contains("(5) All Rate Contacts"))
                {
                    EmailAddresses.AddRange(allEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.TuitionRates).ToList());
                }
                if (systemGeneralAnnouncement.SendToRecipients.Contains("(6) Specified Email Address"))
                {
                    var pocs = new List<PointOfContact>();

                    string[] emails = systemGeneralAnnouncement.EmailAddresses.Split(',');

                    foreach (string email in emails)
                    {
                        var addContact = new InstitutionPointOfContact { Email = email };

                        User user = _uow.UserRepository.GetByEmail(email);

                        if (user == null)
                        {
                            addContact.FirstName = "Not Created Account Yet";
                        }
                        else
                        {
                            addContact.FirstName = user.FirstName;
                            addContact.LastName = user.LastName;
                        }

                        List<PointOfContact> idAssociatedToUser =
                            _uow.PointOfContactRepository
                                .GetAllByEmail(email)
                                .ToList();

                        if (idAssociatedToUser.Count == 0)
                        {
                            addContact.IDNumber = "N/A";
                        }
                        else
                        {
                            string[] opeidArray = opeidAssociatedToUser
                                .Select(x => x.OPEIDNumber)
                                .ToArray();

                            addContact.OPEIDNumber = string.Join(",", opeidArray);
                        }
                        Contacts.Add(addContact);
                    }
                    EmailAddresses.AddRange(Contacts);
                }
            }

The Specific Foreach

    if (EmailAddresses.Count > 0)
                {
                    foreach (PointOfContact emailAddress in EmailAddresses.Where(x => x.Email != "").ToList())
                    {
                        string firstName = emailAddress.FirstName == null ? "" : emailAddress.FirstName.Trim();
                        string lastName = emailAddress.LastName == null ? "" : emailAddress.LastName.Trim();

                        string userName = firstName + " " + lastName;

                        string emailBody = WebUtility.HtmlDecode(systemGeneralAnnouncement.EmailBody);

                        SaveToDatabase(emailAddress.Email, emailBody, systemGeneralAnnouncement.Subject, UserIdentityHelper.GetUserEmailAddress + " (" + UserIdentityHelper.GetUserId + ")", systemGeneralAnnouncement.SystemGeneralAnnouncementId, userName, emailAddress.OPEIDNumber);
                        LogInstitutionEmail(systemGeneralAnnouncement.Subject, emailBody, emailAddress.Email, emailAddress.OPEIDNumber, systemGeneralAnnouncement.EmailAttachmentLocation);
                    }
                }
                return View("GeneralAnnouncementGeneratedConfirmation");
            }

And the Database methods:

        private void LogInstitutionEmail(string subject, string emailBody, string email, string opeidNumber, string emailAttachment)
        {
            try
            {
                using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MasterContext"].ConnectionString))
                {
                    conn.Open();
                    var cmd = new SqlCommand("Insert Into InstitutionEmails (Since, Subject, Email, EmailAddress, OpeidNumber, FirstReadDateTime, Attachment) VALUES(@Since, @Subject, @Email, @EmailAddress, @idNumber, NULL, @Attachment)", conn);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Since", Value = DateTime.Now });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Subject", Value = subject });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Email", Value = emailBody });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@EmailAddress", Value = email });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@idNumber", Value = idNumber });

                    if (!string.IsNullOrEmpty(emailAttachment))
                    {
                        cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Attachment", Value = emailAttachment });
                    }

                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void SaveToDatabase(string emailRecipient, string emailBody, string subject, string userWhoSentIt, int systemGeneralAnnouncementId, string userName, string opeidNumber)
        {
            try
            {
                using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MasterContext"].ConnectionString))
                {
                    conn.Open();
                    var cmd = new SqlCommand("Insert Into EmailQueue (EmailRecipients, EmailBody, EmailSubject, UserWhoSentIt, QueueDate, SystemGeneralAnnouncementId, UserName, idNumber) VALUES(@EmailRecipients, @EmailBody, @EmailSubject, @UserWhoSentIt, @QueueDate, @SystemGeneralAnnouncementId, @UserName, @idNumber)", conn);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add(new SqlParameter() {ParameterName = "@EmailRecipients", Value = emailRecipient });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@EmailBody", Value = emailBody });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@EmailSubject", Value = subject });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@UserWhoSentIt", Value = userWhoSentIt });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@QueueDate", Value = DateTime.Now });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@SystemGeneralAnnouncementId", Value = systemGeneralAnnouncementId });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@UserName", Value = userName });
                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@idNumber", Value = idNumber });

                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }

My Question is two fold. First, is async a viable option with this type of Code (Using Sql server 2012) as I noticed in my research that if you have a database level bottleneck, async could potentially cause dead lock. Second, If Async/await is viable, what would be the best way to actually implement it?

Update: The post method is only retrieving the Id of the SystemGeneralAnnouncement, and the confirmation to start the method. All of the actual execution is being handled inside the method itself.

Update 2: For clarifications Sake, these items are being passed to a task scheduler that fires at a later date, and takes all the stored items in the queue, then delivers them in the background. This is why I am using the SQL call.


问:
Angularjs multiplication operation in html
I am using http get request to get data and show it in my directive, gauge directive has value attribute that takes number, i am binding like this value="" attribute from ng-repeat in html. The problem is the value i'm getting from get request is in decimal like 0.23 etc but i need to multiply this value with 100 to show it in percentage, is it possible in angularjs to do something like this.
I tried like

```<code><div id="main" ng-repeat="n in myObject">

<gage name="name" id="myGage-n.id" value=n.myValuex100>

</div>
</code>```

But when i check in developer toolbar the value attribute shows value=n.myValuex100 as is. It's not replacing it with the multiplied value , in this case expected value is "23"

Please suggest if i'm missing something or need to do in a different way

答:
Actually w/o {{}} and "" worked for me.
Like this

Body:
I am using http get request to get data and show it in my directive, gauge directive has value attribute that takes number, i am binding like this value="" attribute from ng-repeat in html. The problem is the value i'm getting from get request is in decimal like 0.23 etc but i need to multiply this value with 100 to show it in percentage, is it possible in angularjs to do something like this.
I tried like

<gage name="name" id="myGage-n.id" value=n.myValuex100>

But when i check in developer toolbar the value attribute shows value=n.myValuex100 as is. It's not replacing it with the multiplied value , in this case expected value is "23"

Please suggest if i'm missing something or need to do in a different way


问:
printing out the number of times a number repeats itself in an Array (ArrayIndexOutofBoundException)
what I'm trying to do is filling an array of 20 integers with random numbers, and then printing out the number of times each integer repeats itself. I'm getting an error when trying to print out the number of repetitions... Here's my code:

```<code>package nivel3;

import java.util.Random;

public class exercicio3 {

    public static void main(String[] args) {
        int[] numeros;
        int i=0;

        numeros=new int[20];

        Random rand=new Random();
        System.out.println("FILLING ARRAY WITH 20 RANDOM INTEGERS (FROM 0-9) \n");
        do {
            for (i=0; i<20; i++) {
                numeros[i]=rand.nextInt(10);
                System.out.printf("position"+i+of numeros[20]: "+numeros[i]+"\n\n");
            }
        } while (i<20);

        System.out.println("--------------------------------------------------------------------- \n");
        System.out.println("SHOWING THE REPEATED POSITIONS (FOR EACH POSITION OF THE ARRAY)\n");

            for(int j=0; j<20; j++) {
                int k=0;
                do {
                    k++;
                    if (numeros[j]==numeros[k])
                        System.out.printf("the integer in the ["+j+"] position is equal to the integer in the ["+k+"] position \n");

                }while (k<20);
           }
    }
}
</code>```

Here's the error code:

```<code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
    at nivel3.exercicio3.main(exercicio3.java:29)
</code>```

答: You are doing k++ before numeros[k], which is causing ArrayIndexOutOfBoundsException on the last iteration. Move k++ to the end of your loop instead of the beginning.

Body:
what I'm trying to do is filling an array of 20 integers with random numbers, and then printing out the number of times each integer repeats itself. I'm getting an error when trying to print out the number of repetitions... Here's my code:

package nivel3;

import java.util.Random;

public class exercicio3 {

    public static void main(String[] args) {
        int[] numeros;
        int i=0;

        numeros=new int[20];

        Random rand=new Random();
        System.out.println("FILLING ARRAY WITH 20 RANDOM INTEGERS (FROM 0-9) \n");
        do {
            for (i=0; i<20; i++) {
                numeros[i]=rand.nextInt(10);
                System.out.printf("position"+i+of numeros[20]: "+numeros[i]+"\n\n");
            }
        } while (i<20);

        System.out.println("--------------------------------------------------------------------- \n");
        System.out.println("SHOWING THE REPEATED POSITIONS (FOR EACH POSITION OF THE ARRAY)\n");

            for(int j=0; j<20; j++) {
                int k=0;
                do {
                    k++;
                    if (numeros[j]==numeros[k])
                        System.out.printf("the integer in the ["+j+"] position is equal to the integer in the ["+k+"] position \n");

                }while (k<20);
           }
    }
}

Here's the error code:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
    at nivel3.exercicio3.main(exercicio3.java:29)


问:
Reveal toggle hide other div jquery
I have 2 links that both reveal different divs. I've got it slide toggling all fine. But what i need it to do is collapse the opposite toggle (if it's open). Similar to how an accordion panel works (when you trigger a reveal toggle link the open panel closes and the newly triggered panel opens).

Here's the jQuery I'm currently using

```<code>//Left reveal toggle
$(".left-reveal-toggle").on("click", function () {
    $('.left-reveal-section').slideToggle("slow");
    $(".left-reveal-toggle").toggleClass("active");
});

//Right reveal toggle
$(".right-reveal-toggle").on("click", function () {
    $('.right-reveal-section').slideToggle("slow");
    $(".right-reveal-toggle").toggleClass("active");
});
</code>```

Here's a working JSFiddle link: http://jsfiddle.net/wq73aeuh/1/

//Left reveal toggle
$(".left-reveal-toggle").on("click", function() {
  $('.left-reveal-section').slideToggle("slow");
  $(".left-reveal-toggle").toggleClass("active");
});

//Right reveal toggle
$(".right-reveal-toggle").on("click", function() {
  $('.right-reveal-section').slideToggle("slow");
  $(".right-reveal-toggle").toggleClass("active");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.left-panel {
  min-height: 400px;
  background: #31b9ce;
  width: 50%;
  float: left;
  text-align: center;
}

.right-panel {
  min-height: 400px;
  background: #4f5cd6;
  width: 50%;
  float: left;
  text-align: center;
}

.left-panel-reveal {
  min-height: 400px;
  background: #31b9ce;
  width: 50%;
  float: left;
  text-align: center;
}

.right-panel-reveal {
  min-height: 400px;
  background: #4f5cd6;
  width: 50%;
  float: left;
  text-align: center;
}

.hide {
  display: none;
}

.clear {
  clear: both;
  font-size: 0px;
  line-height: 0px;
  display: block;
}

html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
font,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}</code>```

  Read more form left panel

  Read more from right panel

left panel reveal content

left panel reveal content

right panel reveal content

right panel reveal content

```

答:
Use at the top of function in right:
    $('.left-reveal-section').slideUp('slow');
And top of function in left:
    $('.right-reveal-section').slideUp('slow'); </p>

Title: Reveal toggle hide other div jquery

Body:
I have 2 links that both reveal different divs. I've got it slide toggling all fine. But what i need it to do is collapse the opposite toggle (if it's open). Similar to how an accordion panel works (when you trigger a reveal toggle link the open panel closes and the newly triggered panel opens).

Here's the jQuery I'm currently using

//Left reveal toggle
$(".left-reveal-toggle").on("click", function () {
    $('.left-reveal-section').slideToggle("slow");
    $(".left-reveal-toggle").toggleClass("active");
});

//Right reveal toggle
$(".right-reveal-toggle").on("click", function () {
    $('.right-reveal-section').slideToggle("slow");
    $(".right-reveal-toggle").toggleClass("active");
});

Here's a working JSFiddle link: http://jsfiddle.net/wq73aeuh/1/

//Left reveal toggle
$(".left-reveal-toggle").on("click", function() {
  $('.left-reveal-section').slideToggle("slow");
  $(".left-reveal-toggle").toggleClass("active");
});

//Right reveal toggle
$(".right-reveal-toggle").on("click", function() {
  $('.right-reveal-section').slideToggle("slow");
  $(".right-reveal-toggle").toggleClass("active");
});

.left-panel {
  min-height: 400px;
  background: #31b9ce;
  width: 50%;
  float: left;
  text-align: center;
}

.right-panel {
  min-height: 400px;
  background: #4f5cd6;
  width: 50%;
  float: left;
  text-align: center;
}

.left-panel-reveal {
  min-height: 400px;
  background: #31b9ce;
  width: 50%;
  float: left;
  text-align: center;
}

.right-panel-reveal {
  min-height: 400px;
  background: #4f5cd6;
  width: 50%;
  float: left;
  text-align: center;
}

.hide {
  display: none;
}

.clear {
  clear: both;
  font-size: 0px;
  line-height: 0px;
  display: block;
}

html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
font,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

  Read more form left panel

  Read more from right panel

left panel reveal content

left panel reveal content

right panel reveal content

right panel reveal content


问:
Extract word before all matching character in bash
How to extract all the string before :, I could get only the first as below

```<code>$ echo "cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee" | sed 's/:.*//g'
$ cc_dd
# want to print cc_dd aa_bb and ee_ff
</code>```

答:
awk to the rescue!

```<code>echo "cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee" |
awk -v RS=\; '{split($0,a,":"); print a[1]}'

cc_dd
aa_bb
ee_ff
</code>```

Body:
How to extract all the string before :, I could get only the first as below

$ echo "cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee" | sed 's/:.*//g'
$ cc_dd
# want to print cc_dd aa_bb and ee_ff

Body:
awk to the rescue!

echo "cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee" |
awk -v RS=\; '{split($0,a,":"); print a[1]}'

cc_dd
aa_bb
ee_ff


问:
Jackson: sub-class properties hidden by @JsonProperty & @JsonView on super class
Suppose I have two classes:

```<code>public class Super {
    @JsonView(SpecialCaseView.class)
    @JsonProperty("name")
    public String getDisplayName() {
        return "super name";
    }
}
</code>```

and

```<code>public class Duper extends Super {
    private String name = "John Smith";

    public String getName() {
       return name;
    }
}
</code>```

When I do a normal serialization of a Duper object, (e.g, with new ObjectMapper().writerWithView(ADifferentView.class).writeValueAsString(new Duper())), I would expect to get

```<code>{
  "name": "John Smith"
}
</code>```

Instead, I get nothing. It appears this is because the super class's "name" property is getting picked up first, but then Jackson ignores it because of the specific view.

Is this a bug?

If not, is there any way around this, or at least a way to detect it, or get a warning?

答:
Hmm, which version of Jackson are you using? Anyway, I just tried this code (with Jackson 1)

```<code>ObjectMapper mapper = new ObjectMapper();

String json = mapper.writeValueAsString(new Duper());

System.out.println(json);
</code>```

Which results in

```<code>{"name":"super name"}
</code>```

If you put @JsonView on your getName() method in the subclass, you will get what you want.

```<code>@JsonView(SpecialCaseView.class)
public String getName() {
   return name;
}
</code>```

The result

```<code>{"name":"John Smith"}
</code>```

Body:
Suppose I have two classes:

public class Super {
    @JsonView(SpecialCaseView.class)
    @JsonProperty("name")
    public String getDisplayName() {
        return "super name";
    }
}

and

public class Duper extends Super {
    private String name = "John Smith";

    public String getName() {
       return name;
    }
}

When I do a normal serialization of a Duper object, (e.g, with new ObjectMapper().writerWithView(ADifferentView.class).writeValueAsString(new Duper())), I would expect to get

{
  "name": "John Smith"
}

Instead, I get nothing. It appears this is because the super class's "name" property is getting picked up first, but then Jackson ignores it because of the specific view.

Is this a bug?

If not, is there any way around this, or at least a way to detect it, or get a warning?

Body:
Hmm, which version of Jackson are you using? Anyway, I just tried this code (with Jackson 1)

ObjectMapper mapper = new ObjectMapper();

String json = mapper.writeValueAsString(new Duper());

System.out.println(json);

Which results in

{"name":"super name"}

If you put @JsonView on your getName() method in the subclass, you will get what you want.

@JsonView(SpecialCaseView.class)
public String getName() {
   return name;
}

The result

{"name":"John Smith"}


问:
Login to the API manager through Eclipse Developer Tools
I'm unable to connect to the API Manager when using Developer Tools for WSO2. I'm following the instructions on this page. When I try to log in to the publisher I get this error

When I try connecting to the publisher through port 9443 I get this error.

The environment I'm running is APIM 2.1.0 with the IDS 5.3.0 as key manager. I'm using a clustered environment as well with two gateway workers and the gate manager on the APIM side. Then two IDS servers.

I'm trying to connect from my Windows device, so I'm not on the actual Linux server. Also, I have a secondary user store added and when I login to the store and publisher I use those credentials. I tried both my secondary user store credentials and the admin credentials both return same error.

What are some possible fixes I can do? Or I'm I off with some configurations?

答:
This error happens because you have to use the WSO2 trust store in your Java Application. If the plugin doesn't allow you to pass the JVM args, you probably need to add them on the eclipse.ini file, located inside the Eclipse folder.

Assuming you didn't change the default settings, pass the following JVM parameters to and you're good to go.

```<code>-Djavax.net.ssl.trustStore=<path_to_wso2_apim>/repository/resources/security/wso2carbon.jks
-Djavax.net.ssl.trustStorePassword=wso2carbon
-Djavax.net.ssl.trustStoreType=JKS
</code>```

If your Eclipse and the WSO2 installation are not int he same computer you just need to copy the wso2carbon.jks to your PC and update the location on the -Djavax.net.ssl.trustStore argument above.

Body:
This error happens because you have to use the WSO2 trust store in your Java Application. If the plugin doesn't allow you to pass the JVM args, you probably need to add them on the eclipse.ini file, located inside the Eclipse folder.

Assuming you didn't change the default settings, pass the following JVM parameters to and you're good to go.

-Djavax.net.ssl.trustStore=<path_to_wso2_apim>/repository/resources/security/wso2carbon.jks
-Djavax.net.ssl.trustStorePassword=wso2carbon
-Djavax.net.ssl.trustStoreType=JKS

If your Eclipse and the WSO2 installation are not int he same computer you just need to copy the wso2carbon.jks to your PC and update the location on the -Djavax.net.ssl.trustStore argument above.


问:
Using Federated Identities to create user in User Pool AWS
i am using AWS Cognito to manage my app Sign In and Log In, on this way i authenticate my user against the user pool and obtain the jwt tokens (id token, access token and refresh token), i am using the id token to authenticate my app against the backend.

Now i want to integrate my app to make Sign in and Log in with Facebook, Gmail and others, as far as i know i should use the AWS Federated Identities, but i dont know how can i create my user in the user pool using the Facebook Login (p.eg) and obtain the tokens, may someone help me?

答: The way to federate identities into AWS is by using AWS Cognito Federated Identity as you mentioned. Your user pool can be configured as an identity provider for your identity pool, similar to Facebook, and Google. So all these options function as identity providers for your identity pool in order to federate identities into AWS.</p>


问:
Build failed ionic 2
I have an Ionic 2 app and it was working well, but a while ago I installed insomnia plugin and now I can't build the production version!

If I do:
$ionic run android or $ionic run android --consolelogs --livereload, it works well and Insomia works fine.

But, now when I do:

```<code>$ionic build android --prod --release
</code>```

I get:

```<code>build prod failed: Cannot read property 'Plugin' of undefined, resolving symbol Insomnia in /media/....blabla.../node_modules/@ionic-native/insomnia/index.d.ts
</code>```

I followed the steps of the official documentation. (insomnia plugin)

Thank's so much in advance!!!

EDIT:

When I installed the Insomnia plugin I had this but I did not give importance because I got it previous times:

```<code>├── @ionic-native/insomnia@3.4.4
└── UNMET PEER DEPENDENCY rxjs@5.0.1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN @angular/core@2.2.1 requires a peer of rxjs@5.0.0-beta.12 but none was installed.
npm WARN @angular/http@2.2.1 requires a peer of rxjs@5.0.0-beta.12 but none was installed.
npm WARN ionic-angular@2.1.0 requires a peer of rxjs@5.0.0-beta.12 but none was installed.
</code>```

packaje.json:

```<code>{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "2.2.1",
    "@angular/compiler": "2.2.1",
    "@angular/compiler-cli": "2.2.1",
    "@angular/core": "2.2.1",
    "@angular/forms": "2.2.1",
    "@angular/http": "2.2.1",
    "@angular/platform-browser": "2.2.1",
    "@angular/platform-browser-dynamic": "2.2.1",
    "@angular/platform-server": "2.2.1",
    "@ionic-native/core": "^3.4.4",
    "@ionic-native/insomnia": "^3.4.4",
    "@ionic/storage": "1.1.7",
    "angular2-fullcalendar": "^1.1.1",
    "angularfire2": "^2.0.0-beta.6-preview",
    "firebase": "^3.6.4",
    "ionic-angular": "^2.1.0",
    "ionic-native": "^2.5.1",
    "ionicons": "3.0.0",
    "jquery-ui": "^1.12.1",
    "rxjs": "^5.0.1",
    "soundcloud": "^3.1.2",
    "zone.js": "0.6.26"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.1.3",
    "typescript": "2.0.9"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-statusbar",
    "cordova-plugin-console",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "description": "Mindfulness: An Ionic project"
}
</code>```

config.xml:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="com.ionicframework.mindfulness924927" version="0.0.55" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  <name>Visión Clara</name>
  <description>An awesome Ionic/Cordova app.</description>
  <author email="hi@ionicframework" href="http://ionicframework.com/">Ionic Framework Team</author>
  <content src="index.html"/>
  <access origin="*"/>
  <allow-intent href="http://*/*"/>
  <allow-intent href="https://*/*"/>
  <allow-intent href="tel:*"/>
  <allow-intent href="sms:*"/>
  <allow-intent href="mailto:*"/>
  <allow-intent href="geo:*"/>
  <platform name="android">
    <allow-intent href="market:*"/>
    <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png"/>
    <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png"/>
    <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png"/>
    <icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png"/>
    <icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png"/>
    <icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png"/>
    <splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png"/>
    <splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png"/>
    <splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png"/>
    <splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png"/>
    <splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png"/>
    <splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png"/>
    <splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png"/>
    <splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png"/>
    <splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png"/>
    <splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png"/>
    <splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png"/>
    <splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png"/>
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*"/>
    <allow-intent href="itms-apps:*"/>
  </platform>
  <preference name="webviewbounce" value="false"/>
  <preference name="UIWebViewBounce" value="false"/>
  <preference name="DisallowOverscroll" value="true"/>
  <preference name="android-minSdkVersion" value="19"/>
  <preference name="BackupWebStorage" value="none"/>
  <preference name="SplashMaintainAspectRatio" value="true"/>
  <preference name="FadeSplashScreenDuration" value="300"/>
  <preference name="SplashScreen" value="screen"/>
  <preference name="SplashScreenDelay" value="3000"/>
  <preference name="loadUrlTimeoutValue" value="700000"/>
  <preference name="orientation" value="portrait"/>
  <feature name="StatusBar">
    <param name="ios-package" onload="true" value="CDVStatusBar"/>
  </feature>
  <allow-navigation href="http://192.168.1.10:8000"/>
  <allow-navigation href="http://192.168.0.47:8000"/>
  <allow-navigation href="http://192.168.120.57:8000"/>
  <allow-navigation href="http://192.168.120.54:8000"/>
  <allow-navigation href="http://192.168.120.60:8000"/>
  <allow-navigation href="http://192.168.120.51:8000"/>
  <allow-navigation href="http://192.168.120.53:8000"/>
  <allow-navigation href="http://192.168.120.52:8000"/>
  <allow-navigation href="http://192.168.120.55:8000"/>
  <allow-navigation href="http://192.168.120.54:8100"/>
  <allow-navigation href="http://192.168.1.10:8100"/>
  <allow-navigation href="http://192.168.43.177:8100"/>
  <allow-navigation href="http://192.168.0.47:8100"/>
  <allow-navigation href="http://192.168.120.55:8100"/>
  <allow-navigation href="http://192.168.120.50:8100"/>
  <plugin name="cordova-sqlite-storage" spec="~2.0.1"/>
  <plugin name="cordova-plugin-network-information" spec="~1.3.1"/>
  <plugin name="cordova-plugin-http" spec="~1.2.0"/>
  <plugin name="cordova-plugin-media" spec="~2.4.1"/>
  <plugin name="cordova-plugin-file" spec="~4.3.1"/>
  <icon src="resources/android/icon/drawable-xhdpi-icon.png"/>
</widget>
</code>```

EDIT 2:

```<code>{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "2.2.1",
    "@angular/compiler": "2.2.1",
    "@angular/compiler-cli": "2.2.1",
    "@angular/core": "2.2.1",
    "@angular/forms": "2.2.1",
    "@angular/http": "2.2.1",
    "@angular/platform-browser": "2.2.1",
    "@angular/platform-browser-dynamic": "2.2.1",
    "@angular/platform-server": "2.2.1",
    "@ionic-native/core": "^3.4.4",
    "@ionic-native/facebook": "^3.4.4",
    "@ionic-native/file": "^3.4.4",
    "@ionic-native/in-app-purchase": "^3.4.4",
    "@ionic-native/insomnia": "^3.4.4",
    "@ionic-native/local-notifications": "^3.4.4",
    "@ionic-native/media": "^3.4.4",
    "@ionic-native/network": "^3.4.4",
    "@ionic-native/screenshot": "^3.4.4",
    "@ionic-native/social-sharing": "^3.4.4",
    "@ionic-native/splash-screen": "^3.4.4",
    "@ionic-native/status-bar": "^3.4.4",
    "@ionic/storage": "1.1.7",
    "angular2-fullcalendar": "^1.1.1",
    "angularfire2": "^2.0.0-beta.6-preview",
    "firebase": "^3.6.4",
    "ionic-angular": "^2.1.0",
    "ionicons": "3.0.0",
    "jquery-ui": "^1.12.1",
    "rxjs": "^5.0.1",
    "soundcloud": "^3.1.2",
    "zone.js": "0.6.26"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.1.3",
    "typescript": "2.0.9"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-statusbar",
    "cordova-plugin-console",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "description": "Mindfulness: An Ionic project"
}
</code>```

答:
Your problem is here "ionic-native": "^2.5.1",.You have to remove this from your package.json file and after that run npm i.You cannot keep both latest "@ionic-native/core": "^3.4.4", and old one.You didn't upgrade the native module properly.So now you have to do that as mentioned above.Before do that keep a backup of your project.

You have to implement your plugins as providers.Please see this doc.

Update:

uninstall

```<code>cordova plugin remove cordova-plugin-statusbar --save

npm uninstall @ionic-native/status-bar --save
</code>```

install

```<code>ionic plugin add cordova-plugin-statusbar --save

npm install --save @ionic-native/status-bar
</code>```

Title: Build failed ionic 2

Body:
I have an Ionic 2 app and it was working well, but a while ago I installed insomnia plugin and now I can't build the production version!

If I do:
$ionic run android or $ionic run android --consolelogs --livereload, it works well and Insomia works fine.

But, now when I do:

$ionic build android --prod --release

I get:

build prod failed: Cannot read property 'Plugin' of undefined, resolving symbol Insomnia in /media/....blabla.../node_modules/@ionic-native/insomnia/index.d.ts

I followed the steps of the official documentation. (insomnia plugin)

Thank's so much in advance!!!

EDIT:

When I installed the Insomnia plugin I had this but I did not give importance because I got it previous times:

├── @ionic-native/insomnia@3.4.4
└── UNMET PEER DEPENDENCY rxjs@5.0.1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN @angular/core@2.2.1 requires a peer of rxjs@5.0.0-beta.12 but none was installed.
npm WARN @angular/http@2.2.1 requires a peer of rxjs@5.0.0-beta.12 but none was installed.
npm WARN ionic-angular@2.1.0 requires a peer of rxjs@5.0.0-beta.12 but none was installed.

packaje.json:

{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "2.2.1",
    "@angular/compiler": "2.2.1",
    "@angular/compiler-cli": "2.2.1",
    "@angular/core": "2.2.1",
    "@angular/forms": "2.2.1",
    "@angular/http": "2.2.1",
    "@angular/platform-browser": "2.2.1",
    "@angular/platform-browser-dynamic": "2.2.1",
    "@angular/platform-server": "2.2.1",
    "@ionic-native/core": "^3.4.4",
    "@ionic-native/insomnia": "^3.4.4",
    "@ionic/storage": "1.1.7",
    "angular2-fullcalendar": "^1.1.1",
    "angularfire2": "^2.0.0-beta.6-preview",
    "firebase": "^3.6.4",
    "ionic-angular": "^2.1.0",
    "ionic-native": "^2.5.1",
    "ionicons": "3.0.0",
    "jquery-ui": "^1.12.1",
    "rxjs": "^5.0.1",
    "soundcloud": "^3.1.2",
    "zone.js": "0.6.26"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.1.3",
    "typescript": "2.0.9"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-statusbar",
    "cordova-plugin-console",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "description": "Mindfulness: An Ionic project"
}

config.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="com.ionicframework.mindfulness924927" version="0.0.55" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  <name>Visión Clara</name>
  <description>An awesome Ionic/Cordova app.</description>
  <author email="hi@ionicframework" href="http://ionicframework.com/">Ionic Framework Team</author>
  <content src="index.html"/>
  <access origin="*"/>
  <allow-intent href="http://*/*"/>
  <allow-intent href="https://*/*"/>
  <allow-intent href="tel:*"/>
  <allow-intent href="sms:*"/>
  <allow-intent href="mailto:*"/>
  <allow-intent href="geo:*"/>
  <platform name="android">
    <allow-intent href="market:*"/>
    <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png"/>
    <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png"/>
    <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png"/>
    <icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png"/>
    <icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png"/>
    <icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png"/>
    <splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png"/>
    <splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png"/>
    <splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png"/>
    <splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png"/>
    <splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png"/>
    <splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png"/>
    <splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png"/>
    <splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png"/>
    <splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png"/>
    <splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png"/>
    <splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png"/>
    <splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png"/>
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*"/>
    <allow-intent href="itms-apps:*"/>
  </platform>
  <preference name="webviewbounce" value="false"/>
  <preference name="UIWebViewBounce" value="false"/>
  <preference name="DisallowOverscroll" value="true"/>
  <preference name="android-minSdkVersion" value="19"/>
  <preference name="BackupWebStorage" value="none"/>
  <preference name="SplashMaintainAspectRatio" value="true"/>
  <preference name="FadeSplashScreenDuration" value="300"/>
  <preference name="SplashScreen" value="screen"/>
  <preference name="SplashScreenDelay" value="3000"/>
  <preference name="loadUrlTimeoutValue" value="700000"/>
  <preference name="orientation" value="portrait"/>
  <feature name="StatusBar">
    <param name="ios-package" onload="true" value="CDVStatusBar"/>
  </feature>
  <allow-navigation href="http://192.168.1.10:8000"/>
  <allow-navigation href="http://192.168.0.47:8000"/>
  <allow-navigation href="http://192.168.120.57:8000"/>
  <allow-navigation href="http://192.168.120.54:8000"/>
  <allow-navigation href="http://192.168.120.60:8000"/>
  <allow-navigation href="http://192.168.120.51:8000"/>
  <allow-navigation href="http://192.168.120.53:8000"/>
  <allow-navigation href="http://192.168.120.52:8000"/>
  <allow-navigation href="http://192.168.120.55:8000"/>
  <allow-navigation href="http://192.168.120.54:8100"/>
  <allow-navigation href="http://192.168.1.10:8100"/>
  <allow-navigation href="http://192.168.43.177:8100"/>
  <allow-navigation href="http://192.168.0.47:8100"/>
  <allow-navigation href="http://192.168.120.55:8100"/>
  <allow-navigation href="http://192.168.120.50:8100"/>
  <plugin name="cordova-sqlite-storage" spec="~2.0.1"/>
  <plugin name="cordova-plugin-network-information" spec="~1.3.1"/>
  <plugin name="cordova-plugin-http" spec="~1.2.0"/>
  <plugin name="cordova-plugin-media" spec="~2.4.1"/>
  <plugin name="cordova-plugin-file" spec="~4.3.1"/>
  <icon src="resources/android/icon/drawable-xhdpi-icon.png"/>
</widget>

EDIT 2:

{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "2.2.1",
    "@angular/compiler": "2.2.1",
    "@angular/compiler-cli": "2.2.1",
    "@angular/core": "2.2.1",
    "@angular/forms": "2.2.1",
    "@angular/http": "2.2.1",
    "@angular/platform-browser": "2.2.1",
    "@angular/platform-browser-dynamic": "2.2.1",
    "@angular/platform-server": "2.2.1",
    "@ionic-native/core": "^3.4.4",
    "@ionic-native/facebook": "^3.4.4",
    "@ionic-native/file": "^3.4.4",
    "@ionic-native/in-app-purchase": "^3.4.4",
    "@ionic-native/insomnia": "^3.4.4",
    "@ionic-native/local-notifications": "^3.4.4",
    "@ionic-native/media": "^3.4.4",
    "@ionic-native/network": "^3.4.4",
    "@ionic-native/screenshot": "^3.4.4",
    "@ionic-native/social-sharing": "^3.4.4",
    "@ionic-native/splash-screen": "^3.4.4",
    "@ionic-native/status-bar": "^3.4.4",
    "@ionic/storage": "1.1.7",
    "angular2-fullcalendar": "^1.1.1",
    "angularfire2": "^2.0.0-beta.6-preview",
    "firebase": "^3.6.4",
    "ionic-angular": "^2.1.0",
    "ionicons": "3.0.0",
    "jquery-ui": "^1.12.1",
    "rxjs": "^5.0.1",
    "soundcloud": "^3.1.2",
    "zone.js": "0.6.26"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.1.3",
    "typescript": "2.0.9"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-statusbar",
    "cordova-plugin-console",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "description": "Mindfulness: An Ionic project"
}

Body:
Your problem is here "ionic-native": "^2.5.1",.You have to remove this from your package.json file and after that run npm i.You cannot keep both latest "@ionic-native/core": "^3.4.4", and old one.You didn't upgrade the native module properly.So now you have to do that as mentioned above.Before do that keep a backup of your project.

You have to implement your plugins as providers.Please see this doc.

Update:

uninstall

cordova plugin remove cordova-plugin-statusbar --save

npm uninstall @ionic-native/status-bar --save

install

ionic plugin add cordova-plugin-statusbar --save

npm install --save @ionic-native/status-bar


问:
Unable to fire process
I have application which loads images like this:

```<code>someImage = Image.FromFile(@"picture.png");
</code>```

and another application which fires the previous one like this:

```<code>Process.Start(@"C:\dev\gallery.exe");
</code>```

and if I do like this I get an Exception: "picture.png", nothing more, but if I run this first gallery application normally using the icon or cmd then it works ok.

EDIT: I have just noticed that if I put these applications in the same folder then it works properly, why? what I can do then?

答: Looks like a working directory problem. Try using the Process.Start(ProcessStartInfo) overload with the WorkingDirectory property set properly.

Title: Unable to fire process

Body:
I have application which loads images like this:

someImage = Image.FromFile(@"picture.png");

and another application which fires the previous one like this:

Process.Start(@"C:\dev\gallery.exe");

and if I do like this I get an Exception: "picture.png", nothing more, but if I run this first gallery application normally using the icon or cmd then it works ok.

EDIT: I have just noticed that if I put these applications in the same folder then it works properly, why? what I can do then?


问:
CSS: Background Color on Element With Automatic Width
The problem domain.
I would like to style a HTML list using CSS. The list will serve as a navigation bar and always be on screen. To avoid wasting screen space, the menu should by default be in a collapsed state and only expand on mouse-over.

Expected behaviour.
If not hovered-over, the navigation should only display the list’s numbering. If the user hovers over one list item, it should expand to show that item’s text. The navigation bar’s background color should extend to the end of that text, but only around the item which is hovered over. That is, the item should “pop out” of the navigation.

Actual behaviour. I cannot find a way to make the background color work in this scenario. If the list item’s width is set to auto, then the text appears as it should, but the background color doesn’t extend with the list item. If I set a fixed width for the list item (l. 33 in the fiddle), e.g. 300px, then the background color does extend with the text, but I wish to avoid static sizes. Why do static widths behave differently from automatic ones?

I’ve tried fixed positioning of hovered-over list items. That would create the effect I have in mind, but it also has two undesirable side-effects: It removes the automatic numbering from the selected item, and it removes the item from the text flow, which makes the successive items move up in the list. Both of them would have to be compensated for manually, which I’d like to avoid.

JSFiddle and Code
This fiddle illustrates the problem: https://jsfiddle.net/3n8g03y9/

body {
  /* For better visibility of white text */
  background-color: #002;
}

/* Container div */

#navigation {
  position: fixed;
  font-size: 20pt;
  display: block;
  background-color: #333;
  /* dark grey */
}

/* Main topic list */

#navigation>ol {
  box-sizing: border-box;
  list-style-position: inside;
  padding-left: 10px;
  width: 40px;
}

/* Main topic entry */

#navigation>ol>li {
  white-space: nowrap;
  background-color: #333;
  #333;
  /* dark grey */
  color: white;
  overflow: hidden;
  /* Only show the number until hover */
  width: 30px;
  /* 40px minus the OL’s padding */
}

/* Hover over main topic entry */

#navigation>ol>li:hover {
  width: auto;
  overflow: visible;
  ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="navigation">
  <ol>
    <li> Topic 1</li>
    <li> Topic 2</li>
    <li> Topic 3</li>
    <li> Topic 4</li>
  </ol>
</div></code>```

答:
The simple answer is to use set your li elements to float, like this:

```<code>/* Main topic entry */
    #navigation > ol > li{
    white-space: nowrap;
    float: left; /* Add this to show background when hovering */
    background-color: #333; /* dark grey */
    color: white;
    overflow: hidden; /* Only show the number until hover */
    width: 30px; /* 40px minus the OL’s padding */
</code>```

Check this pen for demo: http://codepen.io/MikkelTN/pen/XMoxEa

Body:
The problem domain.
I would like to style a HTML list using CSS. The list will serve as a navigation bar and always be on screen. To avoid wasting screen space, the menu should by default be in a collapsed state and only expand on mouse-over.

Expected behaviour.
If not hovered-over, the navigation should only display the list’s numbering. If the user hovers over one list item, it should expand to show that item’s text. The navigation bar’s background color should extend to the end of that text, but only around the item which is hovered over. That is, the item should “pop out” of the navigation.

Actual behaviour. I cannot find a way to make the background color work in this scenario. If the list item’s width is set to auto, then the text appears as it should, but the background color doesn’t extend with the list item. If I set a fixed width for the list item (l. 33 in the fiddle), e.g. 300px, then the background color does extend with the text, but I wish to avoid static sizes. Why do static widths behave differently from automatic ones?

I’ve tried fixed positioning of hovered-over list items. That would create the effect I have in mind, but it also has two undesirable side-effects: It removes the automatic numbering from the selected item, and it removes the item from the text flow, which makes the successive items move up in the list. Both of them would have to be compensated for manually, which I’d like to avoid.

JSFiddle and Code
This fiddle illustrates the problem: https://jsfiddle.net/3n8g03y9/

body {
  /* For better visibility of white text */
  background-color: #002;
}

/* Container div */

#navigation {
  position: fixed;
  font-size: 20pt;
  display: block;
  background-color: #333;
  /* dark grey */
}

/* Main topic list */

#navigation>ol {
  box-sizing: border-box;
  list-style-position: inside;
  padding-left: 10px;
  width: 40px;
}

/* Main topic entry */

#navigation>ol>li {
  white-space: nowrap;
  background-color: #333;
  #333;
  /* dark grey */
  color: white;
  overflow: hidden;
  /* Only show the number until hover */
  width: 30px;
  /* 40px minus the OL’s padding */
}

/* Hover over main topic entry */

#navigation>ol>li:hover {
  width: auto;
  overflow: visible;
  ;
}

 Topic 1

 Topic 2

 Topic 3

 Topic 4

Body:
The simple answer is to use set your li elements to float, like this:

/* Main topic entry */
    #navigation > ol > li{
    white-space: nowrap;
    float: left; /* Add this to show background when hovering */
    background-color: #333; /* dark grey */
    color: white;
    overflow: hidden; /* Only show the number until hover */
    width: 30px; /* 40px minus the OL’s padding */

Check this pen for demo: http://codepen.io/MikkelTN/pen/XMoxEa


问:
Gradle multiple versions OF GRADLE
For the sake of clarity: this is NOT about multiple versions of dependencies, it's about multiple versions of Gradle's own jars.

I thought this might have the answer... but there aren't any!

This is Gradle 2.14, with a Windows 10 OS.

I found that gradle was constantly building a new directory under the ".gradle\" directory for this project: alongside the legitimate "2.14\" directory it kept building a "2.2.1\" directory.

I looked under my directory where Gradle is installed: and puzzlingly I found multiple versions of Gradle's jar files: not only 2.14, but 2.13, 1.7, and yes, 2.2.1..

So I decided to manually delete the 2.2.1. jars.  It stopped building the "spurious" 2.2.1 directory.

Can someone tell me how Gradle decides which version of itself it is using?  I'd really like to get rid of those non-2.14 jars and find a way to prevent other versions creeping back in somehow!

答:
Can someone tell me how Gradle decides which version of itself it is using ?

This depends on how you invoke gradle.

Method 1. A gradle command will invoke the version of gradle which is in your GRADLE_HOME path.

Method 2. Using gradle wrapper

A gradlew command will invoke the version of gradle which is configured in your project's gradle\wrapper\gradle-wrapper.properties file if it exists already. If its not, you can create it by gradle wrapper --gradle-version 3.3. Now when you use gradlew , it will always use gradle version 3.3.

The use of gradle wrapper is recommended so that you can consistently reproduce the same build in different machines where the installed gradle versions might be different or even on machines where gradle is not installed, because gradlew.bat and gradlew will be used on windows and linux respectively for bootstrapping the build.

The reason you found multiple version of gradle in your .gradle directory might be because previously you might have tried to build with those versions for gradle.

Title: Gradle multiple versions OF GRADLE


问:
mongoose query same field with different values
Is there a way to user mongoose.find({title:'some title'}) to query the same field with multiple values? For example something like this  mongoose.find({title:'some title', title:'some other title'}) sends back only documents matching title:'some other title is there a way to accomplish this ?

答:
You should use the MongoDB $in operator -

```<code>mongoose.find({title: {$in: ['some title', 'some other title']}})
</code>```

You provide an array to $in operator and it will return all the documents which have an exact title in the array specified.

Body:
You should use the MongoDB $in operator -

mongoose.find({title: {$in: ['some title', 'some other title']}})

You provide an array to $in operator and it will return all the documents which have an exact title in the array specified.


问:
Access rights hierarchy
Drive-SDK Devs, thought you would be the best to ask.
Looking at Slack - Google drive integration for example, it is asking to give permission to following:

View the files on your Google Drive
...

View and manage google Drive files and folders that you have opened or created with this app.

Questions is about the hierarchy of this capability based security levels:

Does this mean that Slack has view access to all google drive files and manage to those opened/created by Slack

or is (4) prevailing in which case (1) is superfluous?

答: The two are additive to the ACL. So Slack has full r/w rights to any files which are created/opened by it. Any files which have not been created/opened by Slack are able to be read by Slack, but may not be changed/deleted.</p>

Title: Access rights hierarchy


问:
How does the static keyword affect thread safety and why?
Take the following examples:

```<code>List<MyObject> objects = new List<MyObject();
</code>```

Example #1:

```<code>static class MyClass1
{
    static void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}
</code>```

Example #2:

```<code>class MyClass2
{
    void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}
</code>```

Example #3:

```<code>static MyClass3 myClass3 = new MyClass3();
class MyClass3
{
    void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}
</code>```

and then calling

```<code> Task.Factory.StartNew(() =>
 {
    MyClass1.MyMember(objects);
 });
</code>```

or

```<code> MyClass2 myClass2 = new MyClass2();
 Task.Factory.StartNew(() =>
 {
    myClass2.MyMember(objects);
 });
</code>```

or

```<code> static MyClass3 myClass3 = new MyClass3();
 Task.Factory.StartNew(() =>
 {
    myClass3.MyMember(objects);
 });
</code>```

Assuming that the application will only have one of these examples, and that the Task is called multiple times simultaneously.

You could think of this as a console app where List<MyObject> objects is instantiated in the Main(), same goes for the tasks, called in Main() multiple times simultaneously.

答:
It depends on internal logic of methods. Currently (with empty implementations) they are all thread-safe.

UPD:

And now they are all NOT thread-safe. I'd like to note that static keyword doesn't provide any "magic" on its own. May be you are confused due to common convention in .NET base class library to make all static members thread-safe and all instance members not thread-safe. While this is true, but it is only convention which developers of BCL decided to follow. In your own code static doesn't provide any thread-safety until you implement it by yourself.

Body:
Take the following examples:

List<MyObject> objects = new List<MyObject();

Example #1:

static class MyClass1
{
    static void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}

Example #2:

class MyClass2
{
    void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}

Example #3:

static MyClass3 myClass3 = new MyClass3();
class MyClass3
{
    void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}

and then calling

 Task.Factory.StartNew(() =>
 {
    MyClass1.MyMember(objects);
 });

or

 MyClass2 myClass2 = new MyClass2();
 Task.Factory.StartNew(() =>
 {
    myClass2.MyMember(objects);
 });

or

 static MyClass3 myClass3 = new MyClass3();
 Task.Factory.StartNew(() =>
 {
    myClass3.MyMember(objects);
 });

Assuming that the application will only have one of these examples, and that the Task is called multiple times simultaneously.

You could think of this as a console app where List<MyObject> objects is instantiated in the Main(), same goes for the tasks, called in Main() multiple times simultaneously.


问:
How to avoid deadlock when the called method uses the same lock that the caller already locked?
How to avoid deadlock when the called method uses the same lock that the caller already locked?

I have and method called closeUnusedConnections(), that creates a std::unique_lock but its caller already created a std::unique_lock with the same std::mutex: Foo::m_myMutex.

Do I have to release the lock before calling the subroutine?

Obs.: I can't integrate both methods because the  closeUnusedConnections is also called independently.

Some code:

```<code>void Foo::closeUnusedConnections()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
}

Foo::CommNodePtr Foo::getConnection()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
   if( true /*some condition*/ )
   {
      lock.unlock();     // The goal is to avoid this unlock
                         // someone could get the lock between
                         // this unlock until closeUnusedConnections's lock.
      closeUnusedConnections();
   }
   // etc
}
</code>```

答:
The pattern of "my class owns a mutex, it locks it on all operations" is a poor one.  It doesn't compose or scale.

Using recursive mutexes patches over some problems, but both has a higher cost and doesn't solve the larger problem that mutexes should be either extremely narrow or extremely explicit.

Mutexes are dangerous.  Deadlocks are hard to avoid.  Shared state is a minefield.

One approach is to write a wrapper around a class like this:

```<code>template<class T>
struct mutex_guarded {
  template<class F>
  auto operator->*( F&& f )
  -> decltype( std::forward<F>(std::declval<T&>()) )
  {
    std::unique_lock<std::mutex> l(m_mtx);
    return std::forward<F>(f)(t);
  }
  template<class F>
  auto operator->*( F&& f ) const
  -> decltype( std::forward<F>(std::declval<T const&>()) )
  {
    std::unique_lock<std::mutex> l(m_mtx);
    return std::forward<F>(f)(t);
  }
  mutex_guarded(T tin):t(std::move(tin)) {}
  T copy_out() const {
    return (*this)->*[](auto& t){ return t; };
  }
  T move_out() {
    return (*this)->*[](auto& t){ return std::move(t); };
  }
  template<class U>
  void assign(U&& u) {
    return (*this)->*[&u](auto& t) { t = std::forward<U>(u); }
  }
  mutex_guarded(T const& tin):t(tin) {}
  mutex_guarded(T && tin):t(std::move(tin)) {}
  mutex_guarded(mutex_guarded const& tin):
    mutex_guarded(tin.copy_out())
  {}
  mutex_guarded(mutex_guarded && tin):
    mutex_guarded(tin.move_out())
  {}
  mutex_guarded& operator=(T const& tin) {
    assign( tin );
    return *this;
  }
  mutex_guarded& operator=(T&& tin) {
    assign( std::move(tin) );
    return *this;
  }
  mutex_guarded& operator=(mutex_guarded const& tin) {
    return *this = tin.copy_out();
  }
  mutex_guarded& operator=(mutex_guarded&& tin) {
    return *this = tin.move_out();
  }
private:
  std::mutex m_mtx;
  T t;
};
</code>```

with some bonus augmentation for copy/move/construct.

Now a mutex_guarded<Foo> foo can be interacted with by doing

```<code>foo->*[&](auto& foo){ foo.closeUnusedConnections(); };
</code>```

and the locking happens in the mutex_guarded, not within Foo itself.  Foo lives without any thread safety itself, and its own calls don't cause problems.

This is still dangerous.  Mutexes are in general dangerous, and the less tightly you control them the more dangerous they are.

Body:
How to avoid deadlock when the called method uses the same lock that the caller already locked?

I have and method called closeUnusedConnections(), that creates a std::unique_lock but its caller already created a std::unique_lock with the same std::mutex: Foo::m_myMutex.

Do I have to release the lock before calling the subroutine?

Obs.: I can't integrate both methods because the  closeUnusedConnections is also called independently.

Some code:

void Foo::closeUnusedConnections()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
}

Foo::CommNodePtr Foo::getConnection()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
   if( true /*some condition*/ )
   {
      lock.unlock();     // The goal is to avoid this unlock
                         // someone could get the lock between
                         // this unlock until closeUnusedConnections's lock.
      closeUnusedConnections();
   }
   // etc
}

Body:
The pattern of "my class owns a mutex, it locks it on all operations" is a poor one.  It doesn't compose or scale.

Using recursive mutexes patches over some problems, but both has a higher cost and doesn't solve the larger problem that mutexes should be either extremely narrow or extremely explicit.

Mutexes are dangerous.  Deadlocks are hard to avoid.  Shared state is a minefield.

One approach is to write a wrapper around a class like this:

template<class T>
struct mutex_guarded {
  template<class F>
  auto operator->*( F&& f )
  -> decltype( std::forward<F>(std::declval<T&>()) )
  {
    std::unique_lock<std::mutex> l(m_mtx);
    return std::forward<F>(f)(t);
  }
  template<class F>
  auto operator->*( F&& f ) const
  -> decltype( std::forward<F>(std::declval<T const&>()) )
  {
    std::unique_lock<std::mutex> l(m_mtx);
    return std::forward<F>(f)(t);
  }
  mutex_guarded(T tin):t(std::move(tin)) {}
  T copy_out() const {
    return (*this)->*[](auto& t){ return t; };
  }
  T move_out() {
    return (*this)->*[](auto& t){ return std::move(t); };
  }
  template<class U>
  void assign(U&& u) {
    return (*this)->*[&u](auto& t) { t = std::forward<U>(u); }
  }
  mutex_guarded(T const& tin):t(tin) {}
  mutex_guarded(T && tin):t(std::move(tin)) {}
  mutex_guarded(mutex_guarded const& tin):
    mutex_guarded(tin.copy_out())
  {}
  mutex_guarded(mutex_guarded && tin):
    mutex_guarded(tin.move_out())
  {}
  mutex_guarded& operator=(T const& tin) {
    assign( tin );
    return *this;
  }
  mutex_guarded& operator=(T&& tin) {
    assign( std::move(tin) );
    return *this;
  }
  mutex_guarded& operator=(mutex_guarded const& tin) {
    return *this = tin.copy_out();
  }
  mutex_guarded& operator=(mutex_guarded&& tin) {
    return *this = tin.move_out();
  }
private:
  std::mutex m_mtx;
  T t;
};

with some bonus augmentation for copy/move/construct.

Now a mutex_guarded<Foo> foo can be interacted with by doing

foo->*[&](auto& foo){ foo.closeUnusedConnections(); };

and the locking happens in the mutex_guarded, not within Foo itself.  Foo lives without any thread safety itself, and its own calls don't cause problems.

This is still dangerous.  Mutexes are in general dangerous, and the less tightly you control them the more dangerous they are.


问:
How to count total lines changed by a specific author in a Git repository?
Is there a command I can invoke which will count the lines changed by a specific author in a Git repository? I know that there must be ways to count the number of commits as Github does this for their Impact graph.</p>

答:
Here's a short one-liner that produces stats for all authors. It's much faster than Dan's solution above at https://stackoverflow.com/a/20414465/1102119 (mine has time complexity O(N) instead of O(NM) where N is the number of commits, and M the number of authors).</p>

```<code>git log --no-merges --pretty=format:%an --numstat | awk '/./ && !author { author = $0; next } author { ins[author] += $1; del[author] += $2 } /^$/ { author = ""; next } END { for (a in ins) { printf "%10d %10d %10d %s\n", ins[a] - del[a], ins[a], del[a], a } }' | sort -rn
</code>```

Body:
Here's a short one-liner that produces stats for all authors. It's much faster than Dan's solution above at https://stackoverflow.com/a/20414465/1102119 (mine has time complexity O(N) instead of O(NM) where N is the number of commits, and M the number of authors).

git log --no-merges --pretty=format:%an --numstat | awk '/./ && !author { author = $0; next } author { ins[author] += $1; del[author] += $2 } /^$/ { author = ""; next } END { for (a in ins) { printf "%10d %10d %10d %s\n", ins[a] - del[a], ins[a], del[a], a } }' | sort -rn


问:
Background gradient issue
I'm seeing a double background gradient on this page in Google Chrome.... any ideas why?

http://www.starcraft-source.com/member/login/

I need it to be the solid blue color

答:
You have put the gradient on the html element (which BTW is technically not wrong, but unusual), but the html doesn't fill the whole view port.

Try adding

```<code>html {
  height: 100%;
}
</code>```

Title: Background gradient issue

Body:
You have put the gradient on the html element (which BTW is technically not wrong, but unusual), but the html doesn't fill the whole view port.

Try adding

html {
  height: 100%;
}