问:
Creating new array from looping another array
I need to tidy up an array. And gather all similar information together.

This is going to be a huge order that I'm bringing to the table, however, it's well beyond my skill set and I've been trying to fix it for 3 days.

The message comes from a webservice, which i have absolutely no control over the output/response.

I need to be able to put all the info
But the following (i know its big sorry) is the SOAP object reply: (this has been reduced as well) eek.

```<code>                [0] => RoomInformation Object
                    (
                       [Details] => DetailsType Object
                            (
                                [Total] => TotalType Object
                                    (
                                        [AmountAfterTax] => 1.00
                                    )
                                [EffectiveDate] => 2011-08-12
                                [AvailabilityStatus] => AvailableForSale
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1860
                                        [RoomNo] => THAH01
                                        [Description] => Hotel Alpha
                                    )
                            )
                    )

                [1] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (

                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1861
                                        [RoomNo] => THAH02
                                        [Description] => Hotel Alpha
                                    )
                           )
                    )
                [2] => RoomInformation Object
                    (

                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1226
                                        [RoomNo] => DENM01
                                        [Description] => Hotel Beta
                                    )
                            )

                    )

                [3] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                                [MoreRatesExistInd] =>
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1227
                                        [RoomNo] => DENM02
                                        [Description] => Hotel Beta
                                    )
                            )
                    )

                [4] => RoomInformation Object
                    (
                       [Details] => DetailsType Object
                            (
                                [Total] => TotalType Object
                                    (
                                        [AmountAfterTax] => 1.00
                                    )
                                [EffectiveDate] => 2011-08-13
                                [AvailabilityStatus] => AvailableForSale
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1860
                                        [RoomNo] => THAH01
                                        [Description] => Hotel Alpha
                                    )
                            )
                    )

                [5] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (

                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1861
                                        [RoomNo] => THAH02
                                        [Description] => Hotel Alpha
                                    )
                           )
                    )
                                        [2] => RoomInformation Object
                    (

                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1226
                                        [RoomNo] => DENM01
                                        [Description] => Hotel Beta
                                    )
                            )

                    )

                [3] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                                [MoreRatesExistInd] =>
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1227
                                        [RoomNo] => DENM02
                                        [Description] => Hotel Beta
                                    )
                            )
                    )
</code>```

TL;DR

Each hotel has 2 rooms with ids. Each of these 2 id's are seperated by dates, but are in the different parts of the array :(

```<code>[Hotel A]
 HotelA RoomId = 01
 Date = 12-08-2011
[Hotel A]
 HotelA RoomId = 02
 Date = 12-08-2011
[Hotel B]
 HotelB RoomId = 01
 Date = 12-08-2011
[Hotel B]
 HotelB RoomId = 02
 Date = 12-08-2011
[Hotel A]
 HotelA RoomId = 01
 Date = 13-08-2011
[Hotel A]
 HotelA RoomId = 02
 Date = 13-08-2011
[Hotel B]
 HotelB RoomId = 01
 Date = 13-08-2011
[Hotel B]
 HotelB RoomId = 02
 Date = 13-08-2011
</code>```

I want to be able to put them into an array as such:

```<code>[Hotel A]
 HotelA RoomId = 01
 Date 12-08-2011
 Date 13-08-2011
 HotelA RoomId = 02
 Date 12-08-2011
 Date 13-08-2011
</code>```

etc

Please help. I've been pulling my hair out :(

Here is an example of what ive tried:

```<code>$hotelinfo = array();
$k=0;
for($i = 0; $i < count($result->RoomInformation); $i++)
{
    $flag = false;
    $HotelObj    = $result->RoomInformation[$i];
    $HotelName   = $result->RoomInformation[$i]->RoomInformationExtend->RoomDetails->Description;
    $HotelId     = $result->RoomStays->RoomStay[$i]->RoomInformation->RoomDetails->RoomId;
    //$hotelinfo[$i][$HotelName] = array();
    $hotelinfo[count($hotelinfo)] = array();
    $hotelinfo[count($hotelinfo)][$HotelName] = array();
    for($c = 0; $c < count($result->RoomInformation); $c++)
    {
        $thishotelObj = $result->RRoomInformation[$c];
        $thisHotelName = $thishotelObj->RoomInformationExtend->RoomDetails->Description;
        $thisHotelId = $thishotelObj->TPA_Extensions->RoomDetails->RoomId;
        if($thisHotelName == $HotelName & $thisHotelId == $HotelId){
            $hotelinfo[$i][$HotelName][$c] = $HotelName;
            $hotelinfo[$i][$HotelName][$c] = $thisHotelName;
            $i++;
        }
    }
}
</code>```

was i even going in thr correct direction with this?

答:
I suppose such a foreach loop would be sufficient. PHP doesn't check the existence of array members on updating, so it would just add the needed keys.</p>

```<code>$HotelRooms = array();
$foreach($result as $r)
{
  $HotelName = $r->RoomInformationExtend->RoomDetails->Description;
  $HotelRooms[$HotelName][$r->RoomInformationExtend->RoomDetails->RoomId][] = $r->Details->EffectiveDate
}
</code>```

Body:
I need to tidy up an array. And gather all similar information together.

This is going to be a huge order that I'm bringing to the table, however, it's well beyond my skill set and I've been trying to fix it for 3 days.

The message comes from a webservice, which i have absolutely no control over the output/response.

I need to be able to put all the info
But the following (i know its big sorry) is the SOAP object reply: (this has been reduced as well) eek.

                [0] => RoomInformation Object
                    (
                       [Details] => DetailsType Object
                            (
                                [Total] => TotalType Object
                                    (
                                        [AmountAfterTax] => 1.00
                                    )
                                [EffectiveDate] => 2011-08-12
                                [AvailabilityStatus] => AvailableForSale
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1860
                                        [RoomNo] => THAH01
                                        [Description] => Hotel Alpha
                                    )
                            )
                    )

                [1] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (

                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1861
                                        [RoomNo] => THAH02
                                        [Description] => Hotel Alpha
                                    )
                           )
                    )
                [2] => RoomInformation Object
                    (

                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1226
                                        [RoomNo] => DENM01
                                        [Description] => Hotel Beta
                                    )
                            )

                    )

                [3] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                                [MoreRatesExistInd] =>
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1227
                                        [RoomNo] => DENM02
                                        [Description] => Hotel Beta
                                    )
                            )
                    )

                [4] => RoomInformation Object
                    (
                       [Details] => DetailsType Object
                            (
                                [Total] => TotalType Object
                                    (
                                        [AmountAfterTax] => 1.00
                                    )
                                [EffectiveDate] => 2011-08-13
                                [AvailabilityStatus] => AvailableForSale
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1860
                                        [RoomNo] => THAH01
                                        [Description] => Hotel Alpha
                                    )
                            )
                    )

                [5] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (

                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1861
                                        [RoomNo] => THAH02
                                        [Description] => Hotel Alpha
                                    )
                           )
                    )
                                        [2] => RoomInformation Object
                    (

                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1226
                                        [RoomNo] => DENM01
                                        [Description] => Hotel Beta
                                    )
                            )

                    )

                [3] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                                [MoreRatesExistInd] =>
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1227
                                        [RoomNo] => DENM02
                                        [Description] => Hotel Beta
                                    )
                            )
                    )

TL;DR

Each hotel has 2 rooms with ids. Each of these 2 id's are seperated by dates, but are in the different parts of the array :(

[Hotel A]
 HotelA RoomId = 01
 Date = 12-08-2011
[Hotel A]
 HotelA RoomId = 02
 Date = 12-08-2011
[Hotel B]
 HotelB RoomId = 01
 Date = 12-08-2011
[Hotel B]
 HotelB RoomId = 02
 Date = 12-08-2011
[Hotel A]
 HotelA RoomId = 01
 Date = 13-08-2011
[Hotel A]
 HotelA RoomId = 02
 Date = 13-08-2011
[Hotel B]
 HotelB RoomId = 01
 Date = 13-08-2011
[Hotel B]
 HotelB RoomId = 02
 Date = 13-08-2011

I want to be able to put them into an array as such:

[Hotel A]
 HotelA RoomId = 01
 Date 12-08-2011
 Date 13-08-2011
 HotelA RoomId = 02
 Date 12-08-2011
 Date 13-08-2011

etc

Please help. I've been pulling my hair out :(

Here is an example of what ive tried:

$hotelinfo = array();
$k=0;
for($i = 0; $i < count($result->RoomInformation); $i++)
{
    $flag = false;
    $HotelObj    = $result->RoomInformation[$i];
    $HotelName   = $result->RoomInformation[$i]->RoomInformationExtend->RoomDetails->Description;
    $HotelId     = $result->RoomStays->RoomStay[$i]->RoomInformation->RoomDetails->RoomId;
    //$hotelinfo[$i][$HotelName] = array();
    $hotelinfo[count($hotelinfo)] = array();
    $hotelinfo[count($hotelinfo)][$HotelName] = array();
    for($c = 0; $c < count($result->RoomInformation); $c++)
    {
        $thishotelObj = $result->RRoomInformation[$c];
        $thisHotelName = $thishotelObj->RoomInformationExtend->RoomDetails->Description;
        $thisHotelId = $thishotelObj->TPA_Extensions->RoomDetails->RoomId;
        if($thisHotelName == $HotelName & $thisHotelId == $HotelId){
            $hotelinfo[$i][$HotelName][$c] = $HotelName;
            $hotelinfo[$i][$HotelName][$c] = $thisHotelName;
            $i++;
        }
    }
}

