问:
256 bit fixed point arithmetic, the future?
Just some silly musings, but if computers were able to efficiently calculate 256 bit arithmetic, say if they had a 256 bit architecture, I reckon we'd be able to do away with floating point. I also wonder, if there'd be any reason to progress past 256 bit architecture? My basis for this is rather flimsy, but I'm confident that you'll put me straight if I'm wrong ;) Here's my thinking:

You could have a 256 bit type that used the 127 or 128 bits for integers, 127 or 128 bits for fractional values, and then of course a sign bit. If you had hardware that was capable of calculating, storing and moving such big numbers with no problems, I reckon you'd be set to handle any calculation you'd come across.

One example: If you were working with lengths, and you represented all values in meters, then the minimum value (2^-128 m) would be smaller than the planck length, and the biggest value (2^127 m) would be bigger than the diameter of the observable universe. Imagine calculating light-years of distances with a precision smaller than a planck length?

Ok, that's only one example, but I'm struggling to think of any situations that could possibly warrant bigger and smaller numbers than that. Any thoughts? Are there possible problems with fixed point arithmetic that I haven't considered? Are there issues with creating a 256 bit architecture?

答: 128 bit computers. It is also about addressing memory and when we run out 64-bits when addressing memory. Currently there are servers with 4TB memory. That requires about 42 bits (2^42 > 4 x 10^12). If we assume that memory prices halves every second year then we need one bit more every second year. We still have 22 bits left so at least 2 * 22 years and it is likely that memory prices are not dropping that fast -> more than 50 years when we run out of 64-bits addressing capabilities.</p>


来源: stackexchange

问:
(1/1) InvalidArgumentException Attribute [view] does not exist. Laravel 5.5
When I add the

```<code>Route::view('/', 'welcome');
</code>```

on web.php, I've encountered this error.

(1/1) InvalidArgumentException

```<code>Attribute [view] does not exist.
in RouteRegistrar.php (line 75)
at RouteRegistrar->attribute('view', '/')in Router.php (line 1098)
at Router->__call('view', array('/', 'welcome'))in Facade.php (line 221)
at Facade::__callStatic('view', array('/', 'welcome'))in web.php (line 20)
at require('C:\\wamp64\\www\\crystalcode\\routes\\web.php')in Router.php (line 327)
at Router->loadRoutes('C:\\wamp64\\www\\crystalcode\\routes/web.php')in Router.php (line 283)
at Router->group(array('middleware' => 'web', 'namespace' => 'App\\Http\\Controllers'), 'C:\\wamp64\\www\\crystalcode\\routes/web.php')in RouteRegistrar.php (line 104)
at RouteRegistrar->group('C:\\wamp64\\www\\crystalcode\\routes/web.php')in RouteServiceProvider.php (line 56)
at RouteServiceProvider->mapWebRoutes()in RouteServiceProvider.php (line 40)
at RouteServiceProvider->map()
at call_user_func_array(array(object(RouteServiceProvider), 'map'), array())in BoundMethod.php (line 29)
at BoundMethod::Illuminate\Container\{closure}()in BoundMethod.php (line 87)
at BoundMethod::callBoundMethod(object(Application), array(object(RouteServiceProvider), 'map'), object(Closure))in BoundMethod.php (line 31)
at BoundMethod::call(object(Application), array(object(RouteServiceProvider), 'map'), array(), null)in Container.php (line 539)
at Container->call(array(object(RouteServiceProvider), 'map'))in RouteServiceProvider.php (line 74)
at RouteServiceProvider->loadRoutes()in RouteServiceProvider.php (line 33)
at RouteServiceProvider->boot()in RouteServiceProvider.php (line 28)
at RouteServiceProvider->boot()
at call_user_func_array(array(object(RouteServiceProvider), 'boot'), array())in BoundMethod.php (line 29)
at BoundMethod::Illuminate\Container\{closure}()in BoundMethod.php (line 87)
at BoundMethod::callBoundMethod(object(Application), array(object(RouteServiceProvider), 'boot'), object(Closure))in BoundMethod.php (line 31)
at BoundMethod::call(object(Application), array(object(RouteServiceProvider), 'boot'), array(), null)in Container.php (line 539)
at Container->call(array(object(RouteServiceProvider), 'boot'))in Application.php (line 788)
at Application->bootProvider(object(RouteServiceProvider))in Application.php (line 771)
at Application->Illuminate\Foundation\{closure}(object(RouteServiceProvider), 17)
at array_walk(array(object(EventServiceProvider), object(LogServiceProvider), object(RoutingServiceProvider), object(AuthServiceProvider), object(CookieServiceProvider), object(DatabaseServiceProvider), object(EncryptionServiceProvider), object(FilesystemServiceProvider), object(FormRequestServiceProvider), object(FoundationServiceProvider), object(NotificationServiceProvider), object(PaginationServiceProvider), object(SessionServiceProvider), object(ViewServiceProvider), object(AppServiceProvider), object(AuthServiceProvider), object(EventServiceProvider), object(RouteServiceProvider)), object(Closure))in Application.php (line 772)
at Application->boot()in BootProviders.php (line 17)
at BootProviders->bootstrap(object(Application))in Application.php (line 208)
at Application->bootstrapWith(array('Illuminate\\Foundation\\Bootstrap\\LoadEnvironmentVariables', 'Illuminate\\Foundation\\Bootstrap\\LoadConfiguration', 'Illuminate\\Foundation\\Bootstrap\\HandleExceptions', 'Illuminate\\Foundation\\Bootstrap\\RegisterFacades', 'Illuminate\\Foundation\\Bootstrap\\RegisterProviders', 'Illuminate\\Foundation\\Bootstrap\\BootProviders'))in Kernel.php (line 162)
at Kernel->bootstrap()in Kernel.php (line 146)
at Kernel->sendRequestThroughRouter(object(Request))in Kernel.php (line 116)
at Kernel->handle(object(Request))in index.php (line 53)
</code>```

How to fix this issue, I'm beginner for the laravel please help me to set up this properly.

答:
This is a new feature in Laravel 5.5 - it's a shortcut for calling the Route::get method with a callback that calls your view as @rafik describes.

You are probably using a previous version of Laravel, but are reading about the Route::view() shortcut in the 5.5 documents.  It would actually be helpful if Laravel put a note next to new features telling since what version the feature has been available (see CakePHP documentation, php, etc).

So you need to either update your app (composer update) to the newer version of Laravel, or use a standard Route method (get, post, etc.) and call the view in a function.

ContentLicense: CC BY-SA 3.0

Body:
When I add the

Route::view('/', 'welcome');

on web.php, I've encountered this error.

(1/1) InvalidArgumentException

Attribute [view] does not exist.
in RouteRegistrar.php (line 75)
at RouteRegistrar->attribute('view', '/')in Router.php (line 1098)
at Router->__call('view', array('/', 'welcome'))in Facade.php (line 221)
at Facade::__callStatic('view', array('/', 'welcome'))in web.php (line 20)
at require('C:\\wamp64\\www\\crystalcode\\routes\\web.php')in Router.php (line 327)
at Router->loadRoutes('C:\\wamp64\\www\\crystalcode\\routes/web.php')in Router.php (line 283)
at Router->group(array('middleware' => 'web', 'namespace' => 'App\\Http\\Controllers'), 'C:\\wamp64\\www\\crystalcode\\routes/web.php')in RouteRegistrar.php (line 104)
at RouteRegistrar->group('C:\\wamp64\\www\\crystalcode\\routes/web.php')in RouteServiceProvider.php (line 56)
at RouteServiceProvider->mapWebRoutes()in RouteServiceProvider.php (line 40)
at RouteServiceProvider->map()
at call_user_func_array(array(object(RouteServiceProvider), 'map'), array())in BoundMethod.php (line 29)
at BoundMethod::Illuminate\Container\{closure}()in BoundMethod.php (line 87)
at BoundMethod::callBoundMethod(object(Application), array(object(RouteServiceProvider), 'map'), object(Closure))in BoundMethod.php (line 31)
at BoundMethod::call(object(Application), array(object(RouteServiceProvider), 'map'), array(), null)in Container.php (line 539)
at Container->call(array(object(RouteServiceProvider), 'map'))in RouteServiceProvider.php (line 74)
at RouteServiceProvider->loadRoutes()in RouteServiceProvider.php (line 33)
at RouteServiceProvider->boot()in RouteServiceProvider.php (line 28)
at RouteServiceProvider->boot()
at call_user_func_array(array(object(RouteServiceProvider), 'boot'), array())in BoundMethod.php (line 29)
at BoundMethod::Illuminate\Container\{closure}()in BoundMethod.php (line 87)
at BoundMethod::callBoundMethod(object(Application), array(object(RouteServiceProvider), 'boot'), object(Closure))in BoundMethod.php (line 31)
at BoundMethod::call(object(Application), array(object(RouteServiceProvider), 'boot'), array(), null)in Container.php (line 539)
at Container->call(array(object(RouteServiceProvider), 'boot'))in Application.php (line 788)
at Application->bootProvider(object(RouteServiceProvider))in Application.php (line 771)
at Application->Illuminate\Foundation\{closure}(object(RouteServiceProvider), 17)
at array_walk(array(object(EventServiceProvider), object(LogServiceProvider), object(RoutingServiceProvider), object(AuthServiceProvider), object(CookieServiceProvider), object(DatabaseServiceProvider), object(EncryptionServiceProvider), object(FilesystemServiceProvider), object(FormRequestServiceProvider), object(FoundationServiceProvider), object(NotificationServiceProvider), object(PaginationServiceProvider), object(SessionServiceProvider), object(ViewServiceProvider), object(AppServiceProvider), object(AuthServiceProvider), object(EventServiceProvider), object(RouteServiceProvider)), object(Closure))in Application.php (line 772)
at Application->boot()in BootProviders.php (line 17)
at BootProviders->bootstrap(object(Application))in Application.php (line 208)
at Application->bootstrapWith(array('Illuminate\\Foundation\\Bootstrap\\LoadEnvironmentVariables', 'Illuminate\\Foundation\\Bootstrap\\LoadConfiguration', 'Illuminate\\Foundation\\Bootstrap\\HandleExceptions', 'Illuminate\\Foundation\\Bootstrap\\RegisterFacades', 'Illuminate\\Foundation\\Bootstrap\\RegisterProviders', 'Illuminate\\Foundation\\Bootstrap\\BootProviders'))in Kernel.php (line 162)
at Kernel->bootstrap()in Kernel.php (line 146)
at Kernel->sendRequestThroughRouter(object(Request))in Kernel.php (line 116)
at Kernel->handle(object(Request))in index.php (line 53)

How to fix this issue, I'm beginner for the laravel please help me to set up this properly.


问:
Can't figure out the cause of BAD_ACCESS error?
When trying to initialize this vector with "Cell"'s, a bad access error keeps getting thrown at

```<code>grid.emplace_back(Cell{1,false, row,col});
</code>```

And I can't seem to figure out why. After some googling I believe it has something to do with memory getting dereferenced or lost, but can't seem to figure out where exactly this is happening. Any help would be immensely appreciated. Thanks.

```<code>struct Cell{
    int cellVal;
    bool visited;
    int xPos;
    int yPos;
};
vector<vector<Cell>> grid;
vector<Cell> path(15);

vector<Cell> monsterPath(15);
int main() {

    grid.reserve(15);
    for(int row = 0; row <=1; row++){
        for(int col = 0; col <=15; col++){
            grid[col].reserve(15);
            grid.emplace_back(Cell{1,false,row,col});
        }
    }
</code>```

Thanks to @user0042 the above code segment no longer throws the bad access error. However, my next code segments throws the exact same error, specifically the first line in the if statement.

```<code>if((!grid[path[curX].xPos - 1][path[curX].yPos].visited) &&       //cell being checked is (x-1, y)
               !grid[path[path.size() - 1].xPos - 1][path[path.size() - 1].yPos - 1].visited &&              //check cell x-1, y-1
               !grid[path[path.size() - 1].xPos - 2][path[path.size() - 1].yPos].visited &&                  //check cell x-2, y
               !grid[path[path.size() - 1].xPos][path[path.size() + 1].yPos + 1].visited)                //check cell x, y+1
            {
                grid[path[path.size()-1].xPos - 1][path[path.size()-1].yPos].cellVal = 0;
                grid[path[path.size()-1].xPos - 1][path[path.size()-1].yPos].visited = true;
                path.emplace_back((grid[path[path.size()-1].xPos - 1][path[path.size()-1].yPos]));
                cout << "path constructed" << endl;

            }
</code>```

答:
The line

for(int col = 0; col <=15; col++)

seems wrong, as the highest element you can index is 14, not 15. You should replace the <= with a <.

For your other piece of code, I don't know what's the content of curX, xPos, curY and yPos, but make sure they are not bigger then your array size - 1.

Body:
When trying to initialize this vector with "Cell"'s, a bad access error keeps getting thrown at

grid.emplace_back(Cell{1,false, row,col});

And I can't seem to figure out why. After some googling I believe it has something to do with memory getting dereferenced or lost, but can't seem to figure out where exactly this is happening. Any help would be immensely appreciated. Thanks.

struct Cell{
    int cellVal;
    bool visited;
    int xPos;
    int yPos;
};
vector<vector<Cell>> grid;
vector<Cell> path(15);

vector<Cell> monsterPath(15);
int main() {

    grid.reserve(15);
    for(int row = 0; row <=1; row++){
        for(int col = 0; col <=15; col++){
            grid[col].reserve(15);
            grid.emplace_back(Cell{1,false,row,col});
        }
    }

Thanks to @user0042 the above code segment no longer throws the bad access error. However, my next code segments throws the exact same error, specifically the first line in the if statement.

if((!grid[path[curX].xPos - 1][path[curX].yPos].visited) &&       //cell being checked is (x-1, y)
               !grid[path[path.size() - 1].xPos - 1][path[path.size() - 1].yPos - 1].visited &&              //check cell x-1, y-1
               !grid[path[path.size() - 1].xPos - 2][path[path.size() - 1].yPos].visited &&                  //check cell x-2, y
               !grid[path[path.size() - 1].xPos][path[path.size() + 1].yPos + 1].visited)                //check cell x, y+1
            {
                grid[path[path.size()-1].xPos - 1][path[path.size()-1].yPos].cellVal = 0;
                grid[path[path.size()-1].xPos - 1][path[path.size()-1].yPos].visited = true;
                path.emplace_back((grid[path[path.size()-1].xPos - 1][path[path.size()-1].yPos]));
                cout << "path constructed" << endl;

            }


问:
Advantages of UI component libraries like Bootstrap-Vue and React-Bootstrap
What are the benefits of using a framework like Bootstrap-Vue as opposed to regular bootstrap?

Is it in order to remove jQuery dependency?

答:
Bootstrap Vue removes jQuery from the picture and replaces it with Vue.

The benefit is as simple as it is integrated with Vue if you are using it already. No need to add the extra overhead of jQuery if you are already using Vue.


问:
IN SVG can I animate many objects (64) with different start times without having to create 64 different animations??
I know that the  tag with xlink:href can run the same animation in many different positions and at different scales, angles, opacities, etc. But can I alter either the START time or DURATION of an xlinked instance of an animation?

I want a 10 x 10 grid of squares to drop off of the screen in sequence, one starting at 0s, one at 0.1s, one at 0.2s, etc. I can't see how to do this without creating 100 animations, all identical except for the start times! Is there a reasonably efficient way to do this in pure SVG? Or do I have to learn and introduce some JavaScript? Thanks!

答:
In general, the answer is no. Cloned elements are not independent of the element they are referenced against. Just the oposite, the rendered content of a <use> element has to reflect all life changes to the referenced element, including all animations.

The answer remains true for both SMIL and CSS animations. Now you might know that the rendered content can differ if the <use> element has a style rule that can be inherited by that content. (Like the fill in the example below.) So what would happen if you defined the CSS animation on the referenced source element and then set a differnt animation-delay style rule for every <use>? The animations would still start at the same time, animation-delay is not inheritable.

For the animation you describe, there is a halfway decent solution using CSS animations. Your cloned element is inert and only has to move around as a whole. Therefore it is enough to animate the <use> element itself. Now the technique hinted at above works:

.dropping {
  animation: drop 2s forwards;
}
@keyframes drop {
  from {
    transform: translate(0px, 0px);
  }
  to {
    transform: translate(0px, 300px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="250" height="300">
<symbol id="drop">
  <rect width="50" height="50" />
</symbol>
<use class="dropping" xlink:href="#drop" x="0" style="animation-delay:0s;fill:rgb(255, 0, 0);" />
<use class="dropping" xlink:href="#drop" x="50" style="animation-delay:0.5s;fill:orange;" />
<use class="dropping" xlink:href="#drop" x="100" style="animation-delay:1s;fill:yellow;" />
<use class="dropping" xlink:href="#drop" x="150" style="animation-delay:1.5s;fill:green;" />
<use class="dropping" xlink:href="#drop" x="200" style="animation-delay:2s;fill:blue;" />
</svg></code>```

Body:
In general, the answer is no. Cloned elements are not independent of the element they are referenced against. Just the oposite, the rendered content of a <use> element has to reflect all life changes to the referenced element, including all animations.

The answer remains true for both SMIL and CSS animations. Now you might know that the rendered content can differ if the <use> element has a style rule that can be inherited by that content. (Like the fill in the example below.) So what would happen if you defined the CSS animation on the referenced source element and then set a differnt animation-delay style rule for every <use>? The animations would still start at the same time, animation-delay is not inheritable.

For the animation you describe, there is a halfway decent solution using CSS animations. Your cloned element is inert and only has to move around as a whole. Therefore it is enough to animate the <use> element itself. Now the technique hinted at above works:

.dropping {
  animation: drop 2s forwards;
}
@keyframes drop {
  from {
    transform: translate(0px, 0px);
  }
  to {
    transform: translate(0px, 300px);
  }
}

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="250" height="300">
<symbol id="drop">
  <rect width="50" height="50" />
</symbol>
<use class="dropping" xlink:href="#drop" x="0" style="animation-delay:0s;fill:rgb(255, 0, 0);" />
<use class="dropping" xlink:href="#drop" x="50" style="animation-delay:0.5s;fill:orange;" />
<use class="dropping" xlink:href="#drop" x="100" style="animation-delay:1s;fill:yellow;" />
<use class="dropping" xlink:href="#drop" x="150" style="animation-delay:1.5s;fill:green;" />
<use class="dropping" xlink:href="#drop" x="200" style="animation-delay:2s;fill:blue;" />
</svg>


问:
Pandas iterrows get row string as list
I have a df in pandas which looks like:

```<code>id  name  values

1    a    cat dog
2    b    bird fly
</code>```

I'm currently doing:

```<code>for index, row in df.iterrows():
     print row["values"]
</code>```

However, that prints the entire cell: "cat dog" or "bird fly".

I've tried doing:

```<code>print row["values"][0]
</code>```

That instead prints a single character, so "c" and "b".

How can I get instead something like ["cat", "dog"] and ["bird", "fly"]

答:
Like this:

```<code>for index, row in df.iterrows():
     print(row["values"].split())
</code>```

Output:

```<code>['cat', 'dog']
['bird', 'fly']
</code>```

Title: Pandas iterrows get row string as list

Body:
I have a df in pandas which looks like:

id  name  values

1    a    cat dog
2    b    bird fly

I'm currently doing:

for index, row in df.iterrows():
     print row["values"]

However, that prints the entire cell: "cat dog" or "bird fly".

I've tried doing:

print row["values"][0]

That instead prints a single character, so "c" and "b".

How can I get instead something like ["cat", "dog"] and ["bird", "fly"]

Body:
Like this:

for index, row in df.iterrows():
     print(row["values"].split())

Output:

['cat', 'dog']
['bird', 'fly']


问:
Can't populate a TableView with Jruby/Jrubyfx
I'm trying to make a Jruby app with a TableView but I haven't been able to populate the table with data or even find some sample code to do so. Here's the relevant part of my fxml:

<TableView prefHeight="400.0" prefWidth="200.0" id="table">
  <columns>
    <TableColumn prefWidth="75.0" text="name">
      <cellValueFactory>
        <PropertyValueFactory property="name" />
      </cellValueFactory>
    </TableColumn>
    <TableColumn prefWidth="75.0" text="address">
      <cellValueFactory>
        <PropertyValueFactory property="address" />
      </cellValueFactory>
    </TableColumn>
  </columns>
</TableView>
```

<p>And here's the relevant ruby code:</p>

<pre class="lang-ruby prettyprint-override"><code>class Person
  attr_accessor :name, :address

  def initialize
    @name = 'foo'
    @address = 'bar'
  end
end

class HelloWorldApp < JRubyFX::Application
  def start(stage)
    with(stage, title: "Hello World!", width: 800, height: 600) do
      fxml HelloWorldController
      @data = observable_array_list
      @data.add Person.new
      stage['#table'].set_items @data
      show
    end
  end
end
</code>```

Can someone suggest what I'm doing wrong or point me to a working sample code?

答:
See the contrib/fxmltableview sample; I think that is exactly what you want to do. The issue you are running into is the fact that PropertyValueFactory is a Java class, and it is trying to access a Person which is a JRuby class. By default this won't work as this question shows, but you can easily fix that by calling Person.become_java!. However, even if you do that, it won't work as the PropertyValueFactory expects getter methods of the form [javatype] get[PropertyName]() whereas attr_accessor only generates getter methods of the form [rubytype] [propertyname](). To solve this, use fxml_accessor instead, which generates the proper methods (but doesn't use @ vars, those are the raw property instances):

class Person
  include JRubyFX # gain access to fxml_accessor
  # must specify type as the concrete `Property` implementation
  fxml_accessor :name, SimpleStringProperty
  fxml_accessor :address, SimpleStringProperty

  def initialize
    # note use of self to call the method Person#name= instead of creating local variable
    self.name = 'foo'
    self.address = 'bar'
    # could also technically use @address.setValue('bar'), but that isn't as rubyish
  end
end

# become_java! is needed whenever you pass JRuby objects to java classes
# that try to call methods on them, such as this case. If you used your own
# cellValueFactory, this probably would not be necessary on person, but still
# needed on your CVF
Person.become_java!
```

Body:
I'm trying to make a Jruby app with a TableView but I haven't been able to populate the table with data or even find some sample code to do so. Here's the relevant part of my fxml:

<TableView prefHeight="400.0" prefWidth="200.0" id="table">
  <columns>
    <TableColumn prefWidth="75.0" text="name">
      <cellValueFactory>
        <PropertyValueFactory property="name" />
      </cellValueFactory>
    </TableColumn>
    <TableColumn prefWidth="75.0" text="address">
      <cellValueFactory>
        <PropertyValueFactory property="address" />
      </cellValueFactory>
    </TableColumn>
  </columns>
</TableView>

And here's the relevant ruby code:

class Person
  attr_accessor :name, :address

  def initialize
    @name = 'foo'
    @address = 'bar'
  end
end

class HelloWorldApp < JRubyFX::Application
  def start(stage)
    with(stage, title: "Hello World!", width: 800, height: 600) do
      fxml HelloWorldController
      @data = observable_array_list
      @data.add Person.new
      stage['#table'].set_items @data
      show
    end
  end
end

Can someone suggest what I'm doing wrong or point me to a working sample code?


问:
Express 4: How to catch param in dynamic route structured like file name?
I'm trying to use Express 4 route endpoint that has part of the route in the file URL part - file name. It's used for dynamic generated image. I think it's best described by example...

What I have right now

Right now I have something like this in my routes:

app.get('/api/listing/:id/cover.png', viewListingImage)

And e.g. this URL http://localhost:9500/api/listing/750/cover.png matches listing with id 750.

Expectations

What I would like to have is URL which last part is a filename with listing id in it. So I can quickly save it locally with that filename. E.g.

http://localhost:9540/api/listing/750-cover.png

So basically, I'd like to just replace forward slash with a hyphen.

Tried some RegEx magic, but had not luck. Thanks for any help!

答:
You can use a regex in the route:

```<code>const app = require('express')();

// match /api/listing/ddd-filename
// where ddd is a series of digits
app.get(/\/api\/listing\/(\d+)-([^\/]+)/, function(req, res) {
    console.log(req.params);
    res.send("hello");
});

app.listen(80);
</code>```

Then, if you request a URL such as /api/listing/20-cover.png, you will find that in the request handler:

```<code>req.params[0] === '20'
req.params[1] === 'cover.png';
</code>```

Capture groups in the regex are put into req.params as described here.

As I said in my comments, you could also just do:

```<code>app.get('/api/listing/:filename', function(req, res) {
    // parse req.params.filename yourself here
});
</code>```

Body:
You can use a regex in the route:

const app = require('express')();

// match /api/listing/ddd-filename
// where ddd is a series of digits
app.get(/\/api\/listing\/(\d+)-([^\/]+)/, function(req, res) {
    console.log(req.params);
    res.send("hello");
});

app.listen(80);

Then, if you request a URL such as /api/listing/20-cover.png, you will find that in the request handler:

req.params[0] === '20'
req.params[1] === 'cover.png';

Capture groups in the regex are put into req.params as described here.

As I said in my comments, you could also just do:

app.get('/api/listing/:filename', function(req, res) {
    // parse req.params.filename yourself here
});


问:
Styling Vue Slot
Is there any way to style a slot in a Vue component?

```<code><slot style="position: absolute"></slot>
</code>```

and

```<code><slot class="slot"></slot>
</code>```

do not work.

答:
Wrap the slot in a
 and style the
 instead:

```<code><div style="...">
  <slot></slot>
</div>
</code>```

If you really need to style the slot element, you can use CSS selectors like this:

```<code><div class="wrapper">
  <slot></slot>
</div>
</code>```

```<code>.wrapper > * {
  color: red;
}
</code>```

Title: Styling Vue Slot

Body:
Is there any way to style a slot in a Vue component?

<slot style="position: absolute"></slot>

and

<slot class="slot"></slot>

do not work.

Body:
Wrap the slot in a <div> and style the <div> instead:

<div style="...">
  <slot></slot>
</div>

If you really need to style the slot element, you can use CSS selectors like this:

<div class="wrapper">
  <slot></slot>
</div>

.wrapper > * {
  color: red;
}


问:
VBScript RegExp with Characters + or -
I cannot seem to figure this out. I need the below to spit out "Market Value"</p>

```<code>Function removeScenarioTags (strtoclean)
    Dim objRegExp, outputStr
    Set objRegExp = New Regexp

    objRegExp.IgnoreCase = True
    objRegExp.Global     = True
    objRegExp.Pattern    = " ?\([0-9a-zA-Z ]+\) ?"

    Set objMatch  = objRegExp.Execute( strtoclean )
    corrected_row = strtoclean
    For Each myMatch in objMatch
        matched_value  = myMatch.Value
        corrected_row  = replace(corrected_row, matched_value, "")
    Next
    removeScenarioTags = corrected_row
End Function

'----------------MAIN------------------------------------------

after_clean = removeScenarioTags("Market Value (steep+50)")
msgbox after_clean
</code>```

答:
You need to add the + to the character class:

```<code>objRegExp.Pattern = " ?\([0-9a-zA-Z+]+\) ?"
</code>```

See a demo on regex101.com.

Title: VBScript RegExp with Characters + or -

Body:
I cannot seem to figure this out. I need the below to spit out "Market Value"

Function removeScenarioTags (strtoclean)
    Dim objRegExp, outputStr
    Set objRegExp = New Regexp

    objRegExp.IgnoreCase = True
    objRegExp.Global     = True
    objRegExp.Pattern    = " ?\([0-9a-zA-Z ]+\) ?"

    Set objMatch  = objRegExp.Execute( strtoclean )
    corrected_row = strtoclean
    For Each myMatch in objMatch
        matched_value  = myMatch.Value
        corrected_row  = replace(corrected_row, matched_value, "")
    Next
    removeScenarioTags = corrected_row
End Function

'----------------MAIN------------------------------------------

after_clean = removeScenarioTags("Market Value (steep+50)")
msgbox after_clean

Body:
You need to add the + to the character class:

objRegExp.Pattern = " ?\([0-9a-zA-Z+]+\) ?"

See a demo on regex101.com.


问:
Haskell >>= operation: why is the function argument required to return another Monad?
Considering the expression:

```<code>[0,1..] >>= \i -> [i * 2]
</code>```

In the definition of >>= for List, the lambda function \i -> [i * 2] is mapped over the list argument via fmap, resulting in a list of lists, [[0], [2]..]. So >>= needs to flatten the result using a join function in order to return the list: [0, 2..]

According to this source: "...the definition of bind in terms of fmap and join works for every monad m: ma >>= k = join $ fmap k ma"

So why is it necessary to place the burden of returning a monad on the function supplied to >>=? Why not simply define bind like so?

```<code>ma >>= k = fmap k ma
</code>```

This way you don't have to deal with flattening the result.

答:
A major feature of a monad is to be able to "flatten" (join). This is necessary to define a nice form of composition.

Consider the composition of two functions with side effects, say in the IO monad:

```<code>foo :: A -> IO B
bar :: B -> IO C
</code>```

If >>= was only fmap (without the final join) pass, the composition

```<code>\a -> foo a >>= bar
</code>```

would mean

```<code>\a -> fmap bar (foo a)
-- i.e.
fmap bar . foo
</code>```

which does look as a nice composition, but unfortunately has type A -> IO (IO C) ! If we can't flatten the nested IO, every composition would add yet another layer, and we would end up with result types of the form IO (IO (IO ...)) showing the number of compositions.

At best, this would be inconvenient. At worst, this would prevent recursion such as

```<code>loop = readLn >>= \x -> print x >>= \_ -> loop
</code>```

since it leads to a type with an infinite nesting of IO.

Body:
Considering the expression:

[0,1..] >>= \i -> [i * 2]

In the definition of >>= for List, the lambda function \i -> [i * 2] is mapped over the list argument via fmap, resulting in a list of lists, [[0], [2]..]. So >>= needs to flatten the result using a join function in order to return the list: [0, 2..]

According to this source: "...the definition of bind in terms of fmap and join works for every monad m: ma >>= k = join $ fmap k ma"

So why is it necessary to place the burden of returning a monad on the function supplied to >>=? Why not simply define bind like so?

ma >>= k = fmap k ma

This way you don't have to deal with flattening the result.

Body:
A major feature of a monad is to be able to "flatten" (join). This is necessary to define a nice form of composition.

Consider the composition of two functions with side effects, say in the IO monad:

foo :: A -> IO B
bar :: B -> IO C

If >>= was only fmap (without the final join) pass, the composition

\a -> foo a >>= bar

would mean

\a -> fmap bar (foo a)
-- i.e.
fmap bar . foo

which does look as a nice composition, but unfortunately has type A -> IO (IO C) ! If we can't flatten the nested IO, every composition would add yet another layer, and we would end up with result types of the form IO (IO (IO ...)) showing the number of compositions.

At best, this would be inconvenient. At worst, this would prevent recursion such as

loop = readLn >>= \x -> print x >>= \_ -> loop

since it leads to a type with an infinite nesting of IO.


答:
You may simplify the regex based replacement by using a regex that matches parentheses with any chars inside other than parentheses, enclosed with 0+ whitespaces, and remove the match with RegExp.Replace method directly:

```<code>Function removeScenarioTags(strtoclean)
    Dim objRegExp, outputStr
    Set objRegExp = New Regexp

    objRegExp.IgnoreCase = True
    objRegExp.Global = True
    objRegExp.Pattern = "\s*\([^()]+\)\s*"

    removeScenarioTags = objRegExp.Replace(strtoclean, "")
End Function
</code>```

See the \s*\([^()]+\)\s* regex demo.

Details

\s* - 0+ whitespaces

\( - a (

[^()]+ - 1 or more (replace with * to match 0 or more) chars other than ( and )

\) - a )

\s*- 0+ whitespaces

Note that with this regex, objRegExp.IgnoreCase = True does not do anything meaningful and can be removed.

Title: VBScript RegExp with Characters + or -

Body:
You may simplify the regex based replacement by using a regex that matches parentheses with any chars inside other than parentheses, enclosed with 0+ whitespaces, and remove the match with RegExp.Replace method directly:

Function removeScenarioTags(strtoclean)
    Dim objRegExp, outputStr
    Set objRegExp = New Regexp

    objRegExp.IgnoreCase = True
    objRegExp.Global = True
    objRegExp.Pattern = "\s*\([^()]+\)\s*"

    removeScenarioTags = objRegExp.Replace(strtoclean, "")
End Function

See the \s*\([^()]+\)\s* regex demo.

Details

\s* - 0+ whitespaces

\( - a (

[^()]+ - 1 or more (replace with * to match 0 or more) chars other than ( and )

\) - a )

\s*- 0+ whitespaces

Note that with this regex, objRegExp.IgnoreCase = True does not do anything meaningful and can be removed.


问:
In EF Code First is it possible to encapsulate properties that should be persisted to the data store?
So let's say I've got a POCO that I want EF Code First to persist to a data store:

```<code>public class Campaign
{
    public string Name { get; set; }
    public double GoalAmount { get; set; }
    private double AmountRaised { get; set; }
    public bool GoalMet
    {
        get
        {
            return AmountRaised >= GoalAmount;
        }
    }
}
</code>```

Now, for whatever reason, I don't want the AmountRaised property to be accessible outside the object, but I do want it persisted to the data store. Is this possible with EF Code First?

答:
You can make it internal and make sure that the project that contains the POCOs / domain objects are in the same assembly as your DbContext classes.  Or you can declare "friend" assemblies in the files that contain your POCOs:

[assembly: InternalsVisibleTo("MyOther.Assembly")]

ContentLicense: CC BY-SA 2.5

Body:
So let's say I've got a POCO that I want EF Code First to persist to a data store:

public class Campaign
{
    public string Name { get; set; }
    public double GoalAmount { get; set; }
    private double AmountRaised { get; set; }
    public bool GoalMet
    {
        get
        {
            return AmountRaised >= GoalAmount;
        }
    }
}

Now, for whatever reason, I don't want the AmountRaised property to be accessible outside the object, but I do want it persisted to the data store. Is this possible with EF Code First?


答:
What you're proposing is to simply define the bind operator to be equal to fmap, but with arguments swapped:

```<code>ma >>= k = fmap k ma
-- is equivalent to:
(>>=) = flip fmap
</code>```

In which case, why not just use the fmap itself, or its operator form <$>?

```<code>(*2) <$> [0,1..]
> [0,2,4,6,...]
</code>```

However, this does not cover all cases where bind may be used. The difference is that monads are more powerful than functors. Where functors only let you produce exactly one output for every input, monads let you do all kinds of crazy stuff.

Consider, for example, the following:

```<code>[0,1,2,3] >>= \i -> [i*2, i*3]
> [0,0,2,3,4,6,6,9]
</code>```

Here, the function produces two values for each input. This cannot be expressed via just fmap. This requires joining the resulting values.

Here's another, even less obvious example:

```<code>[0,1,2,3,4,5] >>= \i -> if i `mod` 2 == 0 then [] else [i]
> [1,3,5]
</code>```

Here, the function either produces a value or doesn't. The empty list is technically still a value in the List monad, yet it cannot be obtained by fmaping the input.

Title: Haskell >>= operation: why is the function argument required to return another Monad?

Body:
What you're proposing is to simply define the bind operator to be equal to fmap, but with arguments swapped:

ma >>= k = fmap k ma
-- is equivalent to:
(>>=) = flip fmap

In which case, why not just use the fmap itself, or its operator form <$>?

(*2) <$> [0,1..]
> [0,2,4,6,...]

However, this does not cover all cases where bind may be used. The difference is that monads are more powerful than functors. Where functors only let you produce exactly one output for every input, monads let you do all kinds of crazy stuff.

Consider, for example, the following:

[0,1,2,3] >>= \i -> [i*2, i*3]
> [0,0,2,3,4,6,6,9]

Here, the function produces two values for each input. This cannot be expressed via just fmap. This requires joining the resulting values.

Here's another, even less obvious example:

[0,1,2,3,4,5] >>= \i -> if i `mod` 2 == 0 then [] else [i]
> [1,3,5]

Here, the function either produces a value or doesn't. The empty list is technically still a value in the List monad, yet it cannot be obtained by fmaping the input.


问:
default: "now()" in Sequel generates literal embedded into the defenitiion of a table
I'm trying to create a default value in Sequel:

```<code>create_table(:my_table) do
  primary_key :id
  # ..........
  Timestamp :created_at, default: "now()"
</code>```

After running a migration, it generates a table with this column definition:

```<code>  --........
  created_at timestamp without time zone DEFAULT '2017-10-28 12:26:00.129157'::timestamp without time zone,
</code>```

But what I want is the value "now()" to be set when I'm inserting a new value.

答: Are you trying to set a String in a Time field? I don't think this is going to work. You'll have to use String :created_at, default: "now()"

Body:
I'm trying to create a default value in Sequel:

create_table(:my_table) do
  primary_key :id
  # ..........
  Timestamp :created_at, default: "now()"

After running a migration, it generates a table with this column definition:

  --........
  created_at timestamp without time zone DEFAULT '2017-10-28 12:26:00.129157'::timestamp without time zone,

But what I want is the value "now()" to be set when I'm inserting a new value.


问:
Access VBA Pop Up Sub Form for Submission of Entries
Here's what I've got:
I have an Access form that accepts entries, and places them into a table when the ENTER button is clicked.  At the moment, I have a popup message box that comes up when the button is clicked, asking them to confirm that their entries are ok (your standard pop up box, with OK and CANCEL options).  This popup box comes up right in the middle of the data that the user has entered, and is pretty inconvenient for the user to deal with.

Instead of this popup message box, I came up with the idea of using a pop-up SUB-FORM, that would lie invisible just under the ENTER button, and would come up visible when ENTER is clicked. (Same options as the message box, etc, just different placement.  Making the "physical" subform design was a no brainer).  Since this is a new form/subform, how would I code this in order to make it work like the message box did?  The old code won't work.  This is the best idea I could come up with.  If there's an even better way to accomplish this, I'm open to suggestions...

答: I would strongly recommend, if you feel it necessary to go this route, that you employ the use of a modal pop-up form, whose coordinates I believe you can specify, so that it opens in a particular area. There may be nuances depending upon user screen resolution, but I'm pretty sure this will solve your problem. The subform solution you propose sounds very rickety.</p>


问:
python 2.7 functools_lru_cache does not import although installed
When I try to import matplotlib I get an error

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/__init__.py", line 128, in <module>
  from matplotlib.rcsetup import defaultParams, validate_backend, cycler
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/rcsetup.py", line 29, in <module>
    from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/fontconfig_pattern.py", line 32, in <module>
    from backports.functools_lru_cache import lru_cache
ImportError: No module named functools_lru_cache
</code>```

backports itself imports properly. When I try to install functools manually via

```<code>sudo pip install backports.functools_lru_cache
</code>```

I get info that

```<code>Requirement already satisfied: backports.functools_lru_cache in /usr/local/lib/python2.7/dist-packages
</code>```

Nevertheless when i try to

```<code>import backports.functools_lru_cache
</code>```

I get info that

```<code>ImportError: No module named functools_lru_cache
</code>```

System info
Ubuntu 16
Python 2.7.12
Pip 9.0.1

答:
The pip command was actually the pip3, and the "ImportError" was happening when I used python (2.7).

```<code>pip2 uninstall backports.functools_lru_cache
</code>```

then,

```<code>pip2 install backports.functools_lru_cache
</code>```

fixed my problem.

Body:
When I try to import matplotlib I get an error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/__init__.py", line 128, in <module>
  from matplotlib.rcsetup import defaultParams, validate_backend, cycler
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/rcsetup.py", line 29, in <module>
    from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/fontconfig_pattern.py", line 32, in <module>
    from backports.functools_lru_cache import lru_cache
ImportError: No module named functools_lru_cache

backports itself imports properly. When I try to install functools manually via

sudo pip install backports.functools_lru_cache

I get info that

Requirement already satisfied: backports.functools_lru_cache in /usr/local/lib/python2.7/dist-packages

Nevertheless when i try to

import backports.functools_lru_cache

I get info that

ImportError: No module named functools_lru_cache

System info
Ubuntu 16
Python 2.7.12
Pip 9.0.1

Body:
The pip command was actually the pip3, and the "ImportError" was happening when I used python (2.7).

pip2 uninstall backports.functools_lru_cache

then,

pip2 install backports.functools_lru_cache

fixed my problem.


问:
How to enumerate sibling nodes in SyntaxTree using SyntaxWalker
Is it possible to emunerate sibling of a node in the SyntaxTree?

In the following example how do I get a list of nodes (orange circles) that are siblings of node marked as orange arrow?

```<code> If dayW = DayOfWeek.Wednesday Then
</code>```

答:
The parent of If Statement Node is MultiLineIfStatement that provides details If and End If statements and also MultiLineIfStatement.ElseIfBlocks provides information about the Else and ElseIf statements.

Here is my VisitIfStatement methed:

```<code>public override void VisitIfStatement(IfStatementSyntax node)
  {
     base.VisitIfStatement(node);
     var Block = node.Parent as MultiLineIfBlockSyntax;

     Location Location = Block.GetLocation();
     FileLinePositionSpan LinePosition = Location.GetLineSpan();

     int Level = IndentLevel(Block);

     // Process If and EndIf staments Details here

     // Get the list of ElseIf blocks and Else Block
     SyntaxList<ElseIfBlockSyntax> ElseIfBlocks = Block.ElseIfBlocks;
     ElseBlockSyntax ElseBlock = Block.ElseBlock;

     / Process ElseIf blocks
     for (int i = 0; i <= ElseIfBlocks.Count - 1; i++)
     {
        ElseIfBlockSyntax ElseIfBlock = ElseIfBlocks[i];
        Location = ElseIfBlock.GetLocation();
        LinePosition = Location.GetLineSpan();

        // **Process ElseIf statements here**

     }

     if (ElseBlock != null)
     {
        Location = ElseBlock.GetLocation();
        LinePosition = Location.GetLineSpan();

       // **Process ElseBlock Details here**
     }
  }
</code>```

Body:
Is it possible to emunerate sibling of a node in the SyntaxTree?

In the following example how do I get a list of nodes (orange circles) that are siblings of node marked as orange arrow?

 If dayW = DayOfWeek.Wednesday Then

Body:
The parent of If Statement Node is MultiLineIfStatement that provides details If and End If statements and also MultiLineIfStatement.ElseIfBlocks provides information about the Else and ElseIf statements.

Here is my VisitIfStatement methed:

public override void VisitIfStatement(IfStatementSyntax node)
  {
     base.VisitIfStatement(node);
     var Block = node.Parent as MultiLineIfBlockSyntax;

     Location Location = Block.GetLocation();
     FileLinePositionSpan LinePosition = Location.GetLineSpan();

     int Level = IndentLevel(Block);

     // Process If and EndIf staments Details here

     // Get the list of ElseIf blocks and Else Block
     SyntaxList<ElseIfBlockSyntax> ElseIfBlocks = Block.ElseIfBlocks;
     ElseBlockSyntax ElseBlock = Block.ElseBlock;

     / Process ElseIf blocks
     for (int i = 0; i <= ElseIfBlocks.Count - 1; i++)
     {
        ElseIfBlockSyntax ElseIfBlock = ElseIfBlocks[i];
        Location = ElseIfBlock.GetLocation();
        LinePosition = Location.GetLineSpan();

        // **Process ElseIf statements here**

     }

     if (ElseBlock != null)
     {
        Location = ElseBlock.GetLocation();
        LinePosition = Location.GetLineSpan();

       // **Process ElseBlock Details here**
     }
  }


问:
Safely limiting Ansible playbooks to a single machine?
I'm using Ansible for some simple user management tasks with a small group of computers. Currently, I have my playbooks set to hosts: all and my hosts file is just a single group with all machines listed:

# file: hosts
[office]
imac-1.local
imac-2.local
imac-3.local
```
<p>I've found myself frequently having to target a single machine. The <code>ansible-playbook</code> command can limit plays like this:</p>
<pre class="lang-bash prettyprint-override"><code>ansible-playbook --limit imac-2.local user.yml
</code>```

But that seems kind of fragile, especially for a potentially destructive playbook. Leaving out the limit flag means the playbook would be run everywhere. Since these tools only get used occasionally, it seems worth taking steps to foolproof playback so we don't accidentally nuke something months from now.

Is there a best practice for limiting playbook runs to a single machine? Ideally the playbooks should be harmless if some important detail was left out.

答:
We have some generic playbooks that are usable by a large number of teams. We also have environment specific inventory files, that contain multiple group declarations.

To force someone calling a playbook to specify a group to run against, we seed a dummy entry at the top of the playbook:

```<code>[ansible-dummy-group]
dummy-server
</code>```

We then include the following check as a first step in the shared playbook:

```<code>- hosts: all
  gather_facts: False
  run_once: true
  tasks:
  - fail:
      msg: "Please specify a group to run this playbook against"
    when: '"dummy-server" in ansible_play_batch'
</code>```

If the dummy-server shows up in the list of hosts this playbook is scheduled to run against (ansible_play_batch), then the caller didn't specify a group and the playbook execution will fail.

ContentLicense: CC BY-SA 4.0

Body:
I'm using Ansible for some simple user management tasks with a small group of computers. Currently, I have my playbooks set to hosts: all and my hosts file is just a single group with all machines listed:

# file: hosts
[office]
imac-1.local
imac-2.local
imac-3.local

I've found myself frequently having to target a single machine. The ansible-playbook command can limit plays like this:

ansible-playbook --limit imac-2.local user.yml

But that seems kind of fragile, especially for a potentially destructive playbook. Leaving out the limit flag means the playbook would be run everywhere. Since these tools only get used occasionally, it seems worth taking steps to foolproof playback so we don't accidentally nuke something months from now.

Is there a best practice for limiting playbook runs to a single machine? Ideally the playbooks should be harmless if some important detail was left out.

Body:
We have some generic playbooks that are usable by a large number of teams. We also have environment specific inventory files, that contain multiple group declarations.

To force someone calling a playbook to specify a group to run against, we seed a dummy entry at the top of the playbook:

[ansible-dummy-group]
dummy-server

We then include the following check as a first step in the shared playbook:

- hosts: all
  gather_facts: False
  run_once: true
  tasks:
  - fail:
      msg: "Please specify a group to run this playbook against"
    when: '"dummy-server" in ansible_play_batch'

If the dummy-server shows up in the list of hosts this playbook is scheduled to run against (ansible_play_batch), then the caller didn't specify a group and the playbook execution will fail.


问:
Unable to get gulp autoprefixer working
I'm currently setting up a new project with gulp and I cannot get gulp-autoprefixer to work.

Below is my gulpfile.js so far.

```<code>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    prefix = require('gulp-autoprefixer'),
    rename = require('gulp-rename'),
    livereload = require('gulp-livereload'),
    sourcemaps = require('gulp-sourcemaps');

gulp.task('styles', function() {
  gulp.src('css/**/*.scss')
    .pipe(sourcemaps.init())
    .pipe(prefix('last 2 version'))
    .pipe(sass().on('error', sass.logError))
    .pipe(sourcemaps.write('./'))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./css/'));
});

gulp.task('default',function() {
  gulp.watch('css/**/*.scss',['styles']);
  livereload.listen();
  gulp.watch(['./**/*']).on('change', livereload.changed);
});
</code>```

答:
Managed to fix it, see below.</p>

```<code>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    rename = require('gulp-rename'),
    livereload = require('gulp-livereload'),
    sourcemaps = require('gulp-sourcemaps');

gulp.task('styles', function() {
  gulp.src('src/css/**/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(sourcemaps.write('./'))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./dist/css/'));
});

gulp.task('default',function() {
  gulp.watch('src/css/**/*.scss',['styles']);
  livereload.listen();
  gulp.watch(['./**/*']).on('change', livereload.changed);
});
</code>```

Title: Unable to get gulp autoprefixer working

Body:
I'm currently setting up a new project with gulp and I cannot get gulp-autoprefixer to work.

Below is my gulpfile.js so far.

var gulp = require('gulp'),
    sass = require('gulp-sass'),
    prefix = require('gulp-autoprefixer'),
    rename = require('gulp-rename'),
    livereload = require('gulp-livereload'),
    sourcemaps = require('gulp-sourcemaps');

gulp.task('styles', function() {
  gulp.src('css/**/*.scss')
    .pipe(sourcemaps.init())
    .pipe(prefix('last 2 version'))
    .pipe(sass().on('error', sass.logError))
    .pipe(sourcemaps.write('./'))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./css/'));
});

gulp.task('default',function() {
  gulp.watch('css/**/*.scss',['styles']);
  livereload.listen();
  gulp.watch(['./**/*']).on('change', livereload.changed);
});

Body:
Managed to fix it, see below.

var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    rename = require('gulp-rename'),
    livereload = require('gulp-livereload'),
    sourcemaps = require('gulp-sourcemaps');

gulp.task('styles', function() {
  gulp.src('src/css/**/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(sourcemaps.write('./'))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./dist/css/'));
});

gulp.task('default',function() {
  gulp.watch('src/css/**/*.scss',['styles']);
  livereload.listen();
  gulp.watch(['./**/*']).on('change', livereload.changed);
});


问:
Is middleware neeeded to redirect to HTTPS in ASP.net and C#?
What is the recommend way to redirect to HTTPS all incoming requests that are not secure.  Do I need to write a middleware component?  If so, I couldn't figure out how to get the server name.</p>

```<code>public class RedirectHttpMiddleware
{
    RequestDelegate _next;

    public RedirectHttpMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.IsSecure)
            await _next(context);
        else
        {
            var server = "";  // How do I get the server name?
            context.Response.Redirect("https://" + server + context.Request.Path);
        }
    }
}
</code>```

答:
I like attribute with compiler directive</p>

```<code>#if !DEBUG
    [RequireHttps]
#endif
    public class HomeController : Controller
    {
    }
</code>```

Body:
What is the recommend way to redirect to HTTPS all incoming requests that are not secure.  Do I need to write a middleware component?  If so, I couldn't figure out how to get the server name.

public class RedirectHttpMiddleware
{
    RequestDelegate _next;

    public RedirectHttpMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.IsSecure)
            await _next(context);
        else
        {
            var server = "";  // How do I get the server name?
            context.Response.Redirect("https://" + server + context.Request.Path);
        }
    }
}

Body:
I like attribute with compiler directive

#if !DEBUG
    [RequireHttps]
#endif
    public class HomeController : Controller
    {
    }


问:
Added button successfully by using .innerHTML but can't access the button using its class name
```<code>    function displaMatches (matches) {
  var searchText = document.querySelector('.search').value;
  var menu = document.querySelector('.menu')
  matches.forEach(match => {
    menu.innerHTML += `<li><button class="suggestion">${match}</button></li>`
  });

  var suggestions = document.querySelectorAll('.suggestion');
  suggestions.forEach(suggestion => {
    suggestion.addEventListener('click', () => {
      document.querySelector('.search').value = suggestion.textContent;
    });
  });
}
var search = document.querySelector('.search')

search.addEventListener('change', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

search.addEventListener('keyup', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

function autocomplete () {
  var searchText = document.querySelector('.search').value

  fetch(`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/autocomplete?&text=${searchText}&latitude=37.3351534&longitude=-122.0352478`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${access_token}`,
    }
  }).then((res) => {
    return res.json();
  }).then((data) => {
    var allData = [];
    allData.push(data);
    console.log(allData);
    let businesses = allData[0].businesses
    let categories = allData[0].categories
    let terms = allData[0].terms

    let matches = [];

    businesses.forEach(business => {
      matches.push(business.name);
    });

    categories.forEach(category => {
      matches.push(category.title);
    });

    terms.forEach(term => {
      matches.push(term.text);
    });
    displaMatches(matches);
  });
}
</code>```

I can see buttons being added successfully to the menu on the page. However, when I tried to access a button using the class name "suggestion", what I got is null. What did I do wrong?

I changed my codes and the displayMatches function is now working fine. However, after I added the suggestion to the search box, the search button no longer works. If I disable the suggestion function, and type my own words into the search box, I can search anything with no problem. Can anyone explain why?

答:
There was a lot of errors, but here is something that works. Sorry, in old plain js. </p>

```<code>   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul class="menu">
</ul>
<div id="searchtext">
</div>

<script>
    function displaMatches (matches) {

        var menu = document.querySelector('.menu');
        var item = function(match) {
            return '<li><button class="suggestion">' + match + '</button></li>';
        };

        var menuItems = [];

        for(var i=0;i<matches.length;i++){
            var m = matches[i];
            menuItems.push(item(m));
        }

        menu.innerHTML = menuItems.join('');

    }

   window.onload =  function() {
        var matches = [ 'red', 'blue', 'red' ];
        displaMatches(matches);

       setTimeout(function() {
           var suggestions = document.querySelectorAll('.suggestion');
           for (var i = 0; i < suggestions.length; i++) {
               suggestions[i].onclick = function () {
                   document.getElementById('searchtext').innerText += this.innerText;
               };
            }

       }, 1000);
    };
</script>

</body>
</html>
</code>```

Body:
    function displaMatches (matches) {
  var searchText = document.querySelector('.search').value;
  var menu = document.querySelector('.menu')
  matches.forEach(match => {
    menu.innerHTML += `<li><button class="suggestion">${match}</button></li>`
  });

  var suggestions = document.querySelectorAll('.suggestion');
  suggestions.forEach(suggestion => {
    suggestion.addEventListener('click', () => {
      document.querySelector('.search').value = suggestion.textContent;
    });
  });
}
var search = document.querySelector('.search')

search.addEventListener('change', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

search.addEventListener('keyup', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

function autocomplete () {
  var searchText = document.querySelector('.search').value

  fetch(`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/autocomplete?&text=${searchText}&latitude=37.3351534&longitude=-122.0352478`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${access_token}`,
    }
  }).then((res) => {
    return res.json();
  }).then((data) => {
    var allData = [];
    allData.push(data);
    console.log(allData);
    let businesses = allData[0].businesses
    let categories = allData[0].categories
    let terms = allData[0].terms

    let matches = [];

    businesses.forEach(business => {
      matches.push(business.name);
    });

    categories.forEach(category => {
      matches.push(category.title);
    });

    terms.forEach(term => {
      matches.push(term.text);
    });
    displaMatches(matches);
  });
}

I can see buttons being added successfully to the menu on the page. However, when I tried to access a button using the class name "suggestion", what I got is null. What did I do wrong?

I changed my codes and the displayMatches function is now working fine. However, after I added the suggestion to the search box, the search button no longer works. If I disable the suggestion function, and type my own words into the search box, I can search anything with no problem. Can anyone explain why?

Body:
There was a lot of errors, but here is something that works. Sorry, in old plain js.

   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul class="menu">
</ul>
<div id="searchtext">
</div>

<script>
    function displaMatches (matches) {

        var menu = document.querySelector('.menu');
        var item = function(match) {
            return '<li><button class="suggestion">' + match + '</button></li>';
        };

        var menuItems = [];

        for(var i=0;i<matches.length;i++){
            var m = matches[i];
            menuItems.push(item(m));
        }

        menu.innerHTML = menuItems.join('');

    }

   window.onload =  function() {
        var matches = [ 'red', 'blue', 'red' ];
        displaMatches(matches);

       setTimeout(function() {
           var suggestions = document.querySelectorAll('.suggestion');
           for (var i = 0; i < suggestions.length; i++) {
               suggestions[i].onclick = function () {
                   document.getElementById('searchtext').innerText += this.innerText;
               };
            }

       }, 1000);
    };
</script>

</body>
</html>


问:
How to upsert or partial updates with script documents in ElasticSearch with Spark?
I have a pseudocode in python that reads from a Kafka stream and upsert documents in Elasticsearch (incrementing a counter view if the document exists already.

```<code>for message in consumer:

    msg = json.loads(message.value)
    print(msg)
    index = INDEX_NAME
    es_id = msg["id"]
    script = {"script":"ctx._source.view+=1","upsert" : msg}
    es.update(index=index, doc_type="test", id=es_id, body=script)
</code>```

Since I want to use it in a distributed environment, I am using Spark Structured Streaming

```<code>df.writeStream \
.format("org.elasticsearch.spark.sql")\
.queryName("ESquery")\
.option("es.resource","credentials/url") \
.option("checkpointLocation", "checkpoint").start()
</code>```

or SparkStreaming in scala that reads from KafkaStream:

```<code>// Initializing Spark Streaming Context and kafka stream
sparkConf.setMaster("local[2]")
val ssc = new StreamingContext(sparkConf, Seconds(10))
[...]
val messages = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topicsSet, kafkaParams)
    )

[...]
val urls = messages.map(record => JsonParser.parse(record.value()).values.asInstanceOf[Map[String, Any]])
urls.saveToEs("credentials/credential")
</code>```

.saveToEs(...) is the API of elastic-hadoop.jar documented here. Unfortunately this repo is not really well documented. So I cannot understand where I can put the script command.

Is there anyone can help me? Thank you in advance

答:
You should be able to do it by setting write mode "update" ( or upsert) and passing your script as "script" (depends on ES version).

```<code>EsSpark.saveToEs(rdd, "spark/docs", Map("es.mapping.id" -> "id", "es.write.operation" -> "update","es.update.script.inline" -> "your script" , ))
</code>```

Probably you want to use "upsert"

There are some good unit tests in cascading integration in same library; These settings should be good for spark as both uses same writer.

I suggest to read unit tests to pick correct settings for your ES version.

Body:
I have a pseudocode in python that reads from a Kafka stream and upsert documents in Elasticsearch (incrementing a counter view if the document exists already.

for message in consumer:

    msg = json.loads(message.value)
    print(msg)
    index = INDEX_NAME
    es_id = msg["id"]
    script = {"script":"ctx._source.view+=1","upsert" : msg}
    es.update(index=index, doc_type="test", id=es_id, body=script)

Since I want to use it in a distributed environment, I am using Spark Structured Streaming

df.writeStream \
.format("org.elasticsearch.spark.sql")\
.queryName("ESquery")\
.option("es.resource","credentials/url") \
.option("checkpointLocation", "checkpoint").start()

or SparkStreaming in scala that reads from KafkaStream:

// Initializing Spark Streaming Context and kafka stream
sparkConf.setMaster("local[2]")
val ssc = new StreamingContext(sparkConf, Seconds(10))
[...]
val messages = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topicsSet, kafkaParams)
    )

[...]
val urls = messages.map(record => JsonParser.parse(record.value()).values.asInstanceOf[Map[String, Any]])
urls.saveToEs("credentials/credential")

.saveToEs(...) is the API of elastic-hadoop.jar documented here. Unfortunately this repo is not really well documented. So I cannot understand where I can put the script command.

Is there anyone can help me? Thank you in advance

Body:
You should be able to do it by setting write mode "update" ( or upsert) and passing your script as "script" (depends on ES version).

EsSpark.saveToEs(rdd, "spark/docs", Map("es.mapping.id" -> "id", "es.write.operation" -> "update","es.update.script.inline" -> "your script" , ))

Probably you want to use "upsert"

There are some good unit tests in cascading integration in same library; These settings should be good for spark as both uses same writer.

I suggest to read unit tests to pick correct settings for your ES version.


问:
Parsing Human Names and matching them in Ruby
I'm looking for a gem or project that would let me identify that two names are the same person.  For example

J.R. Smith == John R. Smith == John Smith == John Roy Smith == Johnny Smith

I think you get the idea.  I know nothing is going to be 100% accurate but I'd like to get something that at least handles the majority of cases.  I know that last one is probably going to need a database of nicknames.

答:
I think one option would be to use a ruby implementation of the Levenshtein distance

The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.

Then you could define that names with a distance less than X (being X a number you will have to tweak) are from the same person.

EDIT
Through a little search I was able to find another algorithm, based on phonetics called Metaphone

Still has a lot of holes in it, but I think that in this case the best everyone can do is to give you alternatives for you to test and see what works best


问:
How to exit from thread which is suspended by semaphore?
In main function I create one producer thread and two consumer threads.
Producer doing some work, then with "if" statement checks if it should to break and then increments semaphore. Consumers are waiting for semaphore become greater then 0 and do some work, then waiting again. When producer exited, consumers should finish their work and exit too. I don't understand how can i exit threads which are suspended by semaphore? Here is my code:</p>

```<code>sem_t ready;

void *prod_routine(void*){
    while(true){
        //do_something
        //here i have if statement with break.
        sem_post(&ready);
    }
pthread_exit(0);
}

void *cons_routine(void*){
    while(true){
        sem_wait(&ready);
        //do something
    }
pthread_exit(0);
}

int main(int argc, char *argv[]){

pthread_t prod, cons1, cons2;

sem_init(&ready, 0 , 0);

pthread_create(&prod, NULL, &prod_routine, NULL);
pthread_create(&cons1, NULL, &cons_routine, NULL);
pthread_create(&cons2, NULL, &cons_routine, NULL);

pthread_join(prod, NULL);
pthread_join(cons1, NULL);
pthread_join(cons2, NULL);

return 0;
}
</code>```

答: first try with pthread_kill(). For this first call pthread_cancel and followed by pthread_kill() with signal SIGSTOP. Even if after that it is not working for your try to destroy the semaphore with sem_destroy().

Body:
In main function I create one producer thread and two consumer threads.
Producer doing some work, then with "if" statement checks if it should to break and then increments semaphore. Consumers are waiting for semaphore become greater then 0 and do some work, then waiting again. When producer exited, consumers should finish their work and exit too. I don't understand how can i exit threads which are suspended by semaphore? Here is my code:

sem_t ready;

void *prod_routine(void*){
    while(true){
        //do_something
        //here i have if statement with break.
        sem_post(&ready);
    }
pthread_exit(0);
}

void *cons_routine(void*){
    while(true){
        sem_wait(&ready);
        //do something
    }
pthread_exit(0);
}

int main(int argc, char *argv[]){

pthread_t prod, cons1, cons2;

sem_init(&ready, 0 , 0);

pthread_create(&prod, NULL, &prod_routine, NULL);
pthread_create(&cons1, NULL, &cons_routine, NULL);
pthread_create(&cons2, NULL, &cons_routine, NULL);

pthread_join(prod, NULL);
pthread_join(cons1, NULL);
pthread_join(cons2, NULL);

return 0;
}


问:
Vue.js view doesn't update when an event is received using an eventbus
I'm new to Vue.js 2 and am building my first (vue) web application.
The application uses two components, one header component and one login component.
When the login is succesfull a "loggedIn"-flag variable will be toggled in a singleton authentication service.
This service is responsible to emit an event to the header component (and maybe other listening components) to notify that the user is logged in. The header in turn should update it's view and display the username.

Everything works as described, events are generated and emitted/received using a global event bus.
However, when the event is received by the header component it's unable to update the view.

I already tried different approaches: basic subscriber pattern, vuex and now the event bus. Nothing seems to work. Does anyone know what the problem might be?

EventBus.js:

import Vue from 'vue'
var eventBus = new Vue()
export default eventBus
```

<p><strong>SessionService.js</strong>
</p>

```import eventBus from '../util/EventBus'

class SessionService {
  loggedIn=false
  constructor () {
    if (this.isValid(this.getSessionToken())) {
      this.loggedIn = true
    }
  }
  setSessionToken (token) {
    localStorage.setItem('token', token)
    if (this.isValid(token)) {
      eventBus.$emit('LOGGEDIN')
    } else {
      eventBus.$emit('LOGGEDOUT')
    }
  }
  getSessionToken () {
    return localStorage.getItem('token')
  }
  isValid (token) {
    return token !== undefined && token != null && token !== ''
  }
}
var sessionService = new SessionService()
export default sessionService
```

<p><strong>Header.vue: Script</strong></p>

<pre class="lang-js prettyprint-override"><code>  import eventBus from '../../services/util/EventBus'
  var loggedIn = false
  var m = this
  eventBus.$on('LOGGEDIN', function () {
    console.log('RECEIVED')
    m.loggedIn = true
  })

  export default{
    name: 'Header',
    data () {
      return {loggedIn}
    }
  }
</code>```

Header.vue: HTML

```<code><template>
  <div>
  <nav class="navbar navbar-expand-lg ap-top-nav">
    <div class="container" >
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">

        <form class="form-inline my-2 my-lg-0 mr-auto">
          <div class="ap-searcher">
            <input class="ap-search" type="text" placeholder="Search" aria-label="Search"/>
            <i class="fa fa-search"></i>
          </div>

        </form>
        <div class="logo ml-auto mr-auto">
          <img src="../../assets/images/logo.png"/>
        </div>
        <ul class="navbar-nav ml-auto">
          <li class="nav-item ap-button blue wide">
            <router-link to="/login">Login: {{loggedIn}}</router-link>
          </li>
          <li class="nav-item ap-button light-blue wide">
            <router-link to="/registration">Register</router-link>
          </li>
          <li class="nav-item ap-button blue-border">
            <a href="#">EN <i class="fa fa-sort-desc" aria-hidden="true"></i></a>
          </li>
        </ul>
      </div>

    </div>
  </nav>
    <nav class="navbar navbar-expand-lg ag-bottom-nav">
      <div class="container">
        <div class="collapse navbar-collapse " id="navbarNav">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
              <router-link class="nav-link ap-link" to="/">Auctions</router-link>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Lots</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">About</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Organize your own auction</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Contact </a>
            </li>
          </ul>
        </div>
      </div>

    </nav>
    <div class="ap-line">
    </div>
  </div>
</template>
</code>```

答:
You have some weird structure of Header component code, but I think it should be like this:</p>

```<code>  export default{
    name: 'Header',
    data () {
      return { loggedIn: loggedIn }
    }
  }
</code>```

Body:
I'm new to Vue.js 2 and am building my first (vue) web application.
The application uses two components, one header component and one login component.
When the login is succesfull a "loggedIn"-flag variable will be toggled in a singleton authentication service.
This service is responsible to emit an event to the header component (and maybe other listening components) to notify that the user is logged in. The header in turn should update it's view and display the username.

Everything works as described, events are generated and emitted/received using a global event bus.
However, when the event is received by the header component it's unable to update the view.

I already tried different approaches: basic subscriber pattern, vuex and now the event bus. Nothing seems to work. Does anyone know what the problem might be?

EventBus.js:

import Vue from 'vue'
var eventBus = new Vue()
export default eventBus

SessionService.js

import eventBus from '../util/EventBus'

class SessionService {
  loggedIn=false
  constructor () {
    if (this.isValid(this.getSessionToken())) {
      this.loggedIn = true
    }
  }
  setSessionToken (token) {
    localStorage.setItem('token', token)
    if (this.isValid(token)) {
      eventBus.$emit('LOGGEDIN')
    } else {
      eventBus.$emit('LOGGEDOUT')
    }
  }
  getSessionToken () {
    return localStorage.getItem('token')
  }
  isValid (token) {
    return token !== undefined && token != null && token !== ''
  }
}
var sessionService = new SessionService()
export default sessionService

Header.vue: Script

  import eventBus from '../../services/util/EventBus'
  var loggedIn = false
  var m = this
  eventBus.$on('LOGGEDIN', function () {
    console.log('RECEIVED')
    m.loggedIn = true
  })

  export default{
    name: 'Header',
    data () {
      return {loggedIn}
    }
  }

Header.vue: HTML

<template>

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

        <form class="form-inline my-2 my-lg-0 mr-auto">

            <input class="ap-search" type="text" placeholder="Search" aria-label="Search"/>

        </form>

            <router-link to="/login">Login: {{loggedIn}}</router-link>

            <router-link to="/registration">Register</router-link>

            EN

              <router-link class="nav-link ap-link" to="/">Auctions</router-link>

              Lots

              About

              Organize your own auction

              Contact

</template>

Body:
You have some weird structure of Header component code, but I think it should be like this:

  export default{
    name: 'Header',
    data () {
      return { loggedIn: loggedIn }
    }
  }


问:
Handling Enums with FlowType
```<code>export type Size =
| 'small'
| 'medium'
| 'large'
| 'big'
| 'huge';
</code>```

Defining the Size type like this gives me auto-completion in my IDE wherever I use it:

Yet, I also want to make use of these values inside of a component: let's say a dropdown menu w/ available size values.

In order to achieve that I am maintaining a sizes object out of which I can extract the Size FlowType by leveraging $Keys:

```<code>export const sizes = {
  small: 'small',
  medium: 'medium',
  large: 'large',
  big: 'big',
  huge: 'huge',
};

export type Size = $Keys<typeof sizes>;
</code>```

It kind of works in that it points out invalid values for a prop:

Yet, this solution comes at a cost: it screws all my auto-completion goodness... :( Is there a better way to handle Enums in FlowType?

答:
That's a neat use of $Keys!

I don't know of a better way to derive the Size type from an object. Maybe you could work in the other direction like this:

```<code>export type Size =
| 'small'
| 'medium'
| 'large'
| 'big'
| 'huge';

export const sizes: { [key: string]: Size } = {
  small: 'small',
  medium: 'medium',
  large: 'large',
  big: 'big',
  huge: 'huge',
};
</code>```

or perhaps eliminate a bit of duplication this way:

```<code>export const sizes: { [key: string]: Size } = [
  'small',
  'medium',
  'large',
  'big',
  'huge'
].reduce((obj, s) => {
  obj[s] = s
  return obj
}, {})
</code>```

Clearly that uses more boilerplate. But with the type constraint on sizes you at least get a check that prevents invalid strings from getting into the sizes object.

Title: Handling Enums with FlowType

Body:
export type Size =
| 'small'
| 'medium'
| 'large'
| 'big'
| 'huge';

Defining the Size type like this gives me auto-completion in my IDE wherever I use it:

Yet, I also want to make use of these values inside of a component: let's say a dropdown menu w/ available size values.

In order to achieve that I am maintaining a sizes object out of which I can extract the Size FlowType by leveraging $Keys:

export const sizes = {
  small: 'small',
  medium: 'medium',
  large: 'large',
  big: 'big',
  huge: 'huge',
};

export type Size = $Keys<typeof sizes>;

It kind of works in that it points out invalid values for a prop:

Yet, this solution comes at a cost: it screws all my auto-completion goodness... :( Is there a better way to handle Enums in FlowType?

Body:
That's a neat use of $Keys!

I don't know of a better way to derive the Size type from an object. Maybe you could work in the other direction like this:

export type Size =
| 'small'
| 'medium'
| 'large'
| 'big'
| 'huge';

export const sizes: { [key: string]: Size } = {
  small: 'small',
  medium: 'medium',
  large: 'large',
  big: 'big',
  huge: 'huge',
};

or perhaps eliminate a bit of duplication this way:

export const sizes: { [key: string]: Size } = [
  'small',
  'medium',
  'large',
  'big',
  'huge'
].reduce((obj, s) => {
  obj[s] = s
  return obj
}, {})

Clearly that uses more boilerplate. But with the type constraint on sizes you at least get a check that prevents invalid strings from getting into the sizes object.


问:
Mapping Over a new Array() without populating it returns an empty array. Why?

Riddle me this.

Let's say you new up an array of 1,000 elements and want to assign the index of each element as the element's value using .map(). I would expect it to work like so:

```<code>new Array(1000).map((element, i) => i);
</code>```

Here's the problem: the new array returned, while having the required 1,000 elements, is empty, despite assigning the .map()'s return value to be the array index. This can be remedied by chaining .fill(0) like so:

```<code>new Array(1000).fill(0).map((element, i) => i);
</code>```

But why?

Why do .map or .filter require a populated array to produce a populated array?

答:
It is mainly because the array must be filled, even with undefined pointers in order to be iterated. With new Array() it is not.

From MDC (emphasis mine): "map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. The callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values."

According to the first comment of the accepted answer of this thread:

JavaScript "new Array(n)" and "Array.prototype.map" weirdness

Body:
Riddle me this.

Let's say you new up an array of 1,000 elements and want to assign the index of each element as the element's value using .map(). I would expect it to work like so:

new Array(1000).map((element, i) => i);

Here's the problem: the new array returned, while having the required 1,000 elements, is empty, despite assigning the .map()'s return value to be the array index. This can be remedied by chaining .fill(0) like so:

new Array(1000).fill(0).map((element, i) => i);

But why?

Why do .map or .filter require a populated array to produce a populated array?


问:
Renaming Column names after dropping from dataframe
Below is just a snippet. I started with 28 columns, and dropped and number of them down to 13. Once I reduce my dataframe I would like to give all of the columns proper names.

Do I need to redim the dataframe after removing the columns?

```<code>data_xls.drop('DTM02', axis=1)
data_xls.drop('TDS01', axis=1)
data_xls.drop('CAD05', axis=1)
data_xls.drop('CAD07', axis=1)
data_xls.drop('REFX1', axis=1)

data_xls.columns = ['INV_NO','PO_NO','SHIP_TO','SHIP_ADD_1','SHIP_ADD_2','SHIP_CITY','SHIP_ZIP','INV_QTY','PART_NO','PO_NO','BL_NO','BLUE_BIN_Y_N', 'SHIP_LOC']
</code>```

ValueError: Length mismatch: Expected axis has 28 elements, new values have 13 elements

答:
DataFrame.drop() doesn't change DF in place. So you either need to assign it back or to use inplace=True

You can do it in one step:

```<code>cols_to_drop = ['DTM02','TDS01',...]
data_xls = data_xls.drop(cols_to_drop, axis=1)
</code>```

Body:
Below is just a snippet. I started with 28 columns, and dropped and number of them down to 13. Once I reduce my dataframe I would like to give all of the columns proper names.

Do I need to redim the dataframe after removing the columns?

data_xls.drop('DTM02', axis=1)
data_xls.drop('TDS01', axis=1)
data_xls.drop('CAD05', axis=1)
data_xls.drop('CAD07', axis=1)
data_xls.drop('REFX1', axis=1)

data_xls.columns = ['INV_NO','PO_NO','SHIP_TO','SHIP_ADD_1','SHIP_ADD_2','SHIP_CITY','SHIP_ZIP','INV_QTY','PART_NO','PO_NO','BL_NO','BLUE_BIN_Y_N', 'SHIP_LOC']

ValueError: Length mismatch: Expected axis has 28 elements, new values have 13 elements

Body:
DataFrame.drop() doesn't change DF in place. So you either need to assign it back or to use inplace=True

You can do it in one step:

cols_to_drop = ['DTM02','TDS01',...]
data_xls = data_xls.drop(cols_to_drop, axis=1)


问:
Select rows where ID is repeated, but value in another column is different
I have a table like this:

What I would like to be able to do is return the IDs and how many different types of fruit the ID is associated with other than 1 like so:

Can someone help me out? I don't think it should be that difficult, but I haven't had much luck.

Thanks!

答:
I think you want the having clause and count(distinct):

```<code>select id, count(distinct fruit) as numfruit
from t
group by id
having count(distinct fruit) > 1;
</code>```

Body:
I think you want the having clause and count(distinct):

select id, count(distinct fruit) as numfruit
from t
group by id
having count(distinct fruit) > 1;


问:
AEM code and content migration from AEM 5.6.1 to AEM 6.1
We have 3-4 application in AEM 5.6.1 and now we are migrating one of the applications to AEM 6.1.
We will be creating packages of application from 5.6.1 and deploying them to new instance AEM 6.1.

Is it all we need to do ?

Or else we require any other steps or modifications also ?

答:
There are a couple of things I had come across:

Do the entire env setup (including the hotfixes) and disable all replication agents

Install the code package, verify if all packages are active and test the functionalities

Verify the replication agents and configurations

Update the deprecated APIs if any

Install the index package if any custom index created

If the instances are clustered, make sure you follow the order.


问:
New to CSS, issues with nav bar
I am new to CSS and can't work out a kink. I am having several issues with my nav css. The hover state is not inline with the normal state, and the last item is pushed onto a new line rather than equally spacing across a single bar.

JSFiddle

```<code>ul {
    left: 20%;
    top: 10%;
    list-style-type: none;
    margin: 0;
    padding: 0;
    text-align: center;
    overflow: hidden;
    background: radial-gradient(circle, #505050, #3E3E3E);
    width: 50%;
}

li {
    display: inline-block;
    float: left;
    width: 24%;
    margin: 0;
    padding: 0;
    border-right: 1px solid #232323;
}

/* Remove border from last tab */
li:last-child {
    border: none;
}

li:first-child {
    border: none;
}

/* Setting up the text on the menu */
li a {
    text-align: center;
    font: Verdana;
    font-size: 16px;
    display: inline-block;
    color: #EAE0D2;
    margin: 0;
    padding: 20px 20px;
    text-decoration: none;
    width: 25%;
}

/* Change the link color on hover */
li a:hover {

    background: linear-gradient(#2B2B2B, #232323);
    border:none;
    width: 83%;
}

/* Color the active tab */
.active {
    background: linear-gradient(#3E3E3E, #2B2B2B);
    color: #white;
}
</code>```

答:
You can do it with the Flexbox and much less code:

/* basic CSS browser reset */
* {margin:0;padding:0;box-sizing:border-box}
html, body {width:100%;height:100%}

/* can comment out if you decide to use the below approach */
body {
  display: flex;
  justify-content: center; /* horizontal alignment / centering */
  align-items: flex-start; /* prevents the #menu to fill the remaining height of the body */
}

#menu {
  display: flex; /* displays children inline */
  align-items: flex-start;
  width: 50%; /* added */
  margin-top: 10%; /* added */
  /* alternative to center the #menu horizontally, in this case you don't need the styling on the body element
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  */
  list-style-type: none;
  background: radial-gradient(circle, #505050, #3E3E3E);
}

li {
  flex: 1; /* each takes as much width as it can, i.e. each 25% width of the parent */
  border-right: 1px solid #232323;
}

li:last-child {
  border: none;
}

li a {
  display: block;
  text-align: center;
  font: Verdana;
  font-size: 16px;
  color: #EAE0D2;
  padding: 20px 0;
  text-decoration: none;
}

li a:hover {
  background: linear-gradient(#2B2B2B, #232323);
}

.active {
  background: linear-gradient(#3E3E3E, #2B2B2B);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="menu">
  <li class="active">HOME</li>
  <li>GALLERY</li>
  <li>ART</li>
  <li>CONTACT</li>
</ul></code>```

Title: New to CSS, issues with nav bar

Body:
I am new to CSS and can't work out a kink. I am having several issues with my nav css. The hover state is not inline with the normal state, and the last item is pushed onto a new line rather than equally spacing across a single bar.

JSFiddle

ul {
    left: 20%;
    top: 10%;
    list-style-type: none;
    margin: 0;
    padding: 0;
    text-align: center;
    overflow: hidden;
    background: radial-gradient(circle, #505050, #3E3E3E);
    width: 50%;
}

li {
    display: inline-block;
    float: left;
    width: 24%;
    margin: 0;
    padding: 0;
    border-right: 1px solid #232323;
}

/* Remove border from last tab */
li:last-child {
    border: none;
}

li:first-child {
    border: none;
}

/* Setting up the text on the menu */
li a {
    text-align: center;
    font: Verdana;
    font-size: 16px;
    display: inline-block;
    color: #EAE0D2;
    margin: 0;
    padding: 20px 20px;
    text-decoration: none;
    width: 25%;
}

/* Change the link color on hover */
li a:hover {

    background: linear-gradient(#2B2B2B, #232323);
    border:none;
    width: 83%;
}

/* Color the active tab */
.active {
    background: linear-gradient(#3E3E3E, #2B2B2B);
    color: #white;
}

Body:
You can do it with the Flexbox and much less code:

/* basic CSS browser reset */
* {margin:0;padding:0;box-sizing:border-box}
html, body {width:100%;height:100%}

/* can comment out if you decide to use the below approach */
body {
  display: flex;
  justify-content: center; /* horizontal alignment / centering */
  align-items: flex-start; /* prevents the #menu to fill the remaining height of the body */
}

#menu {
  display: flex; /* displays children inline */
  align-items: flex-start;
  width: 50%; /* added */
  margin-top: 10%; /* added */
  /* alternative to center the #menu horizontally, in this case you don't need the styling on the body element
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  */
  list-style-type: none;
  background: radial-gradient(circle, #505050, #3E3E3E);
}

li {
  flex: 1; /* each takes as much width as it can, i.e. each 25% width of the parent */
  border-right: 1px solid #232323;
}

li:last-child {
  border: none;
}

li a {
  display: block;
  text-align: center;
  font: Verdana;
  font-size: 16px;
  color: #EAE0D2;
  padding: 20px 0;
  text-decoration: none;
}

li a:hover {
  background: linear-gradient(#2B2B2B, #232323);
}

.active {
  background: linear-gradient(#3E3E3E, #2B2B2B);
}

<ul id="menu">
  <li class="active"><a href="#">HOME</a></li>
  <li><a href="#">GALLERY</a></li>
  <li><a href="#">ART</a></li>
  <li><a href="#">CONTACT</a></li>
</ul>


问:
How to add fontawesome to angular CLI
I have an issue. I intall font-awesome by npm like this
npm install --save font-awesome
and later I add a style to :
`

```<code>"apps": [
    {
      "styles": [
        "../node_modules/font-awesome/css/font-awesome.css"
      ]
    }
</code>```

`
but it don't work in my app.
Am I doing something wrong or is there another way to add this to my project?
I also try by ref

答:
hello to my dear friend there is two way for it one of them is using angular-font-awesome and the other one is that you must go to angular-cli.json and add this

"styles": [
    "styles.css",
    "../node_modules/font-awesome/css/font-awesome.css"
],

but if you want to use angular-font-awesome you can use this npm package

Title: How to add fontawesome to angular CLI

Body:
I have an issue. I intall font-awesome by npm like this
npm install --save font-awesome
and later I add a style to :
`

"apps": [
    {
      "styles": [
        "../node_modules/font-awesome/css/font-awesome.css"
      ]
    }

`
but it don't work in my app.
Am I doing something wrong or is there another way to add this to my project?
I also try by ref


问:
deploy django apps using CherryPy
I want to deploy my django application using CherryPy. But I am looking for a pluggable apps instead of a scripts (which I'll just deploy it via apache)

Any good django apps that do that?

Thanks,
James

答: django-cpserver</p>

Title: deploy django apps using CherryPy

Body: django-cpserver


问:
Vue2 Router link from server data
I have a Vue2 SPA page which is loading content from the server.
It is editable by client in a CMS.

When user is adding relative link (lets say /about-us), this should be picked by Vue and treated as the menu link (which already has /about-us link).

However link to /about-us added in the content is reloading the whole page, so it is not picked as vue route.

How is it possible to attach router to such links?

What I did so far is changing the content in the backend response.

So I am essentially changing

```<code><a href="/about-us">Text</a>
</code>```

into

```<code><router-link :to="{ path: '/about-us'}">Text</router-link>
</code>```

Using:

```<code>function parseVueLinks($value)
{
    $pattern = "/<a([^>]*) href=\\\"[^http|https|mailto|tel]([^\\\"]*)\"([^>]*)>(.*?)<(\\/a>)/";
    $replace = "<router-link$1 :to=\"{ path: '$2'}\">$4</router-link>";

    return preg_replace($pattern, $replace, $value);
}
</code>```

Still no luck.

How is this possible?

答:
I think your replacement regex is good but is missing one /.
Indeed, after testing it, I see the result of parsing :

```<code><a href="/about-us">Text</a>
</code>```

outputs :

```<code><router-link :to="{ path: 'about-us'}">Text</router-link>
</code>```

instead of correct:

```<code><router-link :to="{ path: '/about-us'}">Text</router-link>
</code>```

(see about-us instead of /about-us)

Could you try this,please:

```<code>function parseVueLinks($value)
{
    $pattern = "/<a([^>]*) href=\\\"[^http|https|mailto|tel]([^\\\"]*)\"([^>]*)>(.*?)<(\\/a>)/";
    $replace = "<router-link$1 :to=\"{ path: '/$2'}\">$4</router-link>";

    return preg_replace($pattern, $replace, $value);
}
</code>```

Title: Vue2 Router link from server data

Body:
I have a Vue2 SPA page which is loading content from the server.
It is editable by client in a CMS.

When user is adding relative link (lets say /about-us), this should be picked by Vue and treated as the menu link (which already has /about-us link).

However link to /about-us added in the content is reloading the whole page, so it is not picked as vue route.

How is it possible to attach router to such links?

What I did so far is changing the content in the backend response.

So I am essentially changing

Text

into

<router-link :to="{ path: '/about-us'}">Text</router-link>

Using:

function parseVueLinks($value)
{
    $pattern = "/]*) href=\\\"[^http|https|mailto|tel]([^\\\"]*)\"([^>]*)>(.*?)<(\\/a>)/";
    $replace = "<router-link$1 :to=\"{ path: '$2'}\">$4</router-link>";

    return preg_replace($pattern, $replace, $value);
}

Still no luck.

How is this possible?

Body:
I think your replacement regex is good but is missing one /.
Indeed, after testing it, I see the result of parsing :

<a href="/about-us">Text</a>

outputs :

<router-link :to="{ path: 'about-us'}">Text</router-link>

instead of correct:

<router-link :to="{ path: '/about-us'}">Text</router-link>

(see about-us instead of /about-us)

Could you try this,please:

function parseVueLinks($value)
{
    $pattern = "/<a([^>]*) href=\\\"[^http|https|mailto|tel]([^\\\"]*)\"([^>]*)>(.*?)<(\\/a>)/";
    $replace = "<router-link$1 :to=\"{ path: '/$2'}\">$4</router-link>";

    return preg_replace($pattern, $replace, $value);
}