问:
Fetching data from database into checkbox
I am trying to edit my form. Currently, i am able to retrieve data into my input textbox but not the checkbox. Now when, i am inserting data, i check the items that i want to insert, get the ids and save into my database.

Now when i want to edit, i want to retrieve the items that i previously selected (the checkbox of which i selected should be checked ).

In my Json below, i am able to display the id of the food that i selected when i was storing. How can i fetch that into my checkbox back

Desired output

I want to have the selected items checked. As in my JSON, i have stored chicken wings. If i click on edit, chicken wings should be checked already.

PS: I am a beginner and my english is not really good.

Controller

```<code>     $item = Item::findOrFail($id);
     return view('edit',compact('item'));
</code>```

HTML

```<code><div class="panel label_container">
<input onclick="return items(this)" type="checkbox" id="" name="" value="" />
</div>
</code>```

JSON

答:
this is one of my issue back then in checkbox, you can use tenary to check the checkbox if there is a value for that attribute. Try this one,

```<code><div class="panel label_container">
<input onclick="return items(this)" type="checkbox" id="" name="item_checked" value="1" {{ $item->item_checked ? 'checked' : '' }} />
</div>
</code>```

Hope this helps :)

Body:
I am trying to edit my form. Currently, i am able to retrieve data into my input textbox but not the checkbox. Now when, i am inserting data, i check the items that i want to insert, get the ids and save into my database.

Now when i want to edit, i want to retrieve the items that i previously selected (the checkbox of which i selected should be checked ).

In my Json below, i am able to display the id of the food that i selected when i was storing. How can i fetch that into my checkbox back

Desired output

I want to have the selected items checked. As in my JSON, i have stored chicken wings. If i click on edit, chicken wings should be checked already.

PS: I am a beginner and my english is not really good.

Controller

     $item = Item::findOrFail($id);
     return view('edit',compact('item'));

HTML

<input onclick="return items(this)" type="checkbox" id="" name="" value="" />

JSON

Body:
this is one of my issue back then in checkbox, you can use tenary to check the checkbox if there is a value for that attribute. Try this one,

<div class="panel label_container">
<input onclick="return items(this)" type="checkbox" id="" name="item_checked" value="1" {{ $item->item_checked ? 'checked' : '' }} />
</div>

Hope this helps :)


来源: stackexchange

问:
R: transforming specific rows into columns
I have quite messy data imported from json file, it looks like this:

```<code>raw_df <- data.frame(text = c(paste0('text', 1:3), '---------- OUTCOME LINE ----------', paste0('text', 4:6), '---------- OUTCOME LINE ----------'),
                              demand = c('cat1', rep('', 2), 'info', 'cat2', rep('', 2), 'info2')
                     )

raw_df
                                text demand
1                              text1   cat1
2                              text2
3                              text3
4 ---------- OUTCOME LINE ----------   info
5                              text4   cat2
6                              text5
7                              text6
8 ---------- OUTCOME LINE ----------  info2
</code>```

(BTW, ---------- OUTCOME LINE ---------- is the actual string that I have in text column)

I want to tidy it up so that it has the following format:

```<code>final_df
                  text demand outcome
1 text1. text2. text3.   cat1   info1
2 text4. text5. text6.   cat2   info2
</code>```

What would be the quickest and most efficient way to do this? thanks for the tips.

答:
A dplyr & tidyr solution:

```<code>raw_df %>%
    mutate(outcome = demand,
           demand = replace(demand, demand == '', NA),
           outcome = replace(outcome, outcome == '', NA),
           outcome = gsub("^cat\\d+", NA, outcome)) %>%
    fill(demand) %>%
    fill(outcome, .direction = "up") %>%
    filter(!grepl("-----", text)) %>%
    group_by(demand, outcome) %>%
    summarize(text = gsub(",", "\\.", toString(text))) %>%
    select(text, everything())
</code>```

fix up the text to display as desired, swap out blanks for NAs, and prep the outcome column.

fill the demand column in the default down direction, and the outcome column in an up direction.

filter out the  ----- OUTCOME LINE ------ based upon its hyphens.

generate the group_concat for the text column, and then swap the default , out with ..

select the columns into the desired sequence.

```<code># A tibble: 2 x 3
# Groups:   demand [2]
                 text demand outcome
                <chr> <fctr>   <chr>
1 text1. text2. text3   cat1    info
2 text4. text5. text6   cat2   info2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have quite messy data imported from json file, it looks like this:

raw_df <- data.frame(text = c(paste0('text', 1:3), '---------- OUTCOME LINE ----------', paste0('text', 4:6), '---------- OUTCOME LINE ----------'),
                              demand = c('cat1', rep('', 2), 'info', 'cat2', rep('', 2), 'info2')
                     )

raw_df
                                text demand
1                              text1   cat1
2                              text2
3                              text3
4 ---------- OUTCOME LINE ----------   info
5                              text4   cat2
6                              text5
7                              text6
8 ---------- OUTCOME LINE ----------  info2

(BTW, ---------- OUTCOME LINE ---------- is the actual string that I have in text column)

I want to tidy it up so that it has the following format:

final_df
                  text demand outcome
1 text1. text2. text3.   cat1   info1
2 text4. text5. text6.   cat2   info2

What would be the quickest and most efficient way to do this? thanks for the tips.

Body:
A dplyr & tidyr solution:

raw_df %>%
    mutate(outcome = demand,
           demand = replace(demand, demand == '', NA),
           outcome = replace(outcome, outcome == '', NA),
           outcome = gsub("^cat\\d+", NA, outcome)) %>%
    fill(demand) %>%
    fill(outcome, .direction = "up") %>%
    filter(!grepl("-----", text)) %>%
    group_by(demand, outcome) %>%
    summarize(text = gsub(",", "\\.", toString(text))) %>%
    select(text, everything())

fix up the text to display as desired, swap out blanks for NAs, and prep the outcome column.

fill the demand column in the default down direction, and the outcome column in an up direction.

filter out the  ----- OUTCOME LINE ------ based upon its hyphens.

generate the group_concat for the text column, and then swap the default , out with ..

select the columns into the desired sequence.

# A tibble: 2 x 3
# Groups:   demand [2]
                 text demand outcome
                <chr> <fctr>   <chr>
1 text1. text2. text3   cat1    info
2 text4. text5. text6   cat2   info2


问:
Enforcing polymorphic parameters to be of same type
In the method below, I was hoping to set up the type of the function to
enforce that from and to are the same type of LexicalDate. I.e. they must both be Day or both must be Hour.

Currently, from and to can be passed as different types of LexicalDate.

Can from and to be forced at the compile level to always be the same type of LexicalDate?

```<code>sealed trait LexicalDate
case object Day extends LexicalDate
case object Hour extends LexicalDate
def queryDate[Date <: LexicalDate](
    id: Long,
    from: Date,
    to: Date
  )
</code>```

答:
What you are looking for is the generalized type constraint =:=, which requires that a compiler should be able to prove that two types are equal. For your case, =:= can be used as follows (in particular, note the implicit parameter list of the queryDate method):

scala> def queryDate[A <: LexicalDate, B <: LexicalDate](id: Long, from: A, to: B)(implicit ev: A =:= B) { }
queryDate: [A <: LexicalDate, B <: LexicalDate](id: Long, from: A, to: B)(implicit ev: A =:= B)Unit

scala> queryDate(10, Day, Day)

scala> queryDate(10, Hour, Hour)

scala> queryDate(10, Day, Hour)
<console>:15: error: Cannot prove that Day.type =:= Hour.type.
       queryDate(10, Day, Hour)
                ^

scala> queryDate(10, Hour, Day)
<console>:15: error: Cannot prove that Hour.type =:= Day.type.
       queryDate(10, Hour, Day)
                ^
```

Refer to the following links for the general description of generalized type constraints:

What do <:<, <%<, and =:= mean in Scala 2.8, and where are they documented?

Generalized type constraints in Scala (without a PhD)

Body:
In the method below, I was hoping to set up the type of the function to
enforce that from and to are the same type of LexicalDate. I.e. they must both be Day or both must be Hour.

Currently, from and to can be passed as different types of LexicalDate.

Can from and to be forced at the compile level to always be the same type of LexicalDate?

sealed trait LexicalDate
case object Day extends LexicalDate
case object Hour extends LexicalDate
def queryDate[Date <: LexicalDate](
    id: Long,
    from: Date,
    to: Date
  )

Body:
What you are looking for is the generalized type constraint =:=, which requires that a compiler should be able to prove that two types are equal. For your case, =:= can be used as follows (in particular, note the implicit parameter list of the queryDate method):

scala> def queryDate[A <: LexicalDate, B <: LexicalDate](id: Long, from: A, to: B)(implicit ev: A =:= B) { }
queryDate: [A <: LexicalDate, B <: LexicalDate](id: Long, from: A, to: B)(implicit ev: A =:= B)Unit

scala> queryDate(10, Day, Day)

scala> queryDate(10, Hour, Hour)

scala> queryDate(10, Day, Hour)
<console>:15: error: Cannot prove that Day.type =:= Hour.type.
       queryDate(10, Day, Hour)
                ^

scala> queryDate(10, Hour, Day)
<console>:15: error: Cannot prove that Hour.type =:= Day.type.
       queryDate(10, Hour, Day)
                ^

Refer to the following links for the general description of generalized type constraints:

What do <:<, <%<, and =:= mean in Scala 2.8, and where are they documented?

Generalized type constraints in Scala (without a PhD)


问:
How to delete all events from the default calendar
How can I delete all events in the default calendar when a button is tapped?

This is my current code

```<code>     @IBAction func deleteEvents(_ sender: UIButton) {

         eventStore.calendars(for: .event).removeAll()
      }
</code>```

The first problem it's not the current calendar. The second problem is that I get the following error:

Error:

Cannot use mutating member on immutable value: function call returns immutable value

答:
There is no removeAll method.

You need to use the methods of EKEventStore to query and remove the desired events.

At a high level you need to:

Request authorization to access calendar events.

Get a reference to desired the EKCalendar.

Create a predicate for the events you wish to query. You need a date range and the calendar.

Enumerate the events that match the predicate.

Delete each enumerated event.

All of the needed APIs are in the EKEventStore class. See its documentation for specifics.

Body:
How can I delete all events in the default calendar when a button is tapped?

This is my current code

     @IBAction func deleteEvents(_ sender: UIButton) {

         eventStore.calendars(for: .event).removeAll()
      }

The first problem it's not the current calendar. The second problem is that I get the following error:

Error:

Cannot use mutating member on immutable value: function call returns immutable value


问:
While seeding database in Laravel, why with same code for one model's seeder as the previous which is successful, do I get an error?
I have two tables, manufacturers & models that I'm seeding via factories.

ManufacturersFactory:

```<code>use \Faker\Generator as Faker;

$factory->define(\Modules\Cars\Entities\Manufacturer::class, function (Faker $faker) {
    return [
        'title' => $faker->company,
        'summary' => $faker->paragraph,
        'url' => $faker->domainName,
        'dealer' => $faker->boolean(20),
    ];
});
</code>```

ManufacturersTableSeeder:

```<code>namespace Modules\Cars\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class ManufacturersTableSeeder extends Seeder
{
    public function run()
    {
      factory(\Modules\Cars\Entities\Manufacturer::class, 25)->create();
    }
}
</code>```

^ Seeds perfectly successfully.

CarsDatabaseSeeder:

```<code>namespace Modules\Cars\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class CarsDatabaseSeeder extends Seeder
{
    public function run()
    {
      \Eloquent::unguard();

      \DB::table('models')->truncate();
      \DB::table('manufacturers')->truncate();

      \DB::statement('SET FOREIGN_KEY_CHECKS=0;');

      $this->call([
        ManufacturersTableSeeder::class,
        ModelsTableSeeder::class
      ]);

      \DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }
}
</code>```

ModelsFactory:

```<code>use \Faker\Generator as Faker;

$factory->define(\Modules\Cars\Entities\Model::class, function (Faker $faker) {
    return [
      'title' => $faker->word,
      'manufacturer_id' => $faker->numberBetween(1,\Modules\Cars\Entities\Manufacturer::get()->count()),
      'length_ft' => $faker->numberBetween(30,160),
    ];
});
</code>```

ModelsTableSeeder:

```<code>namespace Modules\Cars\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class ModelsTableSeeder extends Seeder
{
    public function run()
    {
        factory(\Modules\Cars\Entities\Model::class, 60)->create();
    }
}
</code>```

No errors if I comment out the factory function.

I do not see how these two are different and thereby why I am receiving the following error when running with Models:

```<code>vagrant@laravel:~/code$ php artisan module:seed Cars
Seeding: Modules\Cars\Database\Seeders\ManufacturersTableSeeder
Seeding: Modules\Cars\Database\Seeders\ModelsTableSeeder
PHP Fatal error:  Cannot declare class Modules\Cars\Entities\Model because the name is already in use in /home/vagrant/code/Modules/Cars/Entities/Model.php on line 7

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Cannot declare class Modules\Cars\Entities\Model because the name is already in use
</code>```

Help please???

Update: changed both manufacturers & models to CSV imports now, manufacturers works fine same way as this one but this one is still producing that same error unless I comment out the [next to] last line:

```<code>    $csv = Reader::createFromPath(__DIR__.'/data/models.csv', 'r');
    $csv->setHeaderOffset(0);
    $headers = $csv->getHeader();
    $records = $csv->getRecords();
    foreach ($records as $r) {
      $cols = array_combine($headers, $r);
      $i = [];
      foreach($headers as $h)
      {
        if(!\Schema::hasColumn('models',$h)) continue;
        if($h == 'manufacturer') {
          $cols[$h] = Manufacturer::where('title', $cols[$h])->first()->id;
          $i['manufacturer_id'] = $cols[$h];
        }
        else $i[$h] = $cols[$h];
      }
      \Modules\Cars\Entities\Model::create($i);
    }
</code>```

Model model:

```<code>namespace Modules\Cars\Entities;

use Illuminate\Database\Eloquent\Model;

class Model extends Model
{
    protected $fillable = [
      'title', 'manufacturer_id', 'length_ft',
    ];
}
</code>```

I tried use Illuminate\Database\Eloquent\Model as EloquentModel; with class Model extends EloquentModel and then get this:

```<code>  [Symfony\Component\Debug\Exception\FatalThrowableError]
  Wrong parameters for Symfony\Component\Debug\Exception\FatalThrowableError([str
  ing $message [, long $code, [ long $severity, [ string $filename, [ long $linen
  o  [, Throwable $previous = NULL]]]]]])
</code>```

答:
Model has already been declared by Illuminate\Database\Eloquent\Model.

You can alias the Eloquent model in this case.

```<code>use Illuminate\Database\Eloquent\Model as EloquentModel;

class Model extends EloquentModel
{
</code>```

Body:
I have two tables, manufacturers & models that I'm seeding via factories.

ManufacturersFactory:

use \Faker\Generator as Faker;

$factory->define(\Modules\Cars\Entities\Manufacturer::class, function (Faker $faker) {
    return [
        'title' => $faker->company,
        'summary' => $faker->paragraph,
        'url' => $faker->domainName,
        'dealer' => $faker->boolean(20),
    ];
});

ManufacturersTableSeeder:

namespace Modules\Cars\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class ManufacturersTableSeeder extends Seeder
{
    public function run()
    {
      factory(\Modules\Cars\Entities\Manufacturer::class, 25)->create();
    }
}

^ Seeds perfectly successfully.

CarsDatabaseSeeder:

namespace Modules\Cars\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class CarsDatabaseSeeder extends Seeder
{
    public function run()
    {
      \Eloquent::unguard();

      \DB::table('models')->truncate();
      \DB::table('manufacturers')->truncate();

      \DB::statement('SET FOREIGN_KEY_CHECKS=0;');

      $this->call([
        ManufacturersTableSeeder::class,
        ModelsTableSeeder::class
      ]);

      \DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }
}

ModelsFactory:

use \Faker\Generator as Faker;

$factory->define(\Modules\Cars\Entities\Model::class, function (Faker $faker) {
    return [
      'title' => $faker->word,
      'manufacturer_id' => $faker->numberBetween(1,\Modules\Cars\Entities\Manufacturer::get()->count()),
      'length_ft' => $faker->numberBetween(30,160),
    ];
});

ModelsTableSeeder:

namespace Modules\Cars\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class ModelsTableSeeder extends Seeder
{
    public function run()
    {
        factory(\Modules\Cars\Entities\Model::class, 60)->create();
    }
}

No errors if I comment out the factory function.

I do not see how these two are different and thereby why I am receiving the following error when running with Models:

vagrant@laravel:~/code$ php artisan module:seed Cars
Seeding: Modules\Cars\Database\Seeders\ManufacturersTableSeeder
Seeding: Modules\Cars\Database\Seeders\ModelsTableSeeder
PHP Fatal error:  Cannot declare class Modules\Cars\Entities\Model because the name is already in use in /home/vagrant/code/Modules/Cars/Entities/Model.php on line 7

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Cannot declare class Modules\Cars\Entities\Model because the name is already in use

Help please???

Update: changed both manufacturers & models to CSV imports now, manufacturers works fine same way as this one but this one is still producing that same error unless I comment out the [next to] last line:

    $csv = Reader::createFromPath(__DIR__.'/data/models.csv', 'r');
    $csv->setHeaderOffset(0);
    $headers = $csv->getHeader();
    $records = $csv->getRecords();
    foreach ($records as $r) {
      $cols = array_combine($headers, $r);
      $i = [];
      foreach($headers as $h)
      {
        if(!\Schema::hasColumn('models',$h)) continue;
        if($h == 'manufacturer') {
          $cols[$h] = Manufacturer::where('title', $cols[$h])->first()->id;
          $i['manufacturer_id'] = $cols[$h];
        }
        else $i[$h] = $cols[$h];
      }
      \Modules\Cars\Entities\Model::create($i);
    }

Model model:

namespace Modules\Cars\Entities;

use Illuminate\Database\Eloquent\Model;

class Model extends Model
{
    protected $fillable = [
      'title', 'manufacturer_id', 'length_ft',
    ];
}

I tried use Illuminate\Database\Eloquent\Model as EloquentModel; with class Model extends EloquentModel and then get this:

  [Symfony\Component\Debug\Exception\FatalThrowableError]
  Wrong parameters for Symfony\Component\Debug\Exception\FatalThrowableError([str
  ing $message [, long $code, [ long $severity, [ string $filename, [ long $linen
  o  [, Throwable $previous = NULL]]]]]])

Body:
Model has already been declared by Illuminate\Database\Eloquent\Model.

You can alias the Eloquent model in this case.

use Illuminate\Database\Eloquent\Model as EloquentModel;

class Model extends EloquentModel
{


问:
ChartJS: how to change data in hover box?
Chart is at the bottom of this page:

http://www.coinparator.com/cgqnYQ/

My PHP script is sending X axis values as a unix time stamp. And while I'm generating chart with JS, I'm converting these unix timestamps into a time.

callback: function(dataLabel, index) {
  timezoned = parseInt(dataLabel, 10) * 1000;
  var date = new Date(timezoned);
  var hours = date.getHours();
  var minutes = "0" + date.getMinutes();
  dataLabel = hours + ':' + minutes.substr(-2);
  return index % 2 === 0 ? dataLabel : '';
}```

As you can se, it works OK. X axis shows time. However if you hover over any point in the chart (dots on the trendline), it will show you unconverted unix timestamp again.

How can I show converted time even in hover boxes over trendline?

答:
You want to set/override the tooltips option when generating the graph.  I've slightly edited some coffee script code I use in a project to give you an idea of how to achieve this</p>

```<code>  tooltips:
      mode: 'label'
      callbacks:
        title: (tooltipItem, data) ->
          return [your date conversion function here]
        label: (tooltipItem, data) ->
          return data
</code>```

Body:
Chart is at the bottom of this page:

http://www.coinparator.com/cgqnYQ/

My PHP script is sending X axis values as a unix time stamp. And while I'm generating chart with JS, I'm converting these unix timestamps into a time.

callback: function(dataLabel, index) {
  timezoned = parseInt(dataLabel, 10) * 1000;
  var date = new Date(timezoned);
  var hours = date.getHours();
  var minutes = "0" + date.getMinutes();
  dataLabel = hours + ':' + minutes.substr(-2);
  return index % 2 === 0 ? dataLabel : '';
}

As you can se, it works OK. X axis shows time. However if you hover over any point in the chart (dots on the trendline), it will show you unconverted unix timestamp again.

How can I show converted time even in hover boxes over trendline?

Body:
You want to set/override the tooltips option when generating the graph.  I've slightly edited some coffee script code I use in a project to give you an idea of how to achieve this

  tooltips:
      mode: 'label'
      callbacks:
        title: (tooltipItem, data) ->
          return [your date conversion function here]
        label: (tooltipItem, data) ->
          return data


问:
Spring CustomNumberEditor parses numbers that are not numbers
I'm using Spring CustomNumberEditor editor to bind my float values and I've experimented that if in the value is not a number sometimes it can parse the value and no error is returned.

number=10 ...... then the number is 10 and there's no errors

number=10a ......   then the number is 10 and there's no errors

number=10a25 ...... then the number is 10 and there's no errors

number=a ...... error because the number is not valid

So it seems that the editor parses the value until it can and omit the rest. Is there any way to configure this editor so the validation is strict (so numbers like 10a or 10a25 result in error) or do I have to build my custom implementation. I'm looking something like setting lenient to false in CustomDateEditor/DateFormat so dates cannot be parsed to the most probable one.

The way I register the editor is:

```<code>@InitBinder
public void initBinder(WebDataBinder binder){
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setGroupingUsed(false);
    binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, numberFormat, true));
}
</code>```

Thanks.

答:
You can not do this whith NumberFormat.

The documentation is clear about this fact:

```<code>/**
 * Parses text from the beginning of the given string to produce a number.
 * The method may not use the entire text of the given string.
 * <p>
 * See the {@link #parse(String, ParsePosition)} method for more information
 * on number parsing.
 *
 * @param source A <code>String</code> whose beginning should be parsed.
 * @return A <code>Number</code> parsed from the string.
 * @exception ParseException if the beginning of the specified string
 *            cannot be parsed.
 */
public Number parse(String source) throws ParseException {
</code>```

When you acceept this API it would even be even invalid to write a parser that does what you want and implement the NumberFormat interface. This mean you have to implment your own Property Editor instead.

```<code>/* untested */
public class StrictNumberPropertyEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
       super.setValue(Float.parseFloat(text));
    }

    @Override
    public String getAsText() {
        return ((Number)this.getValue()).toString();
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using Spring CustomNumberEditor editor to bind my float values and I've experimented that if in the value is not a number sometimes it can parse the value and no error is returned.

number=10 ...... then the number is 10 and there's no errors

number=10a ......   then the number is 10 and there's no errors

number=10a25 ...... then the number is 10 and there's no errors

number=a ...... error because the number is not valid

So it seems that the editor parses the value until it can and omit the rest. Is there any way to configure this editor so the validation is strict (so numbers like 10a or 10a25 result in error) or do I have to build my custom implementation. I'm looking something like setting lenient to false in CustomDateEditor/DateFormat so dates cannot be parsed to the most probable one.

The way I register the editor is:

@InitBinder
public void initBinder(WebDataBinder binder){
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setGroupingUsed(false);
    binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, numberFormat, true));
}

Thanks.

Body:
You can not do this whith NumberFormat.

The documentation is clear about this fact:

/**
 * Parses text from the beginning of the given string to produce a number.
 * The method may not use the entire text of the given string.
 * <p>
 * See the {@link #parse(String, ParsePosition)} method for more information
 * on number parsing.
 *
 * @param source A <code>String</code> whose beginning should be parsed.
 * @return A <code>Number</code> parsed from the string.
 * @exception ParseException if the beginning of the specified string
 *            cannot be parsed.
 */
public Number parse(String source) throws ParseException {

When you acceept this API it would even be even invalid to write a parser that does what you want and implement the NumberFormat interface. This mean you have to implment your own Property Editor instead.

/* untested */
public class StrictNumberPropertyEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
       super.setValue(Float.parseFloat(text));
    }

    @Override
    public String getAsText() {
        return ((Number)this.getValue()).toString();
    }
}


问:
Why can template function parameters of type T& be binded to const lvalues but not rvalues?
Consider:

```<code>template <typename T> void f(T&);

const int b = 2;
f(b);      // ok
f(2);      // error, can not bind rvalue to lvalue reference
</code>```

Why is f(const int) allowed? the logic seems to indicate that if the programmer did not explicitly define the template parameter as const T&, he/she wanted to modify the binded-to variable.

So in this case the question is, why does template instantiation give itself the freedom to instantiate with consts when those were not explicitly required ?

Even if there was a rationale for allowing template instantiation to instantiate with consts, then why, in that case, would be binding to rvalues forbidden? you can bind rvalues to const lvalue references. In that case, the template would be instantiated to f<const int>, and f(2) would be allowed.

I want to know the reasoning behind these decisions, not references to the standard.

答:
Why is f(const int) allowed?

You might subsitute the template T by const int to transform T& into const int&

Even if there was a rationale for allowing template instantiation to instantiate with consts, then why, in that case, would be binding to rvalues forbidden?

There is no T (in T&) which (exact) matches int&& for deduction.

f<const int>(42) is allowed, but there is no deduction happening.

I want to know the reasoning behind these decisions, not references to the standard.

So why allowing cv substitution in template?

I would say it make generic programming easier.

Else you would have to provide overloads for each combination of const, volatile.

Here, if you want to restrict T to non const, you may use SFINAE with traits:

```<code>template <typename T> std::enable_if_t<!std::is_const<T>::value> f(T&);
</code>```

Body:
Consider:

template <typename T> void f(T&);

const int b = 2;
f(b);      // ok
f(2);      // error, can not bind rvalue to lvalue reference

Why is f(const int) allowed? the logic seems to indicate that if the programmer did not explicitly define the template parameter as const T&, he/she wanted to modify the binded-to variable.

So in this case the question is, why does template instantiation give itself the freedom to instantiate with consts when those were not explicitly required ?

Even if there was a rationale for allowing template instantiation to instantiate with consts, then why, in that case, would be binding to rvalues forbidden? you can bind rvalues to const lvalue references. In that case, the template would be instantiated to f<const int>, and f(2) would be allowed.

I want to know the reasoning behind these decisions, not references to the standard.

Body:
Why is f(const int) allowed?

You might subsitute the template T by const int to transform T& into const int&

Even if there was a rationale for allowing template instantiation to instantiate with consts, then why, in that case, would be binding to rvalues forbidden?

There is no T (in T&) which (exact) matches int&& for deduction.

f<const int>(42) is allowed, but there is no deduction happening.

I want to know the reasoning behind these decisions, not references to the standard.

So why allowing cv substitution in template?

I would say it make generic programming easier.

Else you would have to provide overloads for each combination of const, volatile.

Here, if you want to restrict T to non const, you may use SFINAE with traits:

template <typename T> std::enable_if_t<!std::is_const<T>::value> f(T&);


问:
ActiveRecord finder method #where not filtering query results
TL;DR: Why am I receiving a list of all resident's when I'm using class methods to scope between active & inactive residents?

My application uses the 'acts_as_tenant' gem. The tenant model is called Account, which has many employees who manage residents.

```<code>class Account < ActiveRecord::Base
  before_create :set_subdomain

  has_one  :admin, class_name: 'Employee', foreign_key: :account_id,
    dependent: :destroy, inverse_of: :account

  has_many :employees, class_name: 'Employee', foreign_key: :account_id,
    dependent: :destroy, inverse_of: :account

  has_many :residents
  has_many :invites
  has_many :daily_summaries
  has_one  :subscription
  .
  .
  .
end
</code>```

In my resident's schema there is a flag attribute named is_active, it's purpose being to differentiate between active and soft-deleted residents. You can also see the db constraints added.

```<code>create_table :residents do |t|
  t.integer    :account_id, null: false
  t.integer    :employee_id, null: false
  t.boolean    :is_active, default: true, null: false
  .
  .
  .
end
</code>```

I allow employees to view soft-deleted residents & offer a tabbed index-view of both active/inactive residents.

In my Resident class I have the following class methods to scope based on active/inactive state.

```<code>  class Resident < ActiveRecord::Base
    acts_as_tenant(:account)
    .
    .
    .
    def self.inactive_count(current_account)
      where({ account_id: current_account.id, is_active: false }).count
    end

    def self.default(current_account)
      where({ account_id: current_account.id, is_active: true })
    end

    def self.inactive(current_account)
      # where({ account_id: current_account.id, is_active: false })
      where("account_id = ? AND is_active = ?", current_account.id, false).first
    end

    def archive
      update_attribute(:is_active, false)
    end
    .
    .
    .
  end
</code>```

My problem is that I am receiving a list of all residents in both the active and inactive tabs in my index-view. Note the last name is the same in both images of this view page.

I would prefer for the class method to only return active or inactive residents respectively.

I'm wanting to find out why I'm not receiving only active or only inactive residents based on my query class methods.

The class methods for active/inactive count appear to be working as expected, here is a peak.

```<code>  def index
   @inactive_residents = Resident.inactive(current_account)
   @inactive_resident_count = Resident.inactive_count(current_account)
   @active_residents = Resident.default(current_account)
   @active_resident_count = Resident.active_count(current_account)
  end
</code>```

My reading so far to solve:

Rails Guides - ActiveRecord querying

Rails scope returns all instead of nil

ActiveRecord::Relation

Server logs included to show SQL

View templates

index.html.erb

```<code>  <li class="active">
    <a href="#" data-toggle="tab">
      Active Residents
      <span class="badge badge-purple">
        <%= @active_resident_count %>
      </span>
    </a>
   </li>
   <li>
     <a href="#" data-toggle="tab">
       Inactive Residents
       <span class="badge badge-dark">
         <%= @inactive_resident_count %>
       </span>
     </a>
   </li>
</code>```

_active_residents.html.erb

```<code><% if @active_residents.any? %>
  <tbody>
    <% @active_residents.reverse_each do |resident| %>
      .
      .
      .
    <% end %>
  </tbody>
<% end %>
</code>```

_inactive_residents.html.erb

```<code><% unless @inactive_residents.nil? %>
  <% @inactive_residents.reverse_each do |resident| %>
    .
    .
    .
  <% end %>
<% end %>
</code>```

Update after comment

My logs are below, nothing changes in the log when I select the 'inactive' tab in the browser. I also don't see any output from js console in dev tools unless I set an option for verbose output. I will include an image of this also.

答: This could be a UI/jQuery issue. See if you are rendering the correct data under each tab. Since the count looks correct.</p>

Body:
TL;DR: Why am I receiving a list of all resident's when I'm using class methods to scope between active & inactive residents?

My application uses the 'acts_as_tenant' gem. The tenant model is called Account, which has many employees who manage residents.

class Account < ActiveRecord::Base
  before_create :set_subdomain

  has_one  :admin, class_name: 'Employee', foreign_key: :account_id,
    dependent: :destroy, inverse_of: :account

  has_many :employees, class_name: 'Employee', foreign_key: :account_id,
    dependent: :destroy, inverse_of: :account

  has_many :residents
  has_many :invites
  has_many :daily_summaries
  has_one  :subscription
  .
  .
  .
end

In my resident's schema there is a flag attribute named is_active, it's purpose being to differentiate between active and soft-deleted residents. You can also see the db constraints added.

create_table :residents do |t|
  t.integer    :account_id, null: false
  t.integer    :employee_id, null: false
  t.boolean    :is_active, default: true, null: false
  .
  .
  .
end

I allow employees to view soft-deleted residents & offer a tabbed index-view of both active/inactive residents.

In my Resident class I have the following class methods to scope based on active/inactive state.

  class Resident < ActiveRecord::Base
    acts_as_tenant(:account)
    .
    .
    .
    def self.inactive_count(current_account)
      where({ account_id: current_account.id, is_active: false }).count
    end

    def self.default(current_account)
      where({ account_id: current_account.id, is_active: true })
    end

    def self.inactive(current_account)
      # where({ account_id: current_account.id, is_active: false })
      where("account_id = ? AND is_active = ?", current_account.id, false).first
    end

    def archive
      update_attribute(:is_active, false)
    end
    .
    .
    .
  end

My problem is that I am receiving a list of all residents in both the active and inactive tabs in my index-view. Note the last name is the same in both images of this view page.

I would prefer for the class method to only return active or inactive residents respectively.

I'm wanting to find out why I'm not receiving only active or only inactive residents based on my query class methods.

The class methods for active/inactive count appear to be working as expected, here is a peak.

  def index
   @inactive_residents = Resident.inactive(current_account)
   @inactive_resident_count = Resident.inactive_count(current_account)
   @active_residents = Resident.default(current_account)
   @active_resident_count = Resident.active_count(current_account)
  end

My reading so far to solve:

Rails Guides - ActiveRecord querying

Rails scope returns all instead of nil

ActiveRecord::Relation

Server logs included to show SQL

View templates

index.html.erb

      Active Residents

        <%= @active_resident_count %>

       Inactive Residents

         <%= @inactive_resident_count %>

_active_residents.html.erb

<% if @active_residents.any? %>

    <% @active_residents.reverse_each do |resident| %>
      .
      .
      .
    <% end %>

<% end %>

_inactive_residents.html.erb

<% unless @inactive_residents.nil? %>
  <% @inactive_residents.reverse_each do |resident| %>
    .
    .
    .
  <% end %>
<% end %>

Update after comment

My logs are below, nothing changes in the log when I select the 'inactive' tab in the browser. I also don't see any output from js console in dev tools unless I set an option for verbose output. I will include an image of this also.


问:
Testing for a deadlock with nUnit
I'm new to unit testing and nUnit (2.48). I'd like to write a test method where the failure case is that it deadlocks. Is this possible? Obviously nUnit doesn't know by default how long the method should take to execute, so would I have to write code to do the work on a separate thread and then abort it and throw and exception if it took longer than some time I define? Is there a better way to do this?

Thank you

答:
Deadlock detection is equivalent to the halting problem, and therefore currently not solvable in the general case.

If you have a specific problem to guard against, there might be specific hacks to get at least a modicum of security. Be aware though, that this can only be a hack and never 100%. For example such a test might always pass on the development machine but never on the production machine.

OwnerDisplayName: frou

Title: Testing for a deadlock with nUnit

OwnerDisplayName: David Schmitt


问:
Software which makes UML diagrams from PHP scripts
I heard of software which can turn UML diagrams into different languages, like PHP, C++, etc.
But I can't find a tool which makes UML diagrams from PHP code.
Is there any? If not, why?!

Thanks!

答:
One of these tools is called ArgoUML http://argouml.tigris.org/.

PHP is included in the default-package since version 0.13.2 (March 2003).

If you're interested in some other languages like JavaScript, Python you can download a plugin on the project-homepage.

You can also create a uml-diagram out of your existing sourcecode. But I'm sorry - this is not avaiable for php-files.


问:
Why MySQL return column name with quotes?
i have this:

```<code>...
SELECT
    `id`,
    `name`,
    `user_id`,
    `xml_tables`
...
</code>```

and when making the query, I recive this:

```<code>+- ----+------+---------+------------+
| `id` | name | user_id | xml_tables |
+------+------+---------+------------+
|    1 | name |       1 |        xml |
+------+------+---------+------------+
</code>```

with the name of the ID column with quotes.

答:
I see you are calling a stored procedure. But you haven't shown the code in your procedure.

I tried to recreate the issue:

```<code>mysql> create procedure sp_read_database(in i int)
    -> begin
    -> select 123 as `id`, 'name' as `name`, 456 as `user_id`, 'xml tables' as `xml_tables`;
    -> end
</code>```

Then call the procedure in MySQL Workbench 6.3.9:

I don't see any back-ticks around the id column in the result grid.

I suspect your procedure contains some errant code formatting. I can reproduce your results if I add literal back-ticks to my column alias for id:

```<code>mysql> create procedure sp_read_database(in i int)
    -> begin
    -> select 123 as ```id```, 'name' as `name`, 456 as `user_id`, 'xml tables' as `xml_tables`;
    -> end
</code>```

Body:
i have this:

...
SELECT
    `id`,
    `name`,
    `user_id`,
    `xml_tables`
...

and when making the query, I recive this:

+- ----+------+---------+------------+
| `id` | name | user_id | xml_tables |
+------+------+---------+------------+
|    1 | name |       1 |        xml |
+------+------+---------+------------+

with the name of the ID column with quotes.

Body:
I see you are calling a stored procedure. But you haven't shown the code in your procedure.

I tried to recreate the issue:

mysql> create procedure sp_read_database(in i int)
    -> begin
    -> select 123 as `id`, 'name' as `name`, 456 as `user_id`, 'xml tables' as `xml_tables`;
    -> end

Then call the procedure in MySQL Workbench 6.3.9:

I don't see any back-ticks around the id column in the result grid.

I suspect your procedure contains some errant code formatting. I can reproduce your results if I add literal back-ticks to my column alias for id:

mysql> create procedure sp_read_database(in i int)
    -> begin
    -> select 123 as ```id```, 'name' as `name`, 456 as `user_id`, 'xml tables' as `xml_tables`;
    -> end


问:
Docker container can't write on host
First of all, I couldn't find the answer here on SO (this is the closest post).

I have EC2 running Ubuntu. First I installed Jenkins, and then Docker.
It's not "DonD".

My project has a Jenkinsfile, on that I'm running some docker commands.
It's supposed to use a docker container like gradle, share a volume and build the project.

The final .war will be on the host file system.

The problem is: the gradle inside the container can't write on host's folder.

Here's my Jenkinsfile (one of countless tries):

```<code>#!/usr/bin/groovy

node {
    checkout scm
    stage 'Gradle'

    sh 'sudo docker run --rm -v "$PWD":/api -w /api gradle gradle clean build --stacktrace'
}
</code>```

Stacktrace important line:

```<code>Caused by: org.gradle.api.UncheckedIOException: Failed to create parent directory '/api/.gradle' when creating directory '/api/.gradle/4.3/fileHashes'
</code>```

答:
Solved!

I logged into container using the -v argument:

```<code>$ docker exec -it -v "$PWD":/api -w /api gradle bash
</code>```

Then I tried to check the current user:

```<code>$ whoami
# gradle
</code>```

So, the solution is to run the container as root:

```<code>sh 'docker -u root run --rm -v "$PWD":/api -w /api gradle gradle clean build'
</code>```

This is the root of the container. Jenkins doesn't need root access.

Title: Docker container can't write on host

Body:
First of all, I couldn't find the answer here on SO (this is the closest post).

I have EC2 running Ubuntu. First I installed Jenkins, and then Docker.
It's not "DonD".

My project has a Jenkinsfile, on that I'm running some docker commands.
It's supposed to use a docker container like gradle, share a volume and build the project.

The final .war will be on the host file system.

The problem is: the gradle inside the container can't write on host's folder.

Here's my Jenkinsfile (one of countless tries):

#!/usr/bin/groovy

node {
    checkout scm
    stage 'Gradle'

    sh 'sudo docker run --rm -v "$PWD":/api -w /api gradle gradle clean build --stacktrace'
}

Stacktrace important line:

Caused by: org.gradle.api.UncheckedIOException: Failed to create parent directory '/api/.gradle' when creating directory '/api/.gradle/4.3/fileHashes'

Body:
Solved!

I logged into container using the -v argument:

$ docker exec -it -v "$PWD":/api -w /api gradle bash

Then I tried to check the current user:

$ whoami
# gradle

So, the solution is to run the container as root:

sh 'docker -u root run --rm -v "$PWD":/api -w /api gradle gradle clean build'

This is the root of the container. Jenkins doesn't need root access.


问:
Do server-side encrypted files in S3 get transitioned to AWS Glacier?
Question:
Do server-side encrypted (with S3 managed or KMS managed keys) files get transitioned to Glacier ?
If yes, are they decrypted using S3 or KMS key and then encrypted again using Glacier's internal key as all objects in Glacier are encrypted using an internal AES 256 keys ?

Problem statement:
I have some files in S3 encrypted using KMS managed key. I have a lifecycle rule to archive to Glacier after 1 day, but the files still show Storage class as 'Standard' even after 3 days.

答:
There is nothing in the documentation to suggest that storage class changes from lifecycle policies are incompatible with SSE-KMS.

On archive, S3 objects are moved as is (in SSE-KMS encrypted form) to Glacier, encrypted by Glacier again.
  View Thread RSS Feed View Thread RSS Feeds

— susan@aws https://forums.aws.amazon.com/thread.jspa?messageID=786916

S3 apparently does not decrypt and re-encrypt, but rather appears to simply encrypt the encrypted version of the object again, so SSE-C should also be compatible.

Note that lifecycle policies require between up to 24 hours before they actually begin transitioning objects, and new objects will match a "1 day" rule between 24 and 48 hours after the object's initial creation.

If there is a large number of objects, you might want to use aws-cli to try to see if any objects have migrated.

```<code>aws s3api list-objects [options] --output-format=text | grep GLACIER
</code>```

Body:
There is nothing in the documentation to suggest that storage class changes from lifecycle policies are incompatible with SSE-KMS.

On archive, S3 objects are moved as is (in SSE-KMS encrypted form) to Glacier, encrypted by Glacier again.
  View Thread RSS Feed View Thread RSS Feeds

— susan@aws https://forums.aws.amazon.com/thread.jspa?messageID=786916

S3 apparently does not decrypt and re-encrypt, but rather appears to simply encrypt the encrypted version of the object again, so SSE-C should also be compatible.

Note that lifecycle policies require between up to 24 hours before they actually begin transitioning objects, and new objects will match a "1 day" rule between 24 and 48 hours after the object's initial creation.

If there is a large number of objects, you might want to use aws-cli to try to see if any objects have migrated.

aws s3api list-objects [options] --output-format=text | grep GLACIER


问:
jq: Turn json object values into arrays
I have got the following array of objects (this is just an excerpt, also the objects are bigger):

```<code>[{
    "DATE": "10.10.2017 01:00",
    "ID": "X",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "X",
    "VALUE_ONE": 30,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "X",
    "VALUE_ONE": 25,
    "VALUE_TWO": 2
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Y",
    "VALUE_ONE": 10,
    "VALUE_TWO": 9
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Y",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Y",
    "VALUE_ONE": 50,
    "VALUE_TWO": 5
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Z",
    "VALUE_ONE": 55,
    "VALUE_TWO": 3
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Z",
    "VALUE_ONE": 60,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Z",
    "VALUE_ONE": 15,
    "VALUE_TWO": 7
  }
]
</code>```

To simplify this for a web application, and also to reduce file size, I would like to convert the "VALUE_ONE","VALUE_TWO" and "DATE" values to arrays for each "ID" just like this:

```<code>[{
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "X",
    "VALUE_ONE": [20, 30, 25],
    "VALUE_TWO": [5, 7, 2]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Y",
    "VALUE_ONE": [10, 20, 50],
    "VALUE_TWO": [9, 5, 5]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Z",
    "VALUE_ONE": [55, 60, 15],
    "VALUE_TWO": [3, 7, 7]
  }
]
</code>```

Here it is important that you need to be able find the values that are linked to a certain time (date). As the input values for "DATE" are consecutive, you most probably do not need the DATE value anymore to find the requested "VALUE.." value. You can probably just use the index of the array for that (index=0 is always 10.10.2017 01:00, index=1 is ... 02:00 etc.).
Is it possible to do it like that? This would keep the file size even smaller.
Thanks!

答:
If your data set is small enough, you could just group them up by id and map to the desired results. It won't be super efficient compared to a streaming solution, but will be the simplest to implement using builtins.</p>

```<code>group_by(.ID) | map({
    DATE: map(.DATE),
    ID: .[0].ID,
    VALUE_ONE: map(.VALUE_ONE),
    VALUE_TWO: map(.VALUE_TWO)
})
</code>```

Title: jq: Turn json object values into arrays

Body:
I have got the following array of objects (this is just an excerpt, also the objects are bigger):

[{
    "DATE": "10.10.2017 01:00",
    "ID": "X",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "X",
    "VALUE_ONE": 30,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "X",
    "VALUE_ONE": 25,
    "VALUE_TWO": 2
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Y",
    "VALUE_ONE": 10,
    "VALUE_TWO": 9
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Y",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Y",
    "VALUE_ONE": 50,
    "VALUE_TWO": 5
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Z",
    "VALUE_ONE": 55,
    "VALUE_TWO": 3
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Z",
    "VALUE_ONE": 60,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Z",
    "VALUE_ONE": 15,
    "VALUE_TWO": 7
  }
]

To simplify this for a web application, and also to reduce file size, I would like to convert the "VALUE_ONE","VALUE_TWO" and "DATE" values to arrays for each "ID" just like this:

[{
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "X",
    "VALUE_ONE": [20, 30, 25],
    "VALUE_TWO": [5, 7, 2]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Y",
    "VALUE_ONE": [10, 20, 50],
    "VALUE_TWO": [9, 5, 5]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Z",
    "VALUE_ONE": [55, 60, 15],
    "VALUE_TWO": [3, 7, 7]
  }
]

Here it is important that you need to be able find the values that are linked to a certain time (date). As the input values for "DATE" are consecutive, you most probably do not need the DATE value anymore to find the requested "VALUE.." value. You can probably just use the index of the array for that (index=0 is always 10.10.2017 01:00, index=1 is ... 02:00 etc.).
Is it possible to do it like that? This would keep the file size even smaller.
Thanks!

Body:
If your data set is small enough, you could just group them up by id and map to the desired results. It won't be super efficient compared to a streaming solution, but will be the simplest to implement using builtins.

group_by(.ID) | map({
    DATE: map(.DATE),
    ID: .[0].ID,
    VALUE_ONE: map(.VALUE_ONE),
    VALUE_TWO: map(.VALUE_TWO)
})


问:
Python Notebook - split Year and Month into 2 different columns
I have 1 column in my python notebook called Date. This contains 2017-05

I need to split this into 2 columns so one called Year and One MonthNo?

Code i have atm;

```<code>import calendar
from datetime import datetime

crimes['NewDate'] = crimes['Date'].apply(lambda x: datetime.strptime(x.split( [0], '%Y-%m'))

crimes['MonthNo'] = crimes['Date'].apply(lambda x: str(x.split()[0].split('-')[0]))

monthDict = {'01' : 'Jan', '02' : 'Feb', '03' : 'Mar', '04' : 'Apr', '05' : 'May', '06' : 'June', '07' : 'Jul', '08' : 'Aug', '09' : 'Sep', '10' : 'Oct', '11' : 'Nov', '12' : 'Dec' }

crimes['Month'] = crimes['MonthNo'].apply(lambda x: monthDict[x])
crimes.head()
</code>```

答:
You can split on the hyphen, then use the calendar module to get the month name or abbreviation directly.

```<code>import calendar
import pandas as pd

dates = ['2017-05','2017-04','2016-03']
crimes = pd.DataFrame()

years = [int(i.split('-')[0]) for i in dates]
months = [int(i.split('-')[1]) for i in dates]
month_names = [calendar.month_name[i] for i in months]

#Alternatively, use abbrv for abbreviation
#month_names = [calendar.month_abbr[i] for i in months]

crimes['Year'] = years
crimes['Month'] = month_names
</code>```

Body:
I have 1 column in my python notebook called Date. This contains 2017-05

I need to split this into 2 columns so one called Year and One MonthNo?

Code i have atm;

import calendar
from datetime import datetime

crimes['NewDate'] = crimes['Date'].apply(lambda x: datetime.strptime(x.split( [0], '%Y-%m'))

crimes['MonthNo'] = crimes['Date'].apply(lambda x: str(x.split()[0].split('-')[0]))

monthDict = {'01' : 'Jan', '02' : 'Feb', '03' : 'Mar', '04' : 'Apr', '05' : 'May', '06' : 'June', '07' : 'Jul', '08' : 'Aug', '09' : 'Sep', '10' : 'Oct', '11' : 'Nov', '12' : 'Dec' }

crimes['Month'] = crimes['MonthNo'].apply(lambda x: monthDict[x])
crimes.head()

Body:
You can split on the hyphen, then use the calendar module to get the month name or abbreviation directly.

import calendar
import pandas as pd

dates = ['2017-05','2017-04','2016-03']
crimes = pd.DataFrame()

years = [int(i.split('-')[0]) for i in dates]
months = [int(i.split('-')[1]) for i in dates]
month_names = [calendar.month_name[i] for i in months]

#Alternatively, use abbrv for abbreviation
#month_names = [calendar.month_abbr[i] for i in months]

crimes['Year'] = years
crimes['Month'] = month_names


问:
Call a nested function in Swift with a button
I'm trying to call retrieveData() when a user presses a button.

```<code>extension ViewController {

    func doOAuthFitbit2() {

        let oauthswift = OAuth2Swift(
            consumerKey:    "*****",
            consumerSecret: "*****",
            authorizeUrl:   "https://www.fitbit.com/oauth2/authorize",
            accessTokenUrl: "https://api.fitbit.com/oauth2/token",
            responseType:   "code"
        )

        oauthswift.accessTokenBasicAuthentification = true
        oauthswift.authorizeURLHandler = getURLHandler()
        let state = generateState(withLength: 20)

        let _ = oauthswift.authorize(
            withCallbackURL: URL(string: "smart://oauth-callback")!,
            scope: "profile nutrition",
            state: state,
            success: { credential, response, parameters in
                self.retrieveData(oauthswift)
        },
            failure: { error in
                print(error.description)
        }
        )
    }

    func retrieveData(_ oauthswift: OAuth2Swift) {
        print("retrieveData")
        let _ = oauthswift.client.get(
            "https://api.fitbit.com/1/user/-/profile.json",
            parameters: [:],
            success: { response in
                let jsonDict = try? response.jsonObject()
                print(jsonDict as Any)
        },
            failure: { error in
                print(error.description)
        }
        )
    }
}
</code>```

I have the following in ViewController.swift

```<code>@IBAction func btnRetrieveData(_ sender: Any) {
    retrieveData(oauthswift)
}
</code>```

I get the following error:

Cannot convert value of type 'OAuthSwift?' to expected argument type
  'OAuth2Swift'

Which I assume is because "oauthswift" is declared inside the doOAuthFitbit2() function.

Do I need to refactor the code so the retrieveData() function is nested inside the doOAuthFitbit2() function? how would I call that in ViewController.swift?

答:
Your oauthswift property is local to the doOAuthFitbit2() function, and thus you cannot access it from the button method (or any other method). I'd suggest to start with, you could add it as a global property that doOAuthFitbit2() updates, e.g.:

```<code>var oauthswift: OAuth2Swift!
// ^ declare global variable

func doOAuthFitbit2() {

    oauthswift = OAuth2Swift(
    // ^ reference the global variable and set it up here
        consumerKey:    "*****",
        consumerSecret: "*****",
        authorizeUrl:   "https://www.fitbit.com/oauth2/authorize",
        accessTokenUrl: "https://api.fitbit.com/oauth2/token",
        responseType:   "code"
    )

    oauthswift.accessTokenBasicAuthentification = true
    oauthswift.authorizeURLHandler = getURLHandler()
    let state = generateState(withLength: 20)

    let _ = oauthswift.authorize(
        withCallbackURL: URL(string: "smart://oauth-callback")!,
        scope: "profile nutrition",
        state: state,
        success: { credential, response, parameters in
            self.retrieveData(oauthswift)
    },
        failure: { error in
            print(error.description)
    }
    )
}
</code>```

You can then do:

```<code>func retrieveData() {
//                ^ you don't need to pass an arg here, since it's globally accessible
    print("retrieveData")
    let _ = oauthswift.client.get(
        "https://api.fitbit.com/1/user/-/profile.json",
        parameters: [:],
        success: { response in
            let jsonDict = try? response.jsonObject()
            print(jsonDict as Any)
    },
        failure: { error in
            print(error.description)
    }
    )
}
</code>```

That said, there are more stable ways of implementing this - like a shared instance (singleton) that can be accessed globally throughout the application, shared delegates/protocols, or the iOS keychain APIs. I won't get into those though - you'd need to do some learning and reading there.

Body:
I'm trying to call retrieveData() when a user presses a button.

extension ViewController {

    func doOAuthFitbit2() {

        let oauthswift = OAuth2Swift(
            consumerKey:    "*****",
            consumerSecret: "*****",
            authorizeUrl:   "https://www.fitbit.com/oauth2/authorize",
            accessTokenUrl: "https://api.fitbit.com/oauth2/token",
            responseType:   "code"
        )

        oauthswift.accessTokenBasicAuthentification = true
        oauthswift.authorizeURLHandler = getURLHandler()
        let state = generateState(withLength: 20)

        let _ = oauthswift.authorize(
            withCallbackURL: URL(string: "smart://oauth-callback")!,
            scope: "profile nutrition",
            state: state,
            success: { credential, response, parameters in
                self.retrieveData(oauthswift)
        },
            failure: { error in
                print(error.description)
        }
        )
    }

    func retrieveData(_ oauthswift: OAuth2Swift) {
        print("retrieveData")
        let _ = oauthswift.client.get(
            "https://api.fitbit.com/1/user/-/profile.json",
            parameters: [:],
            success: { response in
                let jsonDict = try? response.jsonObject()
                print(jsonDict as Any)
        },
            failure: { error in
                print(error.description)
        }
        )
    }
}

I have the following in ViewController.swift

@IBAction func btnRetrieveData(_ sender: Any) {
    retrieveData(oauthswift)
}

I get the following error:

Cannot convert value of type 'OAuthSwift?' to expected argument type
  'OAuth2Swift'

Which I assume is because "oauthswift" is declared inside the doOAuthFitbit2() function.

Do I need to refactor the code so the retrieveData() function is nested inside the doOAuthFitbit2() function? how would I call that in ViewController.swift?

Body:
Your oauthswift property is local to the doOAuthFitbit2() function, and thus you cannot access it from the button method (or any other method). I'd suggest to start with, you could add it as a global property that doOAuthFitbit2() updates, e.g.:

var oauthswift: OAuth2Swift!
// ^ declare global variable

func doOAuthFitbit2() {

    oauthswift = OAuth2Swift(
    // ^ reference the global variable and set it up here
        consumerKey:    "*****",
        consumerSecret: "*****",
        authorizeUrl:   "https://www.fitbit.com/oauth2/authorize",
        accessTokenUrl: "https://api.fitbit.com/oauth2/token",
        responseType:   "code"
    )

    oauthswift.accessTokenBasicAuthentification = true
    oauthswift.authorizeURLHandler = getURLHandler()
    let state = generateState(withLength: 20)

    let _ = oauthswift.authorize(
        withCallbackURL: URL(string: "smart://oauth-callback")!,
        scope: "profile nutrition",
        state: state,
        success: { credential, response, parameters in
            self.retrieveData(oauthswift)
    },
        failure: { error in
            print(error.description)
    }
    )
}

You can then do:

func retrieveData() {
//                ^ you don't need to pass an arg here, since it's globally accessible
    print("retrieveData")
    let _ = oauthswift.client.get(
        "https://api.fitbit.com/1/user/-/profile.json",
        parameters: [:],
        success: { response in
            let jsonDict = try? response.jsonObject()
            print(jsonDict as Any)
    },
        failure: { error in
            print(error.description)
    }
    )
}

That said, there are more stable ways of implementing this - like a shared instance (singleton) that can be accessed globally throughout the application, shared delegates/protocols, or the iOS keychain APIs. I won't get into those though - you'd need to do some learning and reading there.


问:
OpenVPN, ProxyRADIUS MS-CHAP and Windows AD
Trying to set up VPN authentication against different realms/windows domains.
I'm using OpenVPN Access Server which directs all authentication requests (username in the form of user@domain) to FreeRADIUS server (3.0.15) with required proxy.conf and realms config so that forwards (proxies) the access-request to home server. The OpenVPN is configured to use MS-CHAPv2.
The home server is also a freeRADIUS, same version. Home server is a member of windows domain (samba 4.6) and its clients.conf file includes the proxyRADIUS server as "NAS'....etc.
No issues on home server, when it comes to samba/winbind checks, etc. As a matter of facts, if I send requests from OpenVPN directly to it (without proxy), using username = sAMAccountName, authentication and group membership checks via LDAP work as expected.
However, if the request is proxied, the mschap module in home server reports:
(0) mschap: ERROR: Program returned code (1) and output 'Logon failure (0xc000006d)'
(0) mschap: External script failed
(0) mschap: ERROR: External script says: Logon failure (0xc000006d)
(0) mschap: ERROR: MS-CHAP2-Response is incorrect

(Outout above from radiusd in debug mode)

Just as a way of testing there was no issue with proxying the requests I enabled NPS on the domain controller and started proxying requests towards it and authentication worked with no issues, so, for whatever the reason, when home server tries to authenticate a proxied request the NT-Response (or at least as managed by mschap module) doesn't seem right.
I know there was a bug in an old version of samba about NT-Response, but I don't think that's the issue here, I think it got fixed a few years ago.
Has anyone come across a similar issue?
Thanks!
PS: Proxy and home RADIUS run in BSD 10.3

答: Fixed this. Realm definition in proxyRADIUS with "nostrip", so that user-stripped sent to home server includes user@domain. In home server, "proxy.conf" file, define the realm but with no server pool, so that the realm is treated as LOCAL but challenge is created using only the username (without @domain). That's it</p>


问:
securing passwords in code
Even with https enabled, you can write a password to the event log in code-behind.  Any way to keep that password encrypted in code while you're checking it against a data store?

(using Login control)

(couldn't add comment to Andrew's answer, so I'm putting it here)

NTLM uses the username/password of the machine the user is logged into right?  For this, I was thinking using ActiveDirectory on the server as the data store.  It would have a diferrent un/pw than what the user is currently signed in to their machine as.

答:
If you're sending a plain-text password in a form submission it is always available in the HttpContext object. It can't be removed or encrypted during the life of the page. The capability to store it is available the entire time until the finished page response is pushed out to the client. Even beyond that, the password is available in plaintext in memory and accessible through a hex editor (in RAM).

If you're concerned about password's being available in these fashions, you would be better served by enabling the NTLM authentication through Windows Integrated authentication which is hashed from bang to bullets.

Title: securing passwords in code


问:
I keep getting this error: Field 'api_token' doesn't have a default value in PHP Laravel 5.5
I'm new to laravel. Im trying to make an api. So if you register as a (auth)user, u'd be given an api_token for you to have an access to the dashboard
Here's some of my codes. And when I try to register it gives me this error:

Illuminate \ Database \ QueryException (HY000)
SQLSTATE[HY000]: General error: 1364 Field 'api_token' doesn't have a default value (SQL: insert into users (name, email, password, updated_at, created_at) values (goddies, f@gmail.com, $2y$10$uKJPI9hBJSdygMf7MefP1eM1GQ7VM3s74eVy5qcuFj4/s8HH2Iun., 2017-11-13 19:11:38, 2017-11-13 19:11:38))

On my migration for the user:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('api_token', 20)->unique();
        $table->rememberToken();
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('users');
}
</code>```

}

here's my user model:

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

protected $fillable = [
    'name', 'email', 'password', 'api_token',
];

protected $hidden = [
    'password', 'remember_token', 'api_token',
];
</code>```

}

答:
If you want to prevent this error, you need to set your column 'api_token' to nullable so it has a default value 'NULL' if there is no value coming from your request of 'api_token',

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('api_token', 20)->unique()->nulllable();
        $table->rememberToken();
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('users');
}
</code>```

Hope this helps :)

Body:
I'm new to laravel. Im trying to make an api. So if you register as a (auth)user, u'd be given an api_token for you to have an access to the dashboard
Here's some of my codes. And when I try to register it gives me this error:

Illuminate \ Database \ QueryException (HY000)
SQLSTATE[HY000]: General error: 1364 Field 'api_token' doesn't have a default value (SQL: insert into users (name, email, password, updated_at, created_at) values (goddies, f@gmail.com, $2y$10$uKJPI9hBJSdygMf7MefP1eM1GQ7VM3s74eVy5qcuFj4/s8HH2Iun., 2017-11-13 19:11:38, 2017-11-13 19:11:38))

On my migration for the user:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('api_token', 20)->unique();
        $table->rememberToken();
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('users');
}

}

here's my user model:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

protected $fillable = [
    'name', 'email', 'password', 'api_token',
];

protected $hidden = [
    'password', 'remember_token', 'api_token',
];

}

Body:
If you want to prevent this error, you need to set your column 'api_token' to nullable so it has a default value 'NULL' if there is no value coming from your request of 'api_token',

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('api_token', 20)->unique()->nulllable();
        $table->rememberToken();
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('users');
}

Hope this helps :)


问:
FBML + FBJS == XFBML?
I am trying to understand what exactly is the difference between fbml and xfbml! Is XFBML same as FBML combined with java script?</p>

答:
FBML is a facebook's propriety mark-up language, and originally all app views were static rendered in just FBML. Developers wanted to make their facebook app views more dynamic though, but they couldn't use javscript in FBML, so facebook created FBJS to allow developers to make their pages dynamic.

Later, they added support for iframe views, which originally were just HTML. Finally, they added support for embedding FBML tags in a regular document using XFBML. So using your analogy above, it's more like HTML + FBML = XFBML.

In any case, both static FBML and FBJS are both being deprecated any will eventually be removed entirely, so it would be a bad idea to use either of them. XFBML can still be rendered using the Facebook Javascript API, so it's not as bad an idea to use XFBML, but still not the best idea. Regular HTMl and javascript combined with the Facebook Javascript API can do everything XFBML can do, and it can do it more cleanly.

Title: FBML + FBJS == XFBML?


问:
Postgresql - select something where date = "01/01/11"
I have a datetime field in my Postgresql, named "dt".
I'd like to do something like

```<code>SELECT * FROM myTable WHERE extract (date from dt) = '01/01/11'
</code>```

What is the right syntax to do that?

Thanks!

答:
With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

```<code>SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';
</code>```

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

```<code>CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );
</code>```

One advantage of this is there is some more flexibility with timezones if required, for example:

```<code>CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';
</code>```

Body:
I have a datetime field in my Postgresql, named "dt".
I'd like to do something like

SELECT * FROM myTable WHERE extract (date from dt) = '01/01/11'

What is the right syntax to do that?

Thanks!

Body:
With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

ContentLicense: CC BY-SA 4.0


问:
User input not reflected properly in AJAX URL call
Trying to use user's city input (ex. Los Angeles) and include in Ajax URL parameters, however when I console.log(searchURL). It doesn't add a '+' between "los angels" thus breaking the URL. What can be done to make the URL include the + between cities with two words.

```<code>var apiKey = "&client_id=OTU3MDMwMHwxNTEwMjUwNDQ0LjI3"
var baseQueryURL = "https://api.seatgeek.com/2/events?" + apiKey;
console.log(baseQueryURL);

function runSearch(queryURL) {
  $.ajax({
      url: queryURL,
      method: 'GET'
    }).done(function(response) {
        console.log(response);
      };

      $("#submitSearch").on("click", function(event) {
        //prevents default event from occuring
        event.preventDefault();

        userCity = $("#userCity").val();
        console.log(userCity);
        //create variable queryCity to hold city queried with URL parameters
        var queryCity = "&venue.city=" + userCity;
        //create searchURL to pass in as queryURL in AJAX call
        searchURL = searchURL + queryCity;
        console.log(searchURL);
        runSearch(searchURL);
      });
</code>```

答:
I've used this:

userCity.split(" ").join("+")

Body:
Trying to use user's city input (ex. Los Angeles) and include in Ajax URL parameters, however when I console.log(searchURL). It doesn't add a '+' between "los angels" thus breaking the URL. What can be done to make the URL include the + between cities with two words.

var apiKey = "&client_id=OTU3MDMwMHwxNTEwMjUwNDQ0LjI3"
var baseQueryURL = "https://api.seatgeek.com/2/events?" + apiKey;
console.log(baseQueryURL);

function runSearch(queryURL) {
  $.ajax({
      url: queryURL,
      method: 'GET'
    }).done(function(response) {
        console.log(response);
      };

      $("#submitSearch").on("click", function(event) {
        //prevents default event from occuring
        event.preventDefault();

        userCity = $("#userCity").val();
        console.log(userCity);
        //create variable queryCity to hold city queried with URL parameters
        var queryCity = "&venue.city=" + userCity;
        //create searchURL to pass in as queryURL in AJAX call
        searchURL = searchURL + queryCity;
        console.log(searchURL);
        runSearch(searchURL);
      });


问:
how can i check if 2 lists have the same cyclic order in python?
```<code>def cyclic(lst1,lst2):
    a=lst1
    b=lst2
    if a == b:
        return True
    if a != b:
        return False
</code>```

Hi, I'm writing a function in Python which checks if 2 lists (lst1,lst2) have the same cyclic order. [if yes-the function returns True, if not-it returnes False].
I've already managed to check weather the lists are identical or not.
but i need to check the the cyclic order. for example:[0,1,2,3]
and [3,0,1,2] should return True, while [0,1,2,3] and [3,1,0,2] should return false.

thanks a lot!

答:
```<code>def cyclic(l1, l2):
    if len(l1) != len(l2):
        return False
    if not l1:
        return True
    a = l1[0]
    for i, x in enumerate(l2):
        if a == x:
            if l1 == l2[i:] + l2[:i]:
                return True
    return False
</code>```

Here we walk through the elements of l2 looking for elements that match l1[0].  When we find one, we rotate the list so that element is at the front, then compare the two lists.

Body:
def cyclic(lst1,lst2):
    a=lst1
    b=lst2
    if a == b:
        return True
    if a != b:
        return False

Hi, I'm writing a function in Python which checks if 2 lists (lst1,lst2) have the same cyclic order. [if yes-the function returns True, if not-it returnes False].
I've already managed to check weather the lists are identical or not.
but i need to check the the cyclic order. for example:[0,1,2,3]
and [3,0,1,2] should return True, while [0,1,2,3] and [3,1,0,2] should return false.

thanks a lot!

Body:
def cyclic(l1, l2):
    if len(l1) != len(l2):
        return False
    if not l1:
        return True
    a = l1[0]
    for i, x in enumerate(l2):
        if a == x:
            if l1 == l2[i:] + l2[:i]:
                return True
    return False

Here we walk through the elements of l2 looking for elements that match l1[0].  When we find one, we rotate the list so that element is at the front, then compare the two lists.


问:
Decorate JS object with boolean annotation
This is just a bit of fun here. Say we have this:

```<code>return {
  c: p.then(v => new Client(conf).ensure())
}
</code>```

I need to add a boolean to that, something like this:

```<code>return {
  inject: true
  c: p.then(v => new Client(conf).ensure())
}
</code>```

Is there some way in ESNext or typescript to decorate the returned object, something like so?

```<code>@inject
return {
  c: p.then(v => new Client(conf).ensure())
}
</code>```

how it works? something like this:

```<code>let addInjectProp = function(target){
   target['inject'] = true;
   return target;
}
</code>```

or something like that.

答:
I would just write a generic function and use it in place e.g </p>

```<code>function inject<T>(t: T): T & { inject: true } {
  return Object.assign({}, t, { inject: true as true });
}
</code>```

<p>Use : </p>

```<code>return inject({
  c: p.then(v => new Client(conf).ensure())
})
</code>```

Body:
This is just a bit of fun here. Say we have this:

return {
  c: p.then(v => new Client(conf).ensure())
}

I need to add a boolean to that, something like this:

return {
  inject: true
  c: p.then(v => new Client(conf).ensure())
}

Is there some way in ESNext or typescript to decorate the returned object, something like so?

@inject
return {
  c: p.then(v => new Client(conf).ensure())
}

how it works? something like this:

let addInjectProp = function(target){
   target['inject'] = true;
   return target;
}

or something like that.

Body:
I would just write a generic function and use it in place e.g

function inject<T>(t: T): T & { inject: true } {
  return Object.assign({}, t, { inject: true as true });
}

Use :

return inject({
  c: p.then(v => new Client(conf).ensure())
})


问:
How to push onto Promise.all(Array)
I don't think this is possible with the native promise implementation, but here's the basic idea of what I want:

```<code>const promises = [
    getSomething(),
    getSomethingElse(),
];

// combine promises
const alldone = Promise.all(promises);

// Add a promise after the previous ones have started
promises.push(getAThirdThing());

// everything, including `getAThirdThing` is done
await allDone;
</code>```

In reality Promise.all() doesn't care that I pushed something onto the promises array.

Is there a similar pattern which accomplishes the same thing? Specifically, adding other promises to wait for, as they become known to a list of currently unresolved promises, arbitrarily, and without any requirement that any be added later.

I could do something like this instead:

```<code>const promises = [
    getSomething(),
    getSomethingElse(),
];
const alldone = Promise.all(promises);
await Promise.all([alldone, getAThirdThing()]);
</code>```

But I want to call .then() on allDone prior to adding getAThirdThing().

答:
Promise.all returns a Promise itself, so you can call Promise.all consecutively:

```<code>let finished = Promise.all([...]);
finished = Promise.all([finished, someFunctionReturningAnotherPromise()]);
finished = Promise.all([finished, anotherFunctionReturningAPromise()]);
// etc...
// finally:
await finished;
</code>```

However, what you can't do is add to the Promise chain after awaiting the promise returned by Promise.all.

Also, things get a little tricky if in that scenario if you want to access the results of all the promises, as you'd end up with nested arrays of the results (which you could use something like lodash.flattenDeep to normalize them).

Title: How to push onto Promise.all(Array)

Body:
I don't think this is possible with the native promise implementation, but here's the basic idea of what I want:

const promises = [
    getSomething(),
    getSomethingElse(),
];

// combine promises
const alldone = Promise.all(promises);

// Add a promise after the previous ones have started
promises.push(getAThirdThing());

// everything, including `getAThirdThing` is done
await allDone;

In reality Promise.all() doesn't care that I pushed something onto the promises array.

Is there a similar pattern which accomplishes the same thing? Specifically, adding other promises to wait for, as they become known to a list of currently unresolved promises, arbitrarily, and without any requirement that any be added later.

I could do something like this instead:

const promises = [
    getSomething(),
    getSomethingElse(),
];
const alldone = Promise.all(promises);
await Promise.all([alldone, getAThirdThing()]);

But I want to call .then() on allDone prior to adding getAThirdThing().

Body:
Promise.all returns a Promise itself, so you can call Promise.all consecutively:

let finished = Promise.all([...]);
finished = Promise.all([finished, someFunctionReturningAnotherPromise()]);
finished = Promise.all([finished, anotherFunctionReturningAPromise()]);
// etc...
// finally:
await finished;

However, what you can't do is add to the Promise chain after awaiting the promise returned by Promise.all.

Also, things get a little tricky if in that scenario if you want to access the results of all the promises, as you'd end up with nested arrays of the results (which you could use something like lodash.flattenDeep to normalize them).


问:
Overflow:hidden not working as expected in Google Chrome
I'm having a problem with the "overflow: hidden" CSS property.

In Firefox, IE8 and Safari 5 when I apply this property to a div that is used for containing ad banners (like adsense leader boards or flash) at the top of my content there is still some overlap happening in Chrome when the window is resized to be small enough that they collide.

In Firefox and IE8 it works as expected and everything is completely hidden behind the right sidebar. In Chrome the actual content is hidden but it is replaced with a white background that still overlaps and blocks out the sidebar.

I have linked to a screenshot showing what the problem looks like. Is there anything I can do to fix this?!

http://tinypic.com/r/259cs95/7

答:
Likely there is some issue with your css or layout.

You could sidestep the issue by changing the z-index on your sidebar to be greater than the z-index of your ad, this would cause it to render above the add regardless. Make sure you define some value for position.


问:
Acumulated SUM of nodes/successors (Excel)
Trying to get an accumulated sum in column based on the sum successors(nodes) of that given node (for each predecesors), like the next image:

.

Where "Nod to SUM" is the description of which values to SUM.

Im looking if there is a more effective way than my forced solution (which cant scale up, cant get empty values and uses a semi-circular dependency), posted in the answers below.

答:
By far after days trying to make it work i was able to do it (with a main difference that when req column is not emply the result doesnt consider that row value to the SUM)

result

But with a really sturdy and fixed way like the following example:

```<code>=SUMPRODUCT(SUMIF(Mall[nod],O2:O27,$K$2:$K$11))+IF(Mall[@req]<>"",0,Mall[@[dist m]])
=SUMPRODUCT(SUMIF(Mall[nod],P2:P27,$K$2:$K$11))+IF(Mall[@req]<>"",0,Mall[@[dist m]])
</code>```

Where:

($K$2:$K$11) is the column containing the acumulated sums (the previous formula but different on each row based on the next criteria)

Criteria: (O2:O27 and P2:P27 are arrays "{ }" obtaining the nodes where the current node row appears like: for A:{B} or B:{C,RP1}
using ctrl shift enter.

=IFERROR(INDEX(Mall[nod],IFERROR(SMALL(IF(Mall[predecesor]=O1,ROW(Mall[predecesor])-1),ROW()-1),"")),"")

the problem here is when the table named "Mall" have emply rows the whole formula(sumproduct also [producing 0s at the search of nodes(O2:O27 P2:P27)]) doesnt work and returns 0 (at $K$2:$K$11).

Body:
By far after days trying to make it work i was able to do it (with a main difference that when req column is not emply the result doesnt consider that row value to the SUM)

result

But with a really sturdy and fixed way like the following example:

=SUMPRODUCT(SUMIF(Mall[nod],O2:O27,$K$2:$K$11))+IF(Mall[@req]<>"",0,Mall[@[dist m]])
=SUMPRODUCT(SUMIF(Mall[nod],P2:P27,$K$2:$K$11))+IF(Mall[@req]<>"",0,Mall[@[dist m]])

Where:

($K$2:$K$11) is the column containing the acumulated sums (the previous formula but different on each row based on the next criteria)

Criteria: (O2:O27 and P2:P27 are arrays "{ }" obtaining the nodes where the current node row appears like: for A:{B} or B:{C,RP1}
using ctrl shift enter.

=IFERROR(INDEX(Mall[nod],IFERROR(SMALL(IF(Mall[predecesor]=O1,ROW(Mall[predecesor])-1),ROW()-1),"")),"")

the problem here is when the table named "Mall" have emply rows the whole formula(sumproduct also [producing 0s at the search of nodes(O2:O27 P2:P27)]) doesnt work and returns 0 (at $K$2:$K$11).


问:
python3 pdb: how to repeat multiple commands
How do you repeat a multiple commands?

```<code>Multiple commands may be entered on a single line, separated by ;;.
[...]
Entering a blank line repeats the last command entered.
</code>```

I have already tried:

```<code>n ;; l
<ENTER>
</code>```

But only the list command would be repeated.

Sticking with pdb (no ipdb & co), would you know how to repeat effortlessly multiple commands?

Thanks !

答:
Well, the documentation https://docs.python.org/3/library/pdb.html says

Exception: if the last command was a list command, the next 11 lines
  are listed.

just right after

Entering a blank line repeats the last command entered

you've mentioned

In your expression

n;;l

as we can see the list command 'l' appears to be the last given command which directly hits the exception

I've faced the same problem and found some sort of a solution - we can simply repeat the last command n;;l by pressing up-arrow key and then enter, just like in terminal. Hope this helps.

Body:
How do you repeat a multiple commands?

Multiple commands may be entered on a single line, separated by ;;.
[...]
Entering a blank line repeats the last command entered.

I have already tried:

n ;; l
<ENTER>

But only the list command would be repeated.

Sticking with pdb (no ipdb & co), would you know how to repeat effortlessly multiple commands?

Thanks !


问:
Taking data from one worksheet and input it into another based on if two cells have the same value
I am trying to have this macro check the team name in a worksheet titled "Model", and then check in a worksheet titled "OffensiveStatsPerGame" and if these two have the same name it inputs a value into the worksheet titled "Model" that is one column over from the team name column where it first checked. The value I want it to input is on the "OffensiveStatsPerGame" worksheet 6 columns over from where it checked to see if the team names matched.

```<code>Sub findThreePointAttempted()

Dim x As Integer, z As Integer, i As Variant, j As Integer, ThreePointAttempts As Integer, toadd As Boolean

Worksheets("OffensiveStatsPerGame").Activate
x = Application.WorksheetFunction.CountA(Range("A1").EntireColumn)

Worksheets("Model").Activate
b = Application.WorksheetFunction.CountA(Range("A1").EntireColumn)

For i = 1 To b
    For j = 1 To x
        If Model.Cells(i, 0) = OffensiveStatsPerGame.Cells(j, 1) Then
            toadd = True
                If toadd = True Then
                    Worksheets("OffensiveStatsPerGame").Activate
                    ThreePointAttempts = OffensiveStatsPerGame.Cells(j, 1).Offset(0, 6)
                    Worksheets("Model").Activate
                    Model.Cells(i, 1) = ThreePointAttempts
                Else
                End If
        Else
        End If
    Next j
Next i

End Sub
</code>```

The code above is giving me a

Run Time error 424 : Object required

答:
You aren't setting "Model" to anything.  Since you are activating your "Model" sheet then you don't need to call that object.

Also, Cells(i, 0) doesn't exist since the lowest number a column can be is 1.  You need to change that number to the column number that you want to compare values to.

```<code>Sub findThreePointAttempted()

Dim x As Integer, i As Integer, b as Integer, j As Integer, ThreePointAttempts As Integer

Worksheets("OffensiveStatsPerGame").Activate
x = Application.WorksheetFunction.CountA(Range("A1").EntireColumn)

Worksheets("Model").Activate
b = Application.WorksheetFunction.CountA(Range("A1").EntireColumn)

For i = 1 To b
    For j = 1 To x
        ThreePointAttempts = Worksheets("OffensiveStatsPerGame").Cells(j, 1)
        If Cells(i, [change this value]) = ThreePointAttempts Then
             Cells(i, 1) = ThreePointAttempts
        Else
        End If
    Next j
Next i

End Sub
</code>```

Body:
I am trying to have this macro check the team name in a worksheet titled "Model", and then check in a worksheet titled "OffensiveStatsPerGame" and if these two have the same name it inputs a value into the worksheet titled "Model" that is one column over from the team name column where it first checked. The value I want it to input is on the "OffensiveStatsPerGame" worksheet 6 columns over from where it checked to see if the team names matched.

Sub findThreePointAttempted()

Dim x As Integer, z As Integer, i As Variant, j As Integer, ThreePointAttempts As Integer, toadd As Boolean

Worksheets("OffensiveStatsPerGame").Activate
x = Application.WorksheetFunction.CountA(Range("A1").EntireColumn)

Worksheets("Model").Activate
b = Application.WorksheetFunction.CountA(Range("A1").EntireColumn)

For i = 1 To b
    For j = 1 To x
        If Model.Cells(i, 0) = OffensiveStatsPerGame.Cells(j, 1) Then
            toadd = True
                If toadd = True Then
                    Worksheets("OffensiveStatsPerGame").Activate
                    ThreePointAttempts = OffensiveStatsPerGame.Cells(j, 1).Offset(0, 6)
                    Worksheets("Model").Activate
                    Model.Cells(i, 1) = ThreePointAttempts
                Else
                End If
        Else
        End If
    Next j
Next i

End Sub

The code above is giving me a

Run Time error 424 : Object required

Body:
You aren't setting "Model" to anything.  Since you are activating your "Model" sheet then you don't need to call that object.

Also, Cells(i, 0) doesn't exist since the lowest number a column can be is 1.  You need to change that number to the column number that you want to compare values to.

Sub findThreePointAttempted()

Dim x As Integer, i As Integer, b as Integer, j As Integer, ThreePointAttempts As Integer

Worksheets("OffensiveStatsPerGame").Activate
x = Application.WorksheetFunction.CountA(Range("A1").EntireColumn)

Worksheets("Model").Activate
b = Application.WorksheetFunction.CountA(Range("A1").EntireColumn)

For i = 1 To b
    For j = 1 To x
        ThreePointAttempts = Worksheets("OffensiveStatsPerGame").Cells(j, 1)
        If Cells(i, [change this value]) = ThreePointAttempts Then
             Cells(i, 1) = ThreePointAttempts
        Else
        End If
    Next j
Next i

End Sub


问:
Selenium error - Cannot navigate to invalid URL
I get the following error :

```<code>unknown error: unhandled inspector error:
{"code":-32603,"message":"Cannot navigate to
invalid URL"} (Session info: chrome=29.0.1547.57) (Driver info:
chromedriver=2.2,platform=Windows NT 6.1 SP1 x86_64)
</code>```

I think its got to do with chrome browser last updated version (29) about two days ago.

*Note:*my chromedriver is up to date (2.2).

please let me know what should i do to fix it.

答:
I had exactly the same error but it was due to a parsing issue in Python Behave BDD.

For example, if I have the following feature syntax

Given the user is on <page> using <url>

and my examples syntax has

```<code>Examples: Pages
    | page                    | url                           |
    | Mobile App using Guide  | https://www.example.com       |
</code>```

See how I have the word using between my variables in the given statement and also used using in the page title Mobile App using Guide. Because of this, the word Guide will get added on to the url and Selenium will return the invalid url error.

If you're using Behave or possibly any BDD with Gherkin syntax, avoid using the same keyword in between variables from the Given, When, Then statements in the Example table.

Body:
I get the following error :

unknown error: unhandled inspector error:
{"code":-32603,"message":"Cannot navigate to
invalid URL"} (Session info: chrome=29.0.1547.57) (Driver info:
chromedriver=2.2,platform=Windows NT 6.1 SP1 x86_64)

I think its got to do with chrome browser last updated version (29) about two days ago.

*Note:*my chromedriver is up to date (2.2).

please let me know what should i do to fix it.

Body:
I had exactly the same error but it was due to a parsing issue in Python Behave BDD.

For example, if I have the following feature syntax

Given the user is on <page> using <url>

and my examples syntax has

Examples: Pages
    | page                    | url                           |
    | Mobile App using Guide  | https://www.example.com       |

See how I have the word using between my variables in the given statement and also used using in the page title Mobile App using Guide. Because of this, the word Guide will get added on to the url and Selenium will return the invalid url error.

If you're using Behave or possibly any BDD with Gherkin syntax, avoid using the same keyword in between variables from the Given, When, Then statements in the Example table.


问:
Go HTTP Client adds chunked encoding which is not support by service
The go HTTP client is adding a "chunked" transfer encoding field to my client request.  Unfortunately, this is not supported by the service I'm connecting to and it comes back with an error.

Is there a way to disable this?

This is my Request code:

```<code>// DoHTTPRequest Do a full HTTP Client Request, with timeout
func DoHTTPRequest(method, url string, body io.Reader, headers map[string]string, timeout time.Duration) (*http.Response, error) {

    // Create the request
    req, err := http.NewRequest(method, url, body)
    if err != nil {
        return nil, err
    }

    // Add headers
    for k, v := range headers {
        req.Header.Set(k, v)
    }

    client := &http.Client{
        Timeout: timeout,
    }

    return client.Do(req)
}
</code>```

Basically I would like this header dropped.  This client is talking to S3 which is rather sensitive as to what headers it is sent.

I get this error:

```<code>A header you provided implies functionality that is not implemented
</code>```

答:
TransferEncoding is a field directly on the Request struct. If you set it explicitly it will not be overridden.

req.TransferEncoding = []string{"identity"}

https://golang.org/pkg/net/http/#Request

Body:
The go HTTP client is adding a "chunked" transfer encoding field to my client request.  Unfortunately, this is not supported by the service I'm connecting to and it comes back with an error.

Is there a way to disable this?

This is my Request code:

// DoHTTPRequest Do a full HTTP Client Request, with timeout
func DoHTTPRequest(method, url string, body io.Reader, headers map[string]string, timeout time.Duration) (*http.Response, error) {

    // Create the request
    req, err := http.NewRequest(method, url, body)
    if err != nil {
        return nil, err
    }

    // Add headers
    for k, v := range headers {
        req.Header.Set(k, v)
    }

    client := &http.Client{
        Timeout: timeout,
    }

    return client.Do(req)
}

Basically I would like this header dropped.  This client is talking to S3 which is rather sensitive as to what headers it is sent.

I get this error:

A header you provided implies functionality that is not implemented


问:
Google Glass: Is there anyway to cleanup the timeline
Google Glass makes it very easy for Glassware apps to 'liter' the timeline (especially with news items). Is there any easy way to clean/delete items you don't want?

Many of these items cannot be deleted, and the apps themselves (like Winkfeed for example) don't seem to have that feature. I know your OWN apps can delete their own items, but haven't found a way to delete/manage ALL the items on my timeline (including those created by other apps).

答:
How to delete your Google Glass timeline:
hook your Glass up to a Windows computer, get adb open a dos shell to run adb

```<code>start adb
type adb devices
type adb root
type adb shell
type cd /data/data/com.google.glass.sync/databases
type rm timeline.db
type rm timeline.db-shm
type rm timeline.db-wal
</code>```

reboot your Google Glass and it will recreate an empty timeline database

Body:
How to delete your Google Glass timeline:
hook your Glass up to a Windows computer, get adb open a dos shell to run adb

start adb
type adb devices
type adb root
type adb shell
type cd /data/data/com.google.glass.sync/databases
type rm timeline.db
type rm timeline.db-shm
type rm timeline.db-wal

reboot your Google Glass and it will recreate an empty timeline database