was i even going in thr correct direction with this?

Body:
I suppose such a foreach loop would be sufficient. PHP doesn't check the existence of array members on updating, so it would just add the needed keys.

$HotelRooms = array();
$foreach($result as $r)
{
  $HotelName = $r->RoomInformationExtend->RoomDetails->Description;
  $HotelRooms[$HotelName][$r->RoomInformationExtend->RoomDetails->RoomId][] = $r->Details->EffectiveDate
}


来源: stackexchange

问:
Model Form drop-down (select) field not displaying correct rows to choose from
I have a Parent Model that uses a Foreign Key that points to a Child Model. In this case, the "Child Model" is called Mstrgensalutationtype (which is really Salutations).

The Parent Model is being used to create a Model Form

Basically, below is what I get when trying to choose a Salutation Type.

What I need to see is

```<code>Mr.
Ms.
Mrs.
Prof.
Dr.
</code>```

Question: What am I doing wrong here?

TIA

models.py - used as a Child Model

```<code>class Mstrgensalutationtype(models.Model):
    saltypeid = models.BigIntegerField(primary_key=True)
    lang = models.CharField(max_length=2, blank=True, null=True)
    shortval = models.CharField(max_length=7, blank=True, null=True)
    salutationlong = models.CharField(max_length=20, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'MstrGenSalutationType'

        def __unicode__(self):
            return u'%s ' % ( self.shortval )
</code>```

models.py - used as a Parent Model

```<code>class Mstrstorehead(models.Model):
    tenantid = models.BigIntegerField(primary_key=True)
    extrefacctno = models.CharField(max_length=20, blank=True, null=True, verbose_name="Account Reference No")

[... snip ...]

    contactsalutationid = models.ForeignKey(Mstrgensalutationtype,  models.DO_NOTHING, db_column='contactsalutationid', blank=True, null=True, verbose_name="Salutation")

[... snip ...]

    class Meta:
        managed = False
        db_table = 'MstrStoreHead'
</code>```

Update

I made the following change below - but still getting the same problem.

```<code>class Mstrgensalutationtype(models.Model):
    saltypeid = models.BigIntegerField(primary_key=True)
    lang = models.CharField(max_length=2, blank=True, null=True)
    shortval = models.CharField(max_length=7, blank=True, null=True)
    salutationlong = models.CharField(max_length=20, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'MstrGenSalutationType'

    def __unicode__(self):
        return u'%s ' % ( self.shortval )
</code>```

答:
The __unicode__ method is only valid in Python 2 - it doesn't do anything in Python 3. You need to use __str__ instead:

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

Note also that the u string prefix is redundant in Python 3. All strings are unicode by default.

If you need to support both Python 2 and 3 then use python_2_unicode_compatible as described in the link above.

ContentLicense: CC BY-SA 3.0

Body:
I have a Parent Model that uses a Foreign Key that points to a Child Model. In this case, the "Child Model" is called Mstrgensalutationtype (which is really Salutations).

The Parent Model is being used to create a Model Form

Basically, below is what I get when trying to choose a Salutation Type.

What I need to see is

Mr.
Ms.
Mrs.
Prof.
Dr.

Question: What am I doing wrong here?

TIA

models.py - used as a Child Model

class Mstrgensalutationtype(models.Model):
    saltypeid = models.BigIntegerField(primary_key=True)
    lang = models.CharField(max_length=2, blank=True, null=True)
    shortval = models.CharField(max_length=7, blank=True, null=True)
    salutationlong = models.CharField(max_length=20, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'MstrGenSalutationType'

        def __unicode__(self):
            return u'%s ' % ( self.shortval )

models.py - used as a Parent Model

class Mstrstorehead(models.Model):
    tenantid = models.BigIntegerField(primary_key=True)
    extrefacctno = models.CharField(max_length=20, blank=True, null=True, verbose_name="Account Reference No")

[... snip ...]

    contactsalutationid = models.ForeignKey(Mstrgensalutationtype,  models.DO_NOTHING, db_column='contactsalutationid', blank=True, null=True, verbose_name="Salutation")

[... snip ...]

    class Meta:
        managed = False
        db_table = 'MstrStoreHead'

Update

I made the following change below - but still getting the same problem.

class Mstrgensalutationtype(models.Model):
    saltypeid = models.BigIntegerField(primary_key=True)
    lang = models.CharField(max_length=2, blank=True, null=True)
    shortval = models.CharField(max_length=7, blank=True, null=True)
    salutationlong = models.CharField(max_length=20, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'MstrGenSalutationType'

    def __unicode__(self):
        return u'%s ' % ( self.shortval )

Body:
The __unicode__ method is only valid in Python 2 - it doesn't do anything in Python 3. You need to use __str__ instead:

def __str__(self):
    return self.shortval

Note also that the u string prefix is redundant in Python 3. All strings are unicode by default.

If you need to support both Python 2 and 3 then use python_2_unicode_compatible as described in the link above.


问:
What is involved in using Scala.js for non-web, non-Node.js applications?
I've used Scala.js, and enjoyed it, for writing web page functionality.

I wrote some graphics-related functions that draw pictures on the Canvas, for instance. I'm interested in porting some of that code to Adobe Illustrator and Photoshop. They offer scripting in three languages: (1) AppleScript, (2) JavaScript, and (3) Visual Basic. Of course the API is quite different than the Canvas and will offer many specific, powerful functions that I would like to take advantage of.

My program will be rewritten and expanded considerably, so development will continue. What I wonder is whether I can continue to develop in Scala and if Scala.js can be used to write code for Adobe software, or really any software that scripts with JavaScript.

I figure that I have to create some kind of interface to the Adobe API. What would that involve? Would that code be written in Scala? Would it be a plugin to sbt? How much would I have to learn about the internals of the Scala compiler?

Is it worth doing this, or should I choose instead to develop in JavaScript? (I don't really want to write in JavaScript directly because I've had bad experiences with it in the browser, but I can't say I'm an expert in it.)

(Note that I'm not familiar with much of the Adobe API yet... I'm just investigating now.)

答:
Should be pretty straightforward. The key is that you'll need to build facades -- strongly-typed Scala descriptions -- for the APIs you care about in Illustrator and Photoshop. This isn't particularly hard: you only have to worry about the functions you actually want to call, and you describe the function signatures in Scala. With a little practice, this becomes pretty easy -- it typically takes a minute or less per function once you have the hang of it. (I maintain the jQuery facade, which is one of the larger ones, and banged out most of it in an afternoon once I was in practice.)

Assuming that they are using reasonable standard JavaScript, that's probably most of it -- you define those facades, write Scala.js code to use them, and plug the compiled JavaScript into the tools...


问:
Display selected folder path in Shiny
I want my Shiny app to allow user specify a path to a folder (locally) and display the selected path. The following code works but I can't figure out how to hide "character(0)" in verbatimTextOutput until the folder was selected. I tried conditional panel (see commented out in my code) but can't figure out what to use as a condition here (because shinyDirButton is not a standard action button...). Thank you!

```<code>library(shiny)
library(shinyFiles)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  mainPanel(
    shinyDirButton("dir", "Input directory", "Upload"),
    #conditionalPanel(
      #condition = "???",
      verbatimTextOutput('dir')
    #)
  )
)

server <- function(input, output) {

  shinyDirChoose(input, 'dir', roots = c(home = '~'), filetypes = c('', 'txt','bigWig',"tsv","csv","bw"))

  dir <- reactive(input$dir)
  output$dir <- renderPrint({parseDirPath(c(home = '~'), dir())})

  observeEvent(
    ignoreNULL = TRUE,
    eventExpr = {
      input$dir
    },
    handlerExpr = {
      home <- normalizePath("~")
      datapath <<- file.path(home, paste(unlist(dir()$path[-1]), collapse = .Platform$file.sep))
    }
  )
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

The closest question I was able to find is this but it doesn't solve my problem: R conditionalPanel reacts to output

答:
In the server function, use renderText instead of renderPrint:

```<code>library(shiny)
library(shinyFiles)

# Define UI for application that draws a histogram
ui <- fluidPage( # Application title
  mainPanel(
    shinyDirButton("dir", "Input directory", "Upload"),
    verbatimTextOutput("dir", placeholder = TRUE)  # added a placeholder
  ))

server <- function(input, output) {
  shinyDirChoose(
    input,
    'dir',
    roots = c(home = '~'),
    filetypes = c('', 'txt', 'bigWig', "tsv", "csv", "bw")
  )

  dir <- reactive(input$dir)
  output$dir <- renderText({  # use renderText instead of renderPrint
    parseDirPath(c(home = '~'), dir())
  })

  observeEvent(ignoreNULL = TRUE,
               eventExpr = {
                 input$dir
               },
               handlerExpr = {
                 home <- normalizePath("~")
                 datapath <<-
                   file.path(home, paste(unlist(dir()$path[-1]), collapse = .Platform$file.sep))
               })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Title: Display selected folder path in Shiny

Body:
I want my Shiny app to allow user specify a path to a folder (locally) and display the selected path. The following code works but I can't figure out how to hide "character(0)" in verbatimTextOutput until the folder was selected. I tried conditional panel (see commented out in my code) but can't figure out what to use as a condition here (because shinyDirButton is not a standard action button...). Thank you!

library(shiny)
library(shinyFiles)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  mainPanel(
    shinyDirButton("dir", "Input directory", "Upload"),
    #conditionalPanel(
      #condition = "???",
      verbatimTextOutput('dir')
    #)
  )
)

server <- function(input, output) {

  shinyDirChoose(input, 'dir', roots = c(home = '~'), filetypes = c('', 'txt','bigWig',"tsv","csv","bw"))

  dir <- reactive(input$dir)
  output$dir <- renderPrint({parseDirPath(c(home = '~'), dir())})

  observeEvent(
    ignoreNULL = TRUE,
    eventExpr = {
      input$dir
    },
    handlerExpr = {
      home <- normalizePath("~")
      datapath <<- file.path(home, paste(unlist(dir()$path[-1]), collapse = .Platform$file.sep))
    }
  )
}

# Run the application
shinyApp(ui = ui, server = server)

The closest question I was able to find is this but it doesn't solve my problem: R conditionalPanel reacts to output

Body:
In the server function, use renderText instead of renderPrint:

library(shiny)
library(shinyFiles)

# Define UI for application that draws a histogram
ui <- fluidPage( # Application title
  mainPanel(
    shinyDirButton("dir", "Input directory", "Upload"),
    verbatimTextOutput("dir", placeholder = TRUE)  # added a placeholder
  ))

server <- function(input, output) {
  shinyDirChoose(
    input,
    'dir',
    roots = c(home = '~'),
    filetypes = c('', 'txt', 'bigWig', "tsv", "csv", "bw")
  )

  dir <- reactive(input$dir)
  output$dir <- renderText({  # use renderText instead of renderPrint
    parseDirPath(c(home = '~'), dir())
  })

  observeEvent(ignoreNULL = TRUE,
               eventExpr = {
                 input$dir
               },
               handlerExpr = {
                 home <- normalizePath("~")
                 datapath <<-
                   file.path(home, paste(unlist(dir()$path[-1]), collapse = .Platform$file.sep))
               })
}

# Run the application
shinyApp(ui = ui, server = server)


问:
Custom a touchable text like See more
I am writing a react native app.
I want to make a press. See more like we usually see for more information of something. How can I do that?

Like here

答:
Text components have an onPress prop, where you can pass an arrow function

```<code><Text onPress = {() => this.myFunction()}>
    See More
</Text>
</code>```

Note: Adding some style props, eg color: 'blue' and fontWeight: 600 can help your text look pretty similar to your provided photo.

Title: Custom a touchable text like See more

Body:
Text components have an onPress prop, where you can pass an arrow function

<Text onPress = {() => this.myFunction()}>
    See More
</Text>

Note: Adding some style props, eg color: 'blue' and fontWeight: 600 can help your text look pretty similar to your provided photo.


问:
Only show alert on blur and if no selection from dropdown was made
I use Google Maps Places to autocomplete my input. I am trying to somewhat force the user to select an address from the populated drowdowns, because I want to work with that selected place.

The issue I have though, is that I want to enable the user to enter an address that might not be populated by Google, so on blur I would like to show an alert asking the user if the address is correct.

The issue here is that even when I select from the dropdown, it will show the alert, because the input will blur out.

How can I make sure that the alert is only shown if no place from Google was selected and if it blurs?

```<code><template>
    <input
           type="text"
           name="address"
           @blur="onBlur()"
    />
</template>

<script>
//...
mounted: function() {
    this.autocomplete = new google.maps.places.Autocomplete(
        document.getElementById(this.id),
        this.options
    );

    this.autocomplete.addListener('place_changed', (blur) => {
        console.log('place changed ');
        let place = this.autocomplete.getPlace();
        this.setAddress(place);
    });
},

methods: {
    onBlur() {
        this.isThisYourAddress();
    },

    isThisYourAddress() {
        return swal('test');
    }
}
</script>
</code>```

答:
The basic idea is: use $refs to save the input value each time it is set. On blur, check whether the value has changed from the last one saved. The trick is to ensure that the place-change operation saves the new value before the on-blur tests it. I put in a little time delay for that. You could probably put in a better gatekeeper.

```<code>new Vue({
  el: '#app',
  data: {
    lastSelected: ''
  },
  mounted() {
    this.autocomplete = new google.maps.places.Autocomplete(
        document.getElementById('auto'),
        this.options
    );

    this.autocomplete.addListener('place_changed', (blur) => {
        var  place = this.autocomplete.getPlace();
        this.lastSelected = this.$refs.input.value;
        console.log('place changed ', this.lastSelected);
        this.setAddress(place);
    });
  },
  methods: {
      onBlur() {
        setTimeout(() => {
          const v = this.$refs.input.value;
          if (v !== this.lastSelected) {
            this.lastSelected = v;
            this.isThisYourAddress();
          }
        }, 100);
      },

      isThisYourAddress() {
        return 'something'
      }
  }
})
</code>```

https://codepen.io/anon/pen/WXVRaY?editors=1111

Body:
I use Google Maps Places to autocomplete my input. I am trying to somewhat force the user to select an address from the populated drowdowns, because I want to work with that selected place.

The issue I have though, is that I want to enable the user to enter an address that might not be populated by Google, so on blur I would like to show an alert asking the user if the address is correct.

The issue here is that even when I select from the dropdown, it will show the alert, because the input will blur out.

How can I make sure that the alert is only shown if no place from Google was selected and if it blurs?

<template>
    <input
           type="text"
           name="address"
           @blur="onBlur()"
    />
</template>

Body:
The basic idea is: use $refs to save the input value each time it is set. On blur, check whether the value has changed from the last one saved. The trick is to ensure that the place-change operation saves the new value before the on-blur tests it. I put in a little time delay for that. You could probably put in a better gatekeeper.

new Vue({
  el: '#app',
  data: {
    lastSelected: ''
  },
  mounted() {
    this.autocomplete = new google.maps.places.Autocomplete(
        document.getElementById('auto'),
        this.options
    );

    this.autocomplete.addListener('place_changed', (blur) => {
        var  place = this.autocomplete.getPlace();
        this.lastSelected = this.$refs.input.value;
        console.log('place changed ', this.lastSelected);
        this.setAddress(place);
    });
  },
  methods: {
      onBlur() {
        setTimeout(() => {
          const v = this.$refs.input.value;
          if (v !== this.lastSelected) {
            this.lastSelected = v;
            this.isThisYourAddress();
          }
        }, 100);
      },

      isThisYourAddress() {
        return 'something'
      }
  }
})

https://codepen.io/anon/pen/WXVRaY?editors=1111


问:
UIScrollView scrollRectToVisible isn't doing anything
I'm not really sure why this isn't working, hopefully you can help me find the missing piece. I have a UIScrollView with paging enabled. I'm using it for side-scrolling through a tutorial. I have a button that when tapped should scroll the user back to the beginning of the tutorial. I originally tried using the scroll view's frame as the rect to scroll to because that CGRect should represent the first page. I've tried a couple of different CGRects to no avail though.

```<code>- (IBAction) touchedButtonReturnToBeginning:(id)sender {
    // I've tried several CGRect's, none of which cause the UIScrollView to move.
    // CGRect beginning = self.containerScrollView.frame
    // CGRect beginning = self.containerScrollView.bounds;
    CGRect beginning = CGRectMake(0, 44, 1, 1);
    [self.containerScrollView scrollRectToVisible:beginning animated:YES];
}
</code>```

I have verified that self.containerScrollView is hooked up in my xib as well as the touchedButtonReturnToBeginning action is connected to my button. I've used my debugger to step through this method, so I have verified that it is getting called. All of the variables are appropriately set, but when I call scrollRectToVisible the scroll view just doesn't do anything.

Any ideas?

答: I don't know why that wouldn't work, but have you tried [self.containerScrollView setContentOffset:CGPointZero animated:YES]?

Body:
I'm not really sure why this isn't working, hopefully you can help me find the missing piece. I have a UIScrollView with paging enabled. I'm using it for side-scrolling through a tutorial. I have a button that when tapped should scroll the user back to the beginning of the tutorial. I originally tried using the scroll view's frame as the rect to scroll to because that CGRect should represent the first page. I've tried a couple of different CGRects to no avail though.

- (IBAction) touchedButtonReturnToBeginning:(id)sender {
    // I've tried several CGRect's, none of which cause the UIScrollView to move.
    // CGRect beginning = self.containerScrollView.frame
    // CGRect beginning = self.containerScrollView.bounds;
    CGRect beginning = CGRectMake(0, 44, 1, 1);
    [self.containerScrollView scrollRectToVisible:beginning animated:YES];
}

I have verified that self.containerScrollView is hooked up in my xib as well as the touchedButtonReturnToBeginning action is connected to my button. I've used my debugger to step through this method, so I have verified that it is getting called. All of the variables are appropriately set, but when I call scrollRectToVisible the scroll view just doesn't do anything.

Any ideas?

ContentLicense: CC BY-SA 2.5


问:
If DeviceCheck is device specific not app specific, so it's possible for another app to mess with the 4 bits?
If DeviceCheck is device specific and not app specific, is it possible for another app to mess with the 4 bits and hence mess up your app in the process?</p>

答: The bits are common between apps by a single developer on a device. Your app will not share bits with the Facebook app, for example, but if you produce multiple apps under the same team, they'll share.</p>


问:
selective `for` loop for an R function: `for` loop Or `Vectorize`
I have a small R function called ab. I'm trying to allow user of the function to provide a vector for either argument m or s (not both).

Question:
I'm wondering how should I set up my for loop so that I can selectively loop either over m or s based on user's choice? [is it better to use Vectorize here?]

Here is my R code with no success:

```<code>ab = function(m, s, lo = -Inf, hi = Inf){

loop = if(length(m) > 1) length(m) else length(s)

for(i in 1:loop){

p = function(x) dnorm(x, m[i], s[i])  # [i] should be either for `m` or `s` but what can I do here to have [i] be selectively chosen?
f = function(x) p(x)/integrate(p, lo, hi)[[1]]
curve(f, -3, 3, add = i!= 1, col = i)
    }
}
# Example of use:
ab(m = c(0, .5), s = 1) # Error in integrate(p, lo, hi) : non-finite function value
</code>```

答:
I highly appreciate the answer by our colleague @r2evans, but I think this problem might have a bit simpler solution (i.e., one line of if syntax):

```<code>ab = function(m, s, lo = -Inf, hi = Inf){

loop = if(length(m) > 1) length(m) else length(s)

p = if(length(m) > 1) function(x) dnorm(x, m[i], s) else function(x) dnorm(x, m, s[i])

for(i in 1:loop){
f = function(x) p(x)/integrate(p, lo, hi)[[1]]
curve(f, -3, 3, add = i!= 1, col = i)
 }
}
# Example of use:
ab(m = c(0, 1), 1)
#Example of use:
ab(m = 0, c(1, 2))
</code>```

Body:
I have a small R function called ab. I'm trying to allow user of the function to provide a vector for either argument m or s (not both).

Question:
I'm wondering how should I set up my for loop so that I can selectively loop either over m or s based on user's choice? [is it better to use Vectorize here?]

Here is my R code with no success:

ab = function(m, s, lo = -Inf, hi = Inf){

loop = if(length(m) > 1) length(m) else length(s)

for(i in 1:loop){

p = function(x) dnorm(x, m[i], s[i])  # [i] should be either for `m` or `s` but what can I do here to have [i] be selectively chosen?
f = function(x) p(x)/integrate(p, lo, hi)[[1]]
curve(f, -3, 3, add = i!= 1, col = i)
    }
}
# Example of use:
ab(m = c(0, .5), s = 1) # Error in integrate(p, lo, hi) : non-finite function value

Body:
I highly appreciate the answer by our colleague @r2evans, but I think this problem might have a bit simpler solution (i.e., one line of if syntax):

ab = function(m, s, lo = -Inf, hi = Inf){

loop = if(length(m) > 1) length(m) else length(s)

p = if(length(m) > 1) function(x) dnorm(x, m[i], s) else function(x) dnorm(x, m, s[i])

for(i in 1:loop){
f = function(x) p(x)/integrate(p, lo, hi)[[1]]
curve(f, -3, 3, add = i!= 1, col = i)
 }
}
# Example of use:
ab(m = c(0, 1), 1)
#Example of use:
ab(m = 0, c(1, 2))


问:
How to make WPF ComboBox default selection to blank
I have an enum like:

```<code>enum Gender
{
   Male = 1,
   Female = 2
}
</code>```

Then I have a Combobox binding to a list of Gender.

```<code><ComboBox ItemSource = 'Binding GenderList, Mode=TwoWay,
                        UpdateSourceTrigger=PropertyChanged'
          SelectItem = 'Binding SelectedGender' />
</code>```

When user opens the view, how can I make ComboBox selection default to blank? Then after user made a selection, the blank selection is removed from the ComboBox source.

Thanks

Thanks all the replies. I fixed my problem by manully assigning the selected item to null.

答:
What you are describing is the default behavior of the ComboBox.  You don't need to do anything (except for correct the typos in your XAML.  It should look like:</p>

```<code><ComboBox ItemsSource="{Binding GenderList}" SelectedItem="{Binding Path=SelectedGender}" ></ComboBox>
</code>```

Body:
I have an enum like:

enum Gender
{
   Male = 1,
   Female = 2
}

Then I have a Combobox binding to a list of Gender.

<ComboBox ItemSource = 'Binding GenderList, Mode=TwoWay,
                        UpdateSourceTrigger=PropertyChanged'
          SelectItem = 'Binding SelectedGender' />

When user opens the view, how can I make ComboBox selection default to blank? Then after user made a selection, the blank selection is removed from the ComboBox source.

Thanks

Thanks all the replies. I fixed my problem by manully assigning the selected item to null.

Body:
What you are describing is the default behavior of the ComboBox.  You don't need to do anything (except for correct the typos in your XAML.  It should look like:

<ComboBox ItemsSource="{Binding GenderList}" SelectedItem="{Binding Path=SelectedGender}" ></ComboBox>


问:
Got some issues in Java
I'm still new in Java and I have a problem here. I'm currently learning how to use methods with parameters. Here's the code:

```<code>import java.util.Scanner;
class TEST2 {
    public static void main(String [] args){
        Scanner input = new Scanner(System.in);
        tuna tunaObject = new tuna ();
        System.out.println("Enter your name here: ");
        String name = input.nextLine();
        tunaObject.simpleMessage(name);
    }
}
</code>```

And another one :

```<code>public class tuna {
    public void simpleMessage(String name){
    System.out.println("Hello" + name);
    }
}
</code>```

*The problem is, the result is turned out like this:

Enter your name here:

Eddy

HelloEddy

"HelloEddy" supposed to be "Hello Eddy"
*Why there's no space? What is the mistake I made in this code, can anyone help? Thank you.

答:
You need to put a space at the end of the "Hello" string, so the line would look like

```<code>System.out.println("Hello " + name);
</code>```

Take note of the space.

Title: Got some issues in Java

Body:
I'm still new in Java and I have a problem here. I'm currently learning how to use methods with parameters. Here's the code:

import java.util.Scanner;
class TEST2 {
    public static void main(String [] args){
        Scanner input = new Scanner(System.in);
        tuna tunaObject = new tuna ();
        System.out.println("Enter your name here: ");
        String name = input.nextLine();
        tunaObject.simpleMessage(name);
    }
}

And another one :

public class tuna {
    public void simpleMessage(String name){
    System.out.println("Hello" + name);
    }
}

*The problem is, the result is turned out like this:

Enter your name here:

Eddy

HelloEddy

"HelloEddy" supposed to be "Hello Eddy"
*Why there's no space? What is the mistake I made in this code, can anyone help? Thank you.

Body:
You need to put a space at the end of the "Hello" string, so the line would look like

System.out.println("Hello " + name);

Take note of the space.


问:
Wordpress4.9.1 SMTP not working
I am using the WP mail SMTP (0.11.2) plugin.

usingWordpress4.9.1
When I sent my email  it gives me this error SMTP -> ERROR: Failed to connect to server or Could not authenticate.

How can I fix it?

C:\wamp64\www\wordpress\wp-content\plugins\wp-mail-smtp\wp_mail_smtp.php:258:boolean false

Here is my testmail debuging info:

```<code>PHPMailer Object
(
[Version] => 5.2.22
[Priority] =>
[CharSet] => UTF-8
[ContentType] => text/plain
[Encoding] => 8bit
[ErrorInfo] => SMTP connect() failed.
https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
[From] => xxxxxxxxxx@gmail.com
[FromName] => 搖滾俱樂部
[Sender] =>
[ReturnPath] =>
[Subject] => WP Mail SMTP: Test mail to bb5566123com@yahoo.com.tw
[Body] => 這封測試郵件由 WordPress 外掛 WP Mail SMTP 自動產生。
[AltBody] =>
[Ical] =>
[MIMEBody:protected] => 這封測試郵件由 WordPress 外掛 WP Mail SMTP 自動產生。

[MIMEHeader:protected] => Date: Fri, 8 Dec 2017 14:51:09 +0000
To: xxxxxxxxx@yahoo.com.tw
From: =?UTF-8?B?5pCW5ru+5L+x5qiC6YOo?=
Subject: WP Mail SMTP: Test mail to bb5566123com@yahoo.com.tw
Message-ID: <1d6e4a91953547c850de852e798ccbba@club3.idv.tw>
X-Mailer: PHPMailer 5.2.22 (https://github.com/PHPMailer/PHPMailer)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

[mailHeader:protected] =>
[WordWrap] => 0
[Mailer] => smtp
[Sendmail] => /usr/sbin/sendmail
[UseSendmailOptions] => 1
[PluginDir] =>
[ConfirmReadingTo] =>
[Hostname] =>
[MessageID] =>
[MessageDate] => Fri, 8 Dec 2017 14:51:09 +0000
[Host] => smtp.gmail.com
[Port] => 465
[Helo] =>
[SMTPSecure] => ssl
[SMTPAutoTLS] => 1
[SMTPAuth] => 1
[SMTPOptions] => Array
    (
    )

[Username] => xxxxxxxxxxx@gmail.com
[Password] => xxxxxxxxxxxx
[AuthType] =>
[Realm] =>
[Workstation] =>
[Timeout] => 300
[SMTPDebug] => 0
[Debugoutput] => echo
[SMTPKeepAlive] =>
[SingleTo] =>
[SingleToArray] => Array
    (
    )

[do_verp] =>
[AllowEmpty] =>
[LE] =>

[DKIM_selector] =>
[DKIM_identity] =>
[DKIM_passphrase] =>
[DKIM_domain] =>
[DKIM_private] =>
[DKIM_private_string] =>
[action_function] =>
[XMailer] =>
[smtp:protected] => SMTP Object
    (
        [Version] => 5.2.22
        [SMTP_PORT] => 25
        [CRLF] =>

        [do_debug] => 0
        [Debugoutput] => echo
        [do_verp] =>
        [Timeout] => 300
        [Timelimit] => 300
        [smtp_transaction_id_patterns:protected] => Array
            (
                [exim] => /[0-9]{3} OK id=(.*)/
                [sendmail] => /[0-9]{3} 2.0.0 (.*) Message/
                [postfix] => /[0-9]{3} 2.0.0 Ok: queued as (.*)/
            )

        [smtp_conn:protected] =>
        [error:protected] => Array
            (
                [error] =>
                [detail] =>
                [smtp_code] =>
                [smtp_code_ex] =>
            )

        [helo_rply:protected] =>
        [server_caps:protected] =>
        [last_reply:protected] =>
    )

[to:protected] => Array
    (
        [0] => Array
            (
                [0] => xxxxxxxxxx@yahoo.com.tw
                [1] =>
            )

    )

[cc:protected] => Array
    (
    )

[bcc:protected] => Array
    (
    )

[ReplyTo:protected] => Array
    (
    )

[all_recipients:protected] => Array
    (
        [xxxxxxxxxxx@yahoo.com.tw] => 1
    )

[RecipientsQueue:protected] => Array
    (
    )

[ReplyToQueue:protected] => Array
    (
    )

[attachment:protected] => Array
    (
    )

[CustomHeader:protected] => Array
    (
    )

[lastMessageID:protected] => <1d6e4a91953547c850de852e798ccbba@club3.idv.tw>
[message_type:protected] => plain
[boundary:protected] => Array
    (
        [1] => b1_1d6e4a91953547c850de852e798ccbba
        [2] => b2_1d6e4a91953547c850de852e798ccbba
        [3] => b3_1d6e4a91953547c850de852e798ccbba
    )

[language:protected] => Array
    (
        [authenticate] => SMTP Error: Could not authenticate.
        [connect_host] => SMTP Error: Could not connect to SMTP host.
        [data_not_accepted] => SMTP Error: data not accepted.
        [empty_message] => Message body empty
        [encoding] => Unknown encoding:
        [execute] => Could not execute:
        [file_access] => Could not access file:
        [file_open] => File Error: Could not open file:
        [from_failed] => The following From address failed:
        [instantiate] => Could not instantiate mail function.
        [invalid_address] => Invalid address:
        [mailer_not_supported] =>  mailer is not supported.
        [provide_address] => You must provide at least one recipient email address.
        [recipients_failed] => SMTP Error: The following recipients failed:
        [signing] => Signing Error:
        [smtp_connect_failed] => SMTP connect() failed.
        [smtp_error] => SMTP server error:
        [variable_set] => Cannot set or reset variable:
        [extension_missing] => Extension missing:
    )

[error_count:protected] => 2
[sign_cert_file:protected] =>
[sign_key_file:protected] =>
[sign_extracerts_file:protected] =>
[sign_key_pass:protected] =>
[exceptions:protected] => 1
[uniqueid:protected] => 1d6e4a91953547c850de852e798ccbba
</code>```

)

Heading

答:
Connection: opening to ssl://smtp.gmail.com:465, timeout=300, options=array (
)

Connection: Failed to connect to server.

Error number 2. "Error notice: stream_socket_client():
SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failedConnection: Failed to connect to server.

Error number 2. "Error notice: stream_socket_client(): Failed to enable cryptoConnection: Failed to connect to server.

Error number 2. "Error notice: stream_socket_client(): unable to connect to ssl://smtp.gmail.com:465 (Unknown error)

SMTP ERROR: Failed to connect to server:  (0)SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Title: Wordpress4.9.1 SMTP not working

Body:
I am using the WP mail SMTP (0.11.2) plugin.

usingWordpress4.9.1
When I sent my email  it gives me this error SMTP -> ERROR: Failed to connect to server or Could not authenticate.

How can I fix it?

C:\wamp64\www\wordpress\wp-content\plugins\wp-mail-smtp\wp_mail_smtp.php:258:boolean false

Here is my testmail debuging info:

PHPMailer Object
(
[Version] => 5.2.22
[Priority] =>
[CharSet] => UTF-8
[ContentType] => text/plain
[Encoding] => 8bit
[ErrorInfo] => SMTP connect() failed.
https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
[From] => xxxxxxxxxx@gmail.com
[FromName] => 搖滾俱樂部
[Sender] =>
[ReturnPath] =>
[Subject] => WP Mail SMTP: Test mail to bb5566123com@yahoo.com.tw
[Body] => 這封測試郵件由 WordPress 外掛 WP Mail SMTP 自動產生。
[AltBody] =>
[Ical] =>
[MIMEBody:protected] => 這封測試郵件由 WordPress 外掛 WP Mail SMTP 自動產生。

[MIMEHeader:protected] => Date: Fri, 8 Dec 2017 14:51:09 +0000
To: xxxxxxxxx@yahoo.com.tw
From: =?UTF-8?B?5pCW5ru+5L+x5qiC6YOo?=
Subject: WP Mail SMTP: Test mail to bb5566123com@yahoo.com.tw
Message-ID: <1d6e4a91953547c850de852e798ccbba@club3.idv.tw>
X-Mailer: PHPMailer 5.2.22 (https://github.com/PHPMailer/PHPMailer)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

[mailHeader:protected] =>
[WordWrap] => 0
[Mailer] => smtp
[Sendmail] => /usr/sbin/sendmail
[UseSendmailOptions] => 1
[PluginDir] =>
[ConfirmReadingTo] =>
[Hostname] =>
[MessageID] =>
[MessageDate] => Fri, 8 Dec 2017 14:51:09 +0000
[Host] => smtp.gmail.com
[Port] => 465
[Helo] =>
[SMTPSecure] => ssl
[SMTPAutoTLS] => 1
[SMTPAuth] => 1
[SMTPOptions] => Array
    (
    )

[Username] => xxxxxxxxxxx@gmail.com
[Password] => xxxxxxxxxxxx
[AuthType] =>
[Realm] =>
[Workstation] =>
[Timeout] => 300
[SMTPDebug] => 0
[Debugoutput] => echo
[SMTPKeepAlive] =>
[SingleTo] =>
[SingleToArray] => Array
    (
    )

[do_verp] =>
[AllowEmpty] =>
[LE] =>

[DKIM_selector] =>
[DKIM_identity] =>
[DKIM_passphrase] =>
[DKIM_domain] =>
[DKIM_private] =>
[DKIM_private_string] =>
[action_function] =>
[XMailer] =>
[smtp:protected] => SMTP Object
    (
        [Version] => 5.2.22
        [SMTP_PORT] => 25
        [CRLF] =>

        [do_debug] => 0
        [Debugoutput] => echo
        [do_verp] =>
        [Timeout] => 300
        [Timelimit] => 300
        [smtp_transaction_id_patterns:protected] => Array
            (
                [exim] => /[0-9]{3} OK id=(.*)/
                [sendmail] => /[0-9]{3} 2.0.0 (.*) Message/
                [postfix] => /[0-9]{3} 2.0.0 Ok: queued as (.*)/
            )

        [smtp_conn:protected] =>
        [error:protected] => Array
            (
                [error] =>
                [detail] =>
                [smtp_code] =>
                [smtp_code_ex] =>
            )

        [helo_rply:protected] =>
        [server_caps:protected] =>
        [last_reply:protected] =>
    )

[to:protected] => Array
    (
        [0] => Array
            (
                [0] => xxxxxxxxxx@yahoo.com.tw
                [1] =>
            )

    )

[cc:protected] => Array
    (
    )

[bcc:protected] => Array
    (
    )

[ReplyTo:protected] => Array
    (
    )

[all_recipients:protected] => Array
    (
        [xxxxxxxxxxx@yahoo.com.tw] => 1
    )

[RecipientsQueue:protected] => Array
    (
    )

[ReplyToQueue:protected] => Array
    (
    )

[attachment:protected] => Array
    (
    )

[CustomHeader:protected] => Array
    (
    )

[lastMessageID:protected] => <1d6e4a91953547c850de852e798ccbba@club3.idv.tw>
[message_type:protected] => plain
[boundary:protected] => Array
    (
        [1] => b1_1d6e4a91953547c850de852e798ccbba
        [2] => b2_1d6e4a91953547c850de852e798ccbba
        [3] => b3_1d6e4a91953547c850de852e798ccbba
    )

[language:protected] => Array
    (
        [authenticate] => SMTP Error: Could not authenticate.
        [connect_host] => SMTP Error: Could not connect to SMTP host.
        [data_not_accepted] => SMTP Error: data not accepted.
        [empty_message] => Message body empty
        [encoding] => Unknown encoding:
        [execute] => Could not execute:
        [file_access] => Could not access file:
        [file_open] => File Error: Could not open file:
        [from_failed] => The following From address failed:
        [instantiate] => Could not instantiate mail function.
        [invalid_address] => Invalid address:
        [mailer_not_supported] =>  mailer is not supported.
        [provide_address] => You must provide at least one recipient email address.
        [recipients_failed] => SMTP Error: The following recipients failed:
        [signing] => Signing Error:
        [smtp_connect_failed] => SMTP connect() failed.
        [smtp_error] => SMTP server error:
        [variable_set] => Cannot set or reset variable:
        [extension_missing] => Extension missing:
    )

[error_count:protected] => 2
[sign_cert_file:protected] =>
[sign_key_file:protected] =>
[sign_extracerts_file:protected] =>
[sign_key_pass:protected] =>
[exceptions:protected] => 1
[uniqueid:protected] => 1d6e4a91953547c850de852e798ccbba

)

Heading


问:
Python how to calcualate average of individual list of a list
I have a list in a list with a lot of data:

```<code>data =  [ [4,25,1,6,3,1,6,...],[45,2,1,5,6,20,29],[491,5,195,239,194,09]
         ..[2,1,5,6,1,95] ]
</code>```

and what I've been trying to figure out how to do is calculate the mean of each individual list and turn it into a column of data looking like this:

```<code>List# average
1     (Mean value of the first list)
2     (Mean value of the second list)
....
15    (mean value of the 15th list)
</code>```

I've tried to put in to loop of iteration like this:

```<code>def average(data)
    for i in range(16):
        total = 0.0
        for x in data[i]:
            total = total + x
    return total / len(data[i])
</code>```

but it only calculate the mean of the first list so far. I also want to calculate the mean of the each of those individual list with the first piece of data sliced off but I don't know how to do that with list in a list.

Edit: changed as suggested but I still have only 1 result from the function, not the average from every sublist.

答:
Replace numb by x.

And you should unindent your return by one.

Unfortunately, more problem might arise depending of your goals. :)

EDIT : I'm feeling generous

```<code>def average(listOfList):
    for index, listOfNumbers in listOfList:
        print (  "{}\t{}".format(index, sum(listOfNumbers) / len(listOfNumbers)) )
</code>```

Body:
I have a list in a list with a lot of data:

data =  [ [4,25,1,6,3,1,6,...],[45,2,1,5,6,20,29],[491,5,195,239,194,09]
         ..[2,1,5,6,1,95] ]

and what I've been trying to figure out how to do is calculate the mean of each individual list and turn it into a column of data looking like this:

List# average
1     (Mean value of the first list)
2     (Mean value of the second list)
....
15    (mean value of the 15th list)

I've tried to put in to loop of iteration like this:

def average(data)
    for i in range(16):
        total = 0.0
        for x in data[i]:
            total = total + x
    return total / len(data[i])

but it only calculate the mean of the first list so far. I also want to calculate the mean of the each of those individual list with the first piece of data sliced off but I don't know how to do that with list in a list.

Edit: changed as suggested but I still have only 1 result from the function, not the average from every sublist.

Body:
Replace numb by x.

And you should unindent your return by one.

Unfortunately, more problem might arise depending of your goals. :)

EDIT : I'm feeling generous

def average(listOfList):
    for index, listOfNumbers in listOfList:
        print (  "{}\t{}".format(index, sum(listOfNumbers) / len(listOfNumbers)) )


问:
Why is Pandas and Numpy producing different results for pairwise correlations with NaN?
I am trying to create a table of pairwise correlation for a model that I am building, and I have some numpy.nan values (NAN) in my dataset. For some reason, when I perform the correlation using np.corrcoef() I have different results than using pd.df.corr():

for instance:

```<code>dataset = np.array([[1,np.nan,np.nan,1,1],[1,np.nan,np.nan,3000,1]])
pandas_data = pd.DataFrame(dataset.transpose())

print np.corrcoef(dataset)
</code>```

to which I get:

```<code>[[ nan  nan]
[ nan  nan]]
</code>```

but with the pandas dataframe I do have one result:

```<code>print pandas_data.corr()

    0   1
0 NaN NaN
1 NaN   1
</code>```

Is there a fundamental difference in the way they handle NaN, or I missed something? (Also, why is my correlation 1 if I do have different values?) Thanks

答:
NumPy's default behavior is to propagate NaNs. That is, it performs the computations with the entire array, and every time something is added to NaN (or multiplied by, etc), the result is NaN.  This is reasonable: if a = 5 and b = NaN, a + b should be NaN. Consequently, the variance of an array containing at least one NaN is NaN, and so is the correlation of that array with any other array.

The raw-data-oriented nature of pandas leads to different design decisions: it tries to extract as much information as possible from incomplete data. In particular, the corr method is designed (and documented) to exclude NaN.

To reproduce  pandas behavior in NumPy, use a boolean mask valid as below: it requires that there are no NaN values in the column.

```<code>dataset = np.array([[1, 2, 3, 4, np.nan], [1, 0, np.nan, 8, 9]])

valid = ~np.isnan(dataset).any(axis=0)
numpy_corr = np.corrcoef(dataset[:, valid])

pandas_data = pd.DataFrame(dataset.transpose())
pandas_corr = pandas_data.corr()
</code>```

Both correlation methods now return the same result:

```<code>  [[ 1.        ,  0.90112711],
   [ 0.90112711,  1.        ]])
</code>```

The diagonal entries represent the correlation of an array with itself, which is always 1 (theoretically; in practice it's 1 within machine precision).

Body:
I am trying to create a table of pairwise correlation for a model that I am building, and I have some numpy.nan values (NAN) in my dataset. For some reason, when I perform the correlation using np.corrcoef() I have different results than using pd.df.corr():

for instance:

dataset = np.array([[1,np.nan,np.nan,1,1],[1,np.nan,np.nan,3000,1]])
pandas_data = pd.DataFrame(dataset.transpose())

print np.corrcoef(dataset)

to which I get:

[[ nan  nan]
[ nan  nan]]

but with the pandas dataframe I do have one result:

print pandas_data.corr()

    0   1
0 NaN NaN
1 NaN   1

Is there a fundamental difference in the way they handle NaN, or I missed something? (Also, why is my correlation 1 if I do have different values?) Thanks

Body:
NumPy's default behavior is to propagate NaNs. That is, it performs the computations with the entire array, and every time something is added to NaN (or multiplied by, etc), the result is NaN.  This is reasonable: if a = 5 and b = NaN, a + b should be NaN. Consequently, the variance of an array containing at least one NaN is NaN, and so is the correlation of that array with any other array.

The raw-data-oriented nature of pandas leads to different design decisions: it tries to extract as much information as possible from incomplete data. In particular, the corr method is designed (and documented) to exclude NaN.

To reproduce  pandas behavior in NumPy, use a boolean mask valid as below: it requires that there are no NaN values in the column.

dataset = np.array([[1, 2, 3, 4, np.nan], [1, 0, np.nan, 8, 9]])

valid = ~np.isnan(dataset).any(axis=0)
numpy_corr = np.corrcoef(dataset[:, valid])

pandas_data = pd.DataFrame(dataset.transpose())
pandas_corr = pandas_data.corr()

Both correlation methods now return the same result:

  [[ 1.        ,  0.90112711],
   [ 0.90112711,  1.        ]])

The diagonal entries represent the correlation of an array with itself, which is always 1 (theoretically; in practice it's 1 within machine precision).


问:
Show data from database in ajax
I want to show data from database into ajax.

function Data_Table() {
  $.ajax( {
    url: "<?php echo site_url('admin-spot/company/FieldTable')?>", type: "GET", dataType: "JSON", success: function(data) {
      $('#map').dataSrc(data.map);
    }
  }
  );
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe id="map" src="" frameborder="0" style="width: 100%; height: 300px;" allowfullscreen></iframe></code>```

答:
You can use .load() method here the jquery API jquery API

Javascript

Use simple

```<code>$("#result").load("ajax/test.html");
</code>```

or with a callback

```<code>$("#result").load("ajax/test.html", function() {
    alert( "Load was performed." );
});
</code>```

Title: Show data from database in ajax

Body:
You can use .load() method here the jquery API jquery API

Javascript

Use simple

$("#result").load("ajax/test.html");

or with a callback

$("#result").load("ajax/test.html", function() {
    alert( "Load was performed." );
});


答:
the problem with your code is an indentation error. your return statement is indented into your while loop. if you fix that it should work. however it is better to do this using an average function that finds the average of each sublist, and a list comprehension.

```<code>def average(l):
    return sum(l)/len(l) #float(len(l)) if python 2.x

new_list = [average(lst[1:]) for lst in list] # since you want to cut off the first value.
</code>```

also, you shouldn't use list as a variable, as it reassigns the builtin.

Title: Python how to calcualate average of individual list of a list

Body:
the problem with your code is an indentation error. your return statement is indented into your while loop. if you fix that it should work. however it is better to do this using an average function that finds the average of each sublist, and a list comprehension.

def average(l):
    return sum(l)/len(l) #float(len(l)) if python 2.x

new_list = [average(lst[1:]) for lst in list] # since you want to cut off the first value.

also, you shouldn't use list as a variable, as it reassigns the builtin.


问:
Oracle Trigger How to get Inserted value's parameter
I have a question while studying Oracle Database's triggers.

First of all, I created two tables like below:

```<code>**[Employee]**
(empno NUMBER, VARCHAR2 (20), deptno NUMBER, salary NUMBER)
**[Department]**
(deptno NUMBER, dname VARCHAR2 (20))
</code>```

Employee deptno refers to Department's deptno.

The trigger I want to create is to calculate the salary average of the data with deptno, such as inserted deptno.

For example, suppose I run the following code.

```<code>INSERT INTO employee values (1000, 'PAUL', 10, 4000);
</code>```

Then Trigger would like to have the following output:

```<code>Department [10]'s average of Salary = <avg (salary)>
</code>```

But I do not know how to pass inserted row's parameter in the Trigger.

Does anyone have a good way for me?

答:
I realized that if I use the AFTER INSERT keyword in the trigger, I get an 'ORA-04091' error because the contents of the table are changing. So I found out that I had to use before insert to get the result.
This is not the correct way, but I was able to express the output I wanted.

It was very simple. Before the table is changed (BEFORE INSERT Keyword), I store the sum of the columns in the variable to get the average.
Then add the new value to the variable using the ': NEW' keyword.

When I used this method, I did not get the 'ORA-04091' error because the table is still before the change.

Thanks to a lot of people, I've found that this is not a good way to write in a trigger.
However, I am thinking about this problem and I have learned a lot of internal actions such as the cost of triggers and when to call them.

Thank you again for all the answerer.

Body:
I have a question while studying Oracle Database's triggers.

First of all, I created two tables like below:

**[Employee]**
(empno NUMBER, VARCHAR2 (20), deptno NUMBER, salary NUMBER)
**[Department]**
(deptno NUMBER, dname VARCHAR2 (20))

Employee deptno refers to Department's deptno.

The trigger I want to create is to calculate the salary average of the data with deptno, such as inserted deptno.

For example, suppose I run the following code.

INSERT INTO employee values (1000, 'PAUL', 10, 4000);

Then Trigger would like to have the following output:

Department [10]'s average of Salary = <avg (salary)>

But I do not know how to pass inserted row's parameter in the Trigger.

Does anyone have a good way for me?


问:
correct use of colors in scatterpie
I want to make 6 different pies using scatterpie.  There are 101 different categories making up the pies (not all pies have 101), so I want to be able to differentiate the colors.

This does not give me enough colors (I can tell just by looking at the pies)

```<code>ggplot(wholebody_cutLH_wide_t) +
#  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_scatterpie(aes(x=imX, y=imY,r=radius),
            data=wholebody_cutLH_wide_t,     cols=colnames(wholebody_cutLH_wide_t[1:101]),color=NA) +
#scale_color_manual(values=sample(allcolors,101)) +
 scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
theme(legend.position="none",
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent") # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank(), # get rid of minor grid
    line = element_blank(),
    text = element_blank(),
    title = element_blank()
)
</code>```

Then if I try to set the colors manually as below I get a blank screen.
If I try and set the colors in the scatterpie (color=sample(allcolors,101)), then I get the error

Error: Aesthetics must be either length 1 or the same as the data (2864): colour

```<code>allcolors = grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = T)]
ggplot(wholebody_cutLH_wide_t) +
#  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_scatterpie(aes(x=imX, y=imY,r=radius),
            data=wholebody_cutLH_wide_t, cols=colnames(wholebody_cutLH_wide_t[1:101]),color=NA) +
scale_color_manual(values=sample(allcolors,101)) +
scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
theme(legend.position="none",
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent") # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank(), # get rid of minor grid
    line = element_blank(),
    text = element_blank(),
    title = element_blank()
 )
</code>```

答:
Here is the final working code.  I had to switch the scale_color_manual to scale_fill_manual.

```<code>ggplot(wholebody_cutLH_wide_t) +
annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_scatterpie(aes(x=imX, y=imY,r=radius),
            data=wholebody_cutLH_wide_t, cols=colnames(wholebody_cutLH_wide_t)[1:101],color=NA) +
scale_fill_manual(values=sample(allcolors,101)) +
scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
theme(legend.position="none",
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent") # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank(), # get rid of minor grid
    line = element_blank(),
    text = element_blank(),
    title = element_blank()
)
</code>```

And here is the plot

Title: correct use of colors in scatterpie

Body:
I want to make 6 different pies using scatterpie.  There are 101 different categories making up the pies (not all pies have 101), so I want to be able to differentiate the colors.

This does not give me enough colors (I can tell just by looking at the pies)

ggplot(wholebody_cutLH_wide_t) +
#  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_scatterpie(aes(x=imX, y=imY,r=radius),
            data=wholebody_cutLH_wide_t,     cols=colnames(wholebody_cutLH_wide_t[1:101]),color=NA) +
#scale_color_manual(values=sample(allcolors,101)) +
 scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
theme(legend.position="none",
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent") # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank(), # get rid of minor grid
    line = element_blank(),
    text = element_blank(),
    title = element_blank()
)

Then if I try to set the colors manually as below I get a blank screen.
If I try and set the colors in the scatterpie (color=sample(allcolors,101)), then I get the error

Error: Aesthetics must be either length 1 or the same as the data (2864): colour

allcolors = grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = T)]
ggplot(wholebody_cutLH_wide_t) +
#  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_scatterpie(aes(x=imX, y=imY,r=radius),
            data=wholebody_cutLH_wide_t, cols=colnames(wholebody_cutLH_wide_t[1:101]),color=NA) +
scale_color_manual(values=sample(allcolors,101)) +
scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
theme(legend.position="none",
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent") # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank(), # get rid of minor grid
    line = element_blank(),
    text = element_blank(),
    title = element_blank()
 )

Body:
Here is the final working code.  I had to switch the scale_color_manual to scale_fill_manual.

ggplot(wholebody_cutLH_wide_t) +
annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_scatterpie(aes(x=imX, y=imY,r=radius),
            data=wholebody_cutLH_wide_t, cols=colnames(wholebody_cutLH_wide_t)[1:101],color=NA) +
scale_fill_manual(values=sample(allcolors,101)) +
scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
theme(legend.position="none",
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent") # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank(), # get rid of minor grid
    line = element_blank(),
    text = element_blank(),
    title = element_blank()
)

And here is the plot


问:
How to label separate lines in the image (image of a text) separately using "bwlabel" in matlab?
I have recognized and labeled objects in my image that is fully consists of texts. you can see the objects are labeled as red color in the attached image. so, I want to separate the objects in the second line (or more lines) from the first line and give them different colors (each line would has a different colors) but I can't do that. do you have any idea? thanks for all answers.
this is part of my matlab code that does the labeling:

```<code>%% Label connected components
[L, Ne]=bwlabel(imagen);
%% Measure properties of image regions
propied=regionprops(L,'BoundingBox');
hold on
%% Plot Bounding Box
for n=1:size(propied,1)
    rectangle('Position',propied(n).BoundingBox,'EdgeColor','r','LineWidth',2)
end
</code>```

and this is labeled image that all the objects in different lines have the same label (same color=red).

答:
I think the following methods should work if the lines are not too curvy.

Find the centroids of the bounding boxes, or get the centroids from the regionprops itself, then cluster their y coordinates using kmeans with k = 2.
The result is not perfect, but fine. May be you can then fit a curve to the clustered points, with outlier removal (e.g. RANSAC)

OR

Prepare a new image by filling in the bounding boxes.

Prepare a rectangular structuring element whose height is 1 and width is the width of the widest bounding box.

Perform a morphological closing of the filled image using this structuring element. This will connect the regions horizontally. Now you get a mask separating the two regions.

The resulting images were obtained using opencv (I'm not posting the code because it's too untidy. Hope the instructions are clear enough).

Body:
I have recognized and labeled objects in my image that is fully consists of texts. you can see the objects are labeled as red color in the attached image. so, I want to separate the objects in the second line (or more lines) from the first line and give them different colors (each line would has a different colors) but I can't do that. do you have any idea? thanks for all answers.
this is part of my matlab code that does the labeling:

%% Label connected components
[L, Ne]=bwlabel(imagen);
%% Measure properties of image regions
propied=regionprops(L,'BoundingBox');
hold on
%% Plot Bounding Box
for n=1:size(propied,1)
    rectangle('Position',propied(n).BoundingBox,'EdgeColor','r','LineWidth',2)
end

and this is labeled image that all the objects in different lines have the same label (same color=red).


问:
Can I log when my JAX-RS application can't send its response? (How?)
I'm running a JAX-RS web service on EE6 (EAP 6.4, if that plays a role).

I'd like to be able to tell if the response was delivered to the client, but I can't seem to be able to pick up on errors.

I wrote a sandbox example:

```<code>@POST
@Path("/delay")
@Produces(MediaType.APPLICATION_XML)
public String justWait(InputStream is) throws IOException, InterruptedException {
    String theString = IOUtils.toString(is, "UTF-8");
    log.info("Received body: " + theString);
    log.info("Now waiting a bit");
    Thread.sleep(5000);
    log.info("Back, sending respoonse.");
    return "<OK/>";
}
</code>```

But whatever I do, whenever I send a POST, the log output is pretty and clean. Hit "abort" in the REST plugin? Nothing. Close the browser? Silence. Use curl and Ctrl-C it halfways? Nøpe.

I'm logging all incoming request using a javax.servlet.annotation.WebFilter, and I can also see the outgoing response, but it's of course after this logging that the delivery would fail.

How can I tell that my response wasn't sent?

If there are solutions in EE7, I'd also like to hear about them. We'll upgrade soon anyway.

答:
Try using a servlet filter to trap exceptions when the socket is closed prematurely.  Make sure it's first in your web.xml.</p>

```<code>import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class StackHunterServletFilter implements Filter {

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        try {
            try {
                chain.doFilter(request, response2);
            } catch (Throwable e) {
                e.printStackTrace();
                throw e;
            }
        } catch (IOException e) {
            throw e;
        } catch (ServletException e) {
            throw e;
        } catch (RuntimeException e) {
            throw e;
        } catch (Error e) {
            throw e;
        } catch (Throwable e) {
            throw new ServletException(e.getMessage(), e);
        }
    }

}
</code>```

Body:
I'm running a JAX-RS web service on EE6 (EAP 6.4, if that plays a role).

I'd like to be able to tell if the response was delivered to the client, but I can't seem to be able to pick up on errors.

I wrote a sandbox example:

@POST
@Path("/delay")
@Produces(MediaType.APPLICATION_XML)
public String justWait(InputStream is) throws IOException, InterruptedException {
    String theString = IOUtils.toString(is, "UTF-8");
    log.info("Received body: " + theString);
    log.info("Now waiting a bit");
    Thread.sleep(5000);
    log.info("Back, sending respoonse.");
    return "<OK/>";
}

But whatever I do, whenever I send a POST, the log output is pretty and clean. Hit "abort" in the REST plugin? Nothing. Close the browser? Silence. Use curl and Ctrl-C it halfways? Nøpe.

I'm logging all incoming request using a javax.servlet.annotation.WebFilter, and I can also see the outgoing response, but it's of course after this logging that the delivery would fail.

How can I tell that my response wasn't sent?

If there are solutions in EE7, I'd also like to hear about them. We'll upgrade soon anyway.

Body:
Try using a servlet filter to trap exceptions when the socket is closed prematurely.  Make sure it's first in your web.xml.

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class StackHunterServletFilter implements Filter {

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        try {
            try {
                chain.doFilter(request, response2);
            } catch (Throwable e) {
                e.printStackTrace();
                throw e;
            }
        } catch (IOException e) {
            throw e;
        } catch (ServletException e) {
            throw e;
        } catch (RuntimeException e) {
            throw e;
        } catch (Error e) {
            throw e;
        } catch (Throwable e) {
            throw new ServletException(e.getMessage(), e);
        }
    }

}


问:
removing second layer for loop when defining array
Working in MATLAB R2017a. I'm trying to optimise a piece of code I'm working on. It uses arrays to store field values on a grid.
In order to create a specific function in a field array I originally used the straight forward method of two for loops iterating over all the array elements. But i know for loops are slow so since then I came back and tried my best to remove them. However I could only manage to remove one of the loops; leaving me with this:

```<code>for n = 1:1:K

%%% define initial pertubation

t=n*dt;

% create array for source Ez field.

xtemps = (1:Ng)*dX;

for k = 1:Ng

    ztemp = k*dX;

    Ez0(k,:) = THzamp * (1/(1+exp(-(t-stepuppos)))) * exp(-((xtemps-...
    THzstartx).^2)./(bx^2)) .* (t-((ztemp-THzstartz)/vg))*exp(-((t-((ztemp-...
    THzstartz)/vg))^2)/(bt^2));

end
</code>```

The important bit here is the last 5 lines, but I figured the stuff before might be important for context. I've removed the for loop looping over the x coordinates. I want to vectorize the z/k for loop but I can't figure out how to distinguish between the dimensions with the array oporators.

Edit: THzamp, stepuppos, bx, bt, THzstartz, THzstartx are all just scalars, they control the function (Ez0) I'm trying to create. dX and t are also just scalars. Ez0 is a square array of size Ng.

What I want to achieve is to remove the for loop that loops over k, so that that the values of ztemp are defined in a vector (like xtemps already is), rather than individually in the loop. However, I don't know how I'd write the definition of Ez0 in that case.

First time posting here, if I'm doing it wrong let me know. If you need more info just ask.

答:
It isn't clear if n is used in the other headers and as stated in the comments your sizes aren't properly defined so you'll have to ensure the sizes are correct.

However, you can give this vectorize code a try.

```<code>n = 1:K

%%% define initial pertubation

t=n*dt;

% create array for source Ez field.

xtemps = (1:Ng)*dX;

for k = 1:Ng

    ztemp = k*dX;

    Ez0(k,:) = THzamp .* (1./(1+exp(-(t-stepuppos)))) .* exp(-((xtemps-...
    THzstartx).^2)./(bx^2)) .* (t-((ztemp-THzstartz)/vg)).*exp(-((t-((ztemp-...
    THzstartz)/vg)).^2)/(bt.^2));

end
</code>```

So now t has the size K you'll need to ensure stepupposand (ztemp-THzstartz)/vg) have the same size K. Also you can take a look at vectors vs array operators here.

Body:
Working in MATLAB R2017a. I'm trying to optimise a piece of code I'm working on. It uses arrays to store field values on a grid.
In order to create a specific function in a field array I originally used the straight forward method of two for loops iterating over all the array elements. But i know for loops are slow so since then I came back and tried my best to remove them. However I could only manage to remove one of the loops; leaving me with this:

for n = 1:1:K

%%% define initial pertubation

t=n*dt;

% create array for source Ez field.

xtemps = (1:Ng)*dX;

for k = 1:Ng

    ztemp = k*dX;

    Ez0(k,:) = THzamp * (1/(1+exp(-(t-stepuppos)))) * exp(-((xtemps-...
    THzstartx).^2)./(bx^2)) .* (t-((ztemp-THzstartz)/vg))*exp(-((t-((ztemp-...
    THzstartz)/vg))^2)/(bt^2));

end

The important bit here is the last 5 lines, but I figured the stuff before might be important for context. I've removed the for loop looping over the x coordinates. I want to vectorize the z/k for loop but I can't figure out how to distinguish between the dimensions with the array oporators.

Edit: THzamp, stepuppos, bx, bt, THzstartz, THzstartx are all just scalars, they control the function (Ez0) I'm trying to create. dX and t are also just scalars. Ez0 is a square array of size Ng.

What I want to achieve is to remove the for loop that loops over k, so that that the values of ztemp are defined in a vector (like xtemps already is), rather than individually in the loop. However, I don't know how I'd write the definition of Ez0 in that case.

First time posting here, if I'm doing it wrong let me know. If you need more info just ask.

Body:
It isn't clear if n is used in the other headers and as stated in the comments your sizes aren't properly defined so you'll have to ensure the sizes are correct.

However, you can give this vectorize code a try.

n = 1:K

%%% define initial pertubation

t=n*dt;

% create array for source Ez field.

xtemps = (1:Ng)*dX;

for k = 1:Ng

    ztemp = k*dX;

    Ez0(k,:) = THzamp .* (1./(1+exp(-(t-stepuppos)))) .* exp(-((xtemps-...
    THzstartx).^2)./(bx^2)) .* (t-((ztemp-THzstartz)/vg)).*exp(-((t-((ztemp-...
    THzstartz)/vg)).^2)/(bt.^2));

end

So now t has the size K you'll need to ensure stepupposand (ztemp-THzstartz)/vg) have the same size K. Also you can take a look at vectors vs array operators here.


问:
neo4j how to return all node labels with Cypher?
I can't find how to return a node labels with Cypher.

Anybody knows the syntax for this operation?

答: If you want to get the labels of a specify node, then use labels(node); If you only want to get all node labels in neo4j, then use this function instead: call db.labels;, never ever use this query: MATCH n RETURN DISTINCT LABELS(n). It will do a full table scan, which is very very slow..


问:
what belong is BadTokenException at classes of project
I am trying to run my app in API 25 but when I tap button I got this error:

```<code>E/ACRA: ACRA caught a BadTokenException for com.safa.visit.ts.debug
    android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@2fc535e is not valid; is your activity running?
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:922)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:377)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:105)
        at android.widget.Toast$TN.handleShow(Toast.java:747)
        at android.widget.Toast$TN$2.handleMessage(Toast.java:622)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6823)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
</code>```

I have searched and I find out this problem is for Toast. Because toast context may be be NULL. For that I checked context before showing context. This is my method:

```<code>    private void toastError(Context ctx,final String msg) {
    if (ctx != null)
    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
}
</code>```

My problem is, I do not know this error is for what page or class, because that place, where I clicked at the button and this error is appeared, I put my method there and have used my method instead of Toast but still I got this error.

What can you suggest me?

答:
I have created a library to hook and fix this BadTokenException:

https://github.com/drakeet/ToastCompat

Just use:

```<code>ToastCompat.makeText(context, "hello world!", Toast.LENGTH_SHORT).show();
</code>```

Or with BadTokenListener#onBadTokenCaught(@NonNull Toast toast):

```<code>ToastCompat.makeText(this, "hello", Toast.LENGTH_SHORT)
    .setBadTokenListener(toast -> {
        ...
    }).show();
</code>```

Why the Exception: https://github.com/drakeet/ToastCompat#why

Body:
I am trying to run my app in API 25 but when I tap button I got this error:

E/ACRA: ACRA caught a BadTokenException for com.safa.visit.ts.debug
    android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@2fc535e is not valid; is your activity running?
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:922)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:377)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:105)
        at android.widget.Toast$TN.handleShow(Toast.java:747)
        at android.widget.Toast$TN$2.handleMessage(Toast.java:622)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6823)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'

I have searched and I find out this problem is for Toast. Because toast context may be be NULL. For that I checked context before showing context. This is my method:

    private void toastError(Context ctx,final String msg) {
    if (ctx != null)
    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
}

My problem is, I do not know this error is for what page or class, because that place, where I clicked at the button and this error is appeared, I put my method there and have used my method instead of Toast but still I got this error.

What can you suggest me?

Body:
I have created a library to hook and fix this BadTokenException:

https://github.com/drakeet/ToastCompat

Just use:

ToastCompat.makeText(context, "hello world!", Toast.LENGTH_SHORT).show();

Or with BadTokenListener#onBadTokenCaught(@NonNull Toast toast):

ToastCompat.makeText(this, "hello", Toast.LENGTH_SHORT)
    .setBadTokenListener(toast -> {
        ...
    }).show();

Why the Exception: https://github.com/drakeet/ToastCompat#why