问:
Is it possible to get the current html5 video timeframe with milliseconds?
I am trying to build a live video captioning editor and require that the JS/DOM returns the current video timeframe with milliseconds. According to the DOM, video.currentTime only returns the value in seconds. Is there anyway to get the value in/with milliseconds? </p>

答:
ontimeupdate event gives your currentTime in seconds with milliseconds fraction represented as float number, so if you want milliseconds precision you should multiply by 1000. Here are some ways to approach it:

With low granularity timeupdate event tracking

window.onTimeUpdate = (e) => {
  console.log(Math.round(e.target.currentTime * 1000));
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video id="video" src="https://www.sample-videos.com/video701/mp4/240/big_buck_bunny_240p_30mb.mp4" width='320' height='240' ontimeupdate="onTimeUpdate(event)" controls='controls' autoplay></video></code>```

But delay between timeupdate event is pretty big starting from 200ms, so if you want more frequent update control you can try setInterval or requestAnimationFrame solutions, something like this:

var reqId;

var startTracking = function() {
  console.log(Math.round(video.currentTime * 1000));
  reqId = requestAnimationFrame(function play() {
    console.log(Math.round(video.currentTime * 1000));
    reqId = requestAnimationFrame(play);
  });
};

var stopTracking = function () {
  if (reqId) {
    cancelAnimationFrame(reqId);
  }
};

video.addEventListener('play', startTracking);

video.addEventListener('pause', stopTracking);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video id="video" src="https://www.sample-videos.com/video701/mp4/240/big_buck_bunny_240p_30mb.mp4" width='320' height='240' controls='controls' autoplay></video></code>```

Body:
ontimeupdate event gives your currentTime in seconds with milliseconds fraction represented as float number, so if you want milliseconds precision you should multiply by 1000. Here are some ways to approach it:

With low granularity timeupdate event tracking

window.onTimeUpdate = (e) => {
  console.log(Math.round(e.target.currentTime * 1000));
};

<video id="video" src="https://www.sample-videos.com/video701/mp4/240/big_buck_bunny_240p_30mb.mp4" width='320' height='240' ontimeupdate="onTimeUpdate(event)" controls='controls' autoplay></video>

But delay between timeupdate event is pretty big starting from 200ms, so if you want more frequent update control you can try setInterval or requestAnimationFrame solutions, something like this:

var reqId;

var startTracking = function() {
  console.log(Math.round(video.currentTime * 1000));
  reqId = requestAnimationFrame(function play() {
    console.log(Math.round(video.currentTime * 1000));
    reqId = requestAnimationFrame(play);
  });
};

var stopTracking = function () {
  if (reqId) {
    cancelAnimationFrame(reqId);
  }
};

video.addEventListener('play', startTracking);

video.addEventListener('pause', stopTracking);

<video id="video" src="https://www.sample-videos.com/video701/mp4/240/big_buck_bunny_240p_30mb.mp4" width='320' height='240' controls='controls' autoplay></video>

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Run ssh commands across all gce instances
I have a bunch of GCE instances and I want to run the same shell command on all of them. Is it possible to do something like gcloud compute ssh --command="ls -al" my-instance1 my-instance2 my-instance3?

答:
You can use gcloud compute instances list --format='value[separator=","](name,zone)' to get a list like:

```<code>my-instance1,my-zone1
my-instance2,my-zone2
my-instance3,my-zone3
</code>```

Then you can use bash Substring Removal to extract the parts before and after the comma.

```<code>var="before,after"
before="${var%,*}"
after="${var#*,}"
</code>```

Put it all in a loop and add trailing '&' to run things in the background:

```<code>for instance in $(gcloud compute instances list --format='value[separator=","](name,zone)'); do
  name="${instance%,*}";
  zone="${instance#*,}";
  gcloud compute ssh $name --zone=$zone --command="ls -al" &
done
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use gcloud compute instances list --format='value[separator=","](name,zone)' to get a list like:

my-instance1,my-zone1
my-instance2,my-zone2
my-instance3,my-zone3

Then you can use bash Substring Removal to extract the parts before and after the comma.

var="before,after"
before="${var%,*}"
after="${var#*,}"

Put it all in a loop and add trailing '&' to run things in the background:

for instance in $(gcloud compute instances list --format='value[separator=","](name,zone)'); do
  name="${instance%,*}";
  zone="${instance#*,}";
  gcloud compute ssh $name --zone=$zone --command="ls -al" &
done


问:
Possible bug - dijit/layout/ContentPane does not resize when adding widgets as children
Widget dijit/layout/ContentPane does not resize properly when adding widgets as children.

Steps to reproduce issue:

Open test case at https://jsfiddle.net/9eja3jtr/

Click 10 times button "Click me many times!".

Issue:

dijit/layout/ContentPane does not resize when adding widgets as children.
Content inserted is not fully visible.

I would need the dimensions for dijit/layout/ContentPane to be increased in order to accommodate new added widgets so that all inner widgets should be visible.

I think this is a bug within the dijit widget.I would like to know a workaround if any.

Notes:
I have reported bug to dojo https://bugs.dojotoolkit.org/ticket/19021

```<code>require(["dijit/layout/ContentPane", "dijit/TitlePane", "dijit/form/Button", "dojo/domReady!"], function(ContentPane, TitlePane, Button) {
  this._contentPanel = new ContentPane({
    style: "background-color:red;"
  }, "contentPanel");

  this._titlePanel = new TitlePane({
    title: "I'm a TitlePane",
    content: "Collapse me!"
  }, "titlePanel");

  this._button = new Button({
    label: "Click me many times!",
    onClick: function() {
      this._titlePanel.addChild(new Button({
        label: "Test",
        style: "width: 250px"
      }));
    }.bind(this)
  }, "button");

  this._contentPanel.addChild(this._titlePanel);
  this._titlePanel.addChild(this._button);
  this._contentPanel.startup();
});
</code>```

答:
You can make simple workaround by CSS:

```<code>#titlePanel {
  height: auto !important;
}
</code>```

See https://jsfiddle.net/9eja3jtr/3/

Body:
Widget dijit/layout/ContentPane does not resize properly when adding widgets as children.

Steps to reproduce issue:

Open test case at https://jsfiddle.net/9eja3jtr/

Click 10 times button "Click me many times!".

Issue:

dijit/layout/ContentPane does not resize when adding widgets as children.
Content inserted is not fully visible.

I would need the dimensions for dijit/layout/ContentPane to be increased in order to accommodate new added widgets so that all inner widgets should be visible.

I think this is a bug within the dijit widget.I would like to know a workaround if any.

Notes:
I have reported bug to dojo https://bugs.dojotoolkit.org/ticket/19021

require(["dijit/layout/ContentPane", "dijit/TitlePane", "dijit/form/Button", "dojo/domReady!"], function(ContentPane, TitlePane, Button) {
  this._contentPanel = new ContentPane({
    style: "background-color:red;"
  }, "contentPanel");

  this._titlePanel = new TitlePane({
    title: "I'm a TitlePane",
    content: "Collapse me!"
  }, "titlePanel");

  this._button = new Button({
    label: "Click me many times!",
    onClick: function() {
      this._titlePanel.addChild(new Button({
        label: "Test",
        style: "width: 250px"
      }));
    }.bind(this)
  }, "button");

  this._contentPanel.addChild(this._titlePanel);
  this._titlePanel.addChild(this._button);
  this._contentPanel.startup();
});

Body:
You can make simple workaround by CSS:

#titlePanel {
  height: auto !important;
}

See https://jsfiddle.net/9eja3jtr/3/


Title: Continuous wave like animation from wave line svg

Body:
Hello I have an svg that is a wavy line built with adobe illustrator and I'm trying to add a continuous wave like animation to it.

I've tried vivus.js and was able to get the draw animation working but not coninuously.

Does anyone have an idea on how to start something like this? I don't expect someone to do the problem for me but instead point me to the right direction, although im not opposed if someone has a quick answer.

Any answer will work wether its pure css, js or both.

Here is the svg

<svg id="wave" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 456.7 39.9" style="enable-background:new 0 0 456.7 39.9;" xml:space="preserve">

    <path class="st69" d="M4.2,33.2c0.1-0.1,7-6.9,15.9-13.8C27.7,13.7,38.7,6,47.5,6c7.5,0,14,6.6,20.3,12.9l0.4,0.4
    c6.8,6.9,14.6,14.6,24.6,14.6c9.9,0,17.7-7.8,24.5-14.6l0.5-0.5C124,12.5,130.5,6,137.9,6c7.5,0,13.9,6.5,20.2,12.9l0.4,0.4
    c6.8,6.9,14.6,14.6,24.5,14.6c10,0,17.8-7.8,24.6-14.6l0.5-0.5C214.4,12.5,220.9,6,228.4,6c7.5,0,14,6.5,20.2,12.9l0.4,0.4
    c6.8,6.9,14.5,14.6,24.5,14.6c9.9,0,17.7-7.8,24.5-14.6l0.3-0.3c6.3-6.4,12.9-13,20.5-13c7.5,0,14.1,6.6,20.4,13l0.3,0.3
    c6.8,6.9,14.6,14.6,24.5,14.6c9.9,0,17.6-7.8,24.5-14.6l0.2-0.2C395.1,12.6,401.6,6,409.2,6c8.7,0,19.8,7.7,27.3,13.4
    c8.9,6.8,15.9,13.7,16,13.8"/>
</svg>

and the jsfiddle link

here

Thanks!!

Body:
I hope this will help you. Play a little bit with the values or add the SVG wave as background, repeat it and change the background-position.

@keyframes wave {
  0% {
    left: -80px;
  }
  100% {
    left: 0;
  }
}

.container {
  width: 100px;
  overflow: hidden;
}
.container svg {
  position: relative;
  left: -50px;
  width: 200px;
  animation: wave 2s linear infinite;
}

<div class="container">
<svg id="wave" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 456.7 39.9" style="enable-background:new 0 0 456.7 39.9;" xml:space="preserve">
<style type="text/css">
    .st69{fill:none;stroke:#000000;stroke-width:12;stroke-miterlimit:10;}
</style>
    <path class="st69" d="M4.2,33.2c0.1-0.1,7-6.9,15.9-13.8C27.7,13.7,38.7,6,47.5,6c7.5,0,14,6.6,20.3,12.9l0.4,0.4
 c6.8,6.9,14.6,14.6,24.6,14.6c9.9,0,17.7-7.8,24.5-14.6l0.5-0.5C124,12.5,130.5,6,137.9,6c7.5,0,13.9,6.5,20.2,12.9l0.4,0.4
 c6.8,6.9,14.6,14.6,24.5,14.6c10,0,17.8-7.8,24.6-14.6l0.5-0.5C214.4,12.5,220.9,6,228.4,6c7.5,0,14,6.5,20.2,12.9l0.4,0.4
 c6.8,6.9,14.5,14.6,24.5,14.6c9.9,0,17.7-7.8,24.5-14.6l0.3-0.3c6.3-6.4,12.9-13,20.5-13c7.5,0,14.1,6.6,20.4,13l0.3,0.3
    c6.8,6.9,14.6,14.6,24.5,14.6c9.9,0,17.6-7.8,24.5-14.6l0.2-0.2C395.1,12.6,401.6,6,409.2,6c8.7,0,19.8,7.7,27.3,13.4
 c8.9,6.8,15.9,13.7,16,13.8"/>
</svg>
</div>


问:
Codeigniter index.php error
After removing my codeigniter project from a xampp server to a Live server i've got an error when trying to access my home page without index.php in front..

this is my route :

```<code>$route['home'] = 'Pages/view/home';
</code>```

this is my config :

```<code>$config['index_page'] = '';
$config['base_url'] = 'http://mysite/newsite';
$config['uri_protocol'] = 'REQUEST_URI';
</code>```

my .htaccess file :

```<code>RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
</code>```

so when i try to surf to www.mysite/home it gives me this error :

The requested URL /index.php/home was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to
  use an ErrorDocument to handle the request.

but when i surf to www.mysite/index.php/home it does work

I tried different htaccess files but without success

答:
I am on xampp with widows 10 I use these two

```<code>RewriteEngine on

# Next two lines get rid of trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ $1 [L,R=301]

RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</code>```

And

```<code>Options +FollowSymLinks
Options -Indexes
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</code>```

Also with your base url I would put / at the end of it

```<code>$config['base_url'] = 'http://localhost/yourproject/';
</code>```

Title: Codeigniter index.php error

Body:
After removing my codeigniter project from a xampp server to a Live server i've got an error when trying to access my home page without index.php in front..

this is my route :

$route['home'] = 'Pages/view/home';

this is my config :

$config['index_page'] = '';
$config['base_url'] = 'http://mysite/newsite';
$config['uri_protocol'] = 'REQUEST_URI';

my .htaccess file :

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

so when i try to surf to www.mysite/home it gives me this error :

The requested URL /index.php/home was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to
  use an ErrorDocument to handle the request.

but when i surf to www.mysite/index.php/home it does work

I tried different htaccess files but without success

Body:
I am on xampp with widows 10 I use these two

RewriteEngine on

# Next two lines get rid of trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ $1 [L,R=301]

RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

And

Options +FollowSymLinks
Options -Indexes
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Also with your base url I would put / at the end of it

$config['base_url'] = 'http://localhost/yourproject/';


问:
d3.js Double-click is not Releasing Nodes
I am attempting to convert a force-directed graph from d3 v3 to v4. My project is here:

https://bl.ocks.org/anonymous/337d113cb77c3695ac6959bebe728795

Why isn't the double-click action on the nodes releasing the node back into the normal force layout? The drag and pin related functions are directly below the node code.

答:
Once you set the d.fx and d.fy properties, the nodes will not move regardless of d.fixed. You set those properties here:

```<code>function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
}
</code>```

From the d3v4 API documentation:

To fix a node in a given position, you may specify two additional
  properties:

```<code>fx - the node’s fixed x-position
fy - the node’s fixed y-position
</code>```

At the end of each tick, after the application of any forces, a node
  with a defined node.fx has node.x reset to this value and node.vx set
  to zero; likewise, a node with a defined node.fy has node.y reset to
  this value and node.vy set to zero. To unfix a node that was
  previously fixed, set node.fx and node.fy to null, or delete these
  properties.

I didn't read this prior to making a demo forked from your block, but the effect is the same: I set the d.fx and d.fy properties to undefined on double click, which allows them to be positioned according to the force diagram.

The reason you might see use of d.fixed to fix positions is this is the method used in v3:

fixed - a boolean indicating whether node position is locked.

Body:
Once you set the d.fx and d.fy properties, the nodes will not move regardless of d.fixed. You set those properties here:

function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
}

From the d3v4 API documentation:

To fix a node in a given position, you may specify two additional
  properties:

fx - the node’s fixed x-position
fy - the node’s fixed y-position

At the end of each tick, after the application of any forces, a node
  with a defined node.fx has node.x reset to this value and node.vx set
  to zero; likewise, a node with a defined node.fy has node.y reset to
  this value and node.vy set to zero. To unfix a node that was
  previously fixed, set node.fx and node.fy to null, or delete these
  properties.

I didn't read this prior to making a demo forked from your block, but the effect is the same: I set the d.fx and d.fy properties to undefined on double click, which allows them to be positioned according to the force diagram.

The reason you might see use of d.fixed to fix positions is this is the method used in v3:

fixed - a boolean indicating whether node position is locked.


问:
Isolate nested sass map into new map
How can I isolate nested sass map into a new map? For example I have sass map like this:

```<code>$susy-setting: (
  s: (
    'columns': 4,
    'gutters': 30px,
  ),

  m: (
    'columns': 8,
    'gutters': 30px,
  ),

  l: (
    'columns': 12,
    'gutters': 30px,
  )
);
</code>```

Then I need to isolate each map inside after the loop, because my other mixin need map for its parameter.

```<code>@each $setting in $susy-setting{
    @include susy-settings-block($setting) { // This mixin need map
        @for $i from 1 through map-get($setting, 'columns') {
            @content;
        }
    }
}
</code>```

答:
To answer your primary question, you'll need to get both the key and value in your loop: @each $size, $setting in $susy-setting. The $size variable will store the key (e.g. s, m, l) while the $setting variable stores the map value assigned to that key.

EDIT: I saw your comment on my gist, which provides a bit more context. Try this:

```<code>@mixin susy-settings-block(
  $name,
  $config: $susy-settings
) {
  // store the old settings
  $global: $susy;

  // Get the new settings by name
  $new: map-get($config, $name);

  // apply the new settings
  $susy: map-merge($susy, $new) !global;

  // allow nested styles, using new settings
  @content;

  // return to the initial settings
  $susy: $global !global;
}
</code>```

Title: Isolate nested sass map into new map

Body:
How can I isolate nested sass map into a new map? For example I have sass map like this:

$susy-setting: (
  s: (
    'columns': 4,
    'gutters': 30px,
  ),

  m: (
    'columns': 8,
    'gutters': 30px,
  ),

  l: (
    'columns': 12,
    'gutters': 30px,
  )
);

Then I need to isolate each map inside after the loop, because my other mixin need map for its parameter.

@each $setting in $susy-setting{
    @include susy-settings-block($setting) { // This mixin need map
        @for $i from 1 through map-get($setting, 'columns') {
            @content;
        }
    }
}

Body:
To answer your primary question, you'll need to get both the key and value in your loop: @each $size, $setting in $susy-setting. The $size variable will store the key (e.g. s, m, l) while the $setting variable stores the map value assigned to that key.

EDIT: I saw your comment on my gist, which provides a bit more context. Try this:

@mixin susy-settings-block(
  $name,
  $config: $susy-settings
) {
  // store the old settings
  $global: $susy;

  // Get the new settings by name
  $new: map-get($config, $name);

  // apply the new settings
  $susy: map-merge($susy, $new) !global;

  // allow nested styles, using new settings
  @content;

  // return to the initial settings
  $susy: $global !global;
}


问:
How do you do a media query using SASS?
I've read through the SASS documentation and can only find how to do a media query using scss syntax instead of sass syntax (sass is the one that has strict white space without curly braces or semicolon). How do you do a media query using sass syntax? </p>

答:
It looks like a great place to use sass mixins.

You can use the sass @content to load inside everything within "brackets" (in my case within mixin use declaration indentions)

Here you have the sass mixin structure I use for handling media query. It is written in a way to give you freedom of implementation.

You can make some custom config preset and use it if that's what you want or you can customize it as you please. Even that you can find many different media query mixin handlers, I personally prefer to inject values into the mixins rather than define them within the mixing structure.

This is because of a couple of reasons. We can target device-specific width or height, or we could simply try to make it look good without width breakpoints. Sometimes this is simply more convenient and a better solution which is why we need a mixin that gives us full flexibility.

_mixins.sass

```<code>// mixin
=media($type1, $size1: null, $type2: null, $size2: null)
  @if ($type1) and ($size1) and ($type2) and ($size2)
    @media ($type1: $size1) and ($type2: $size2)
      @content
  @elseif ($type1) and ($size1) and not ($type2) and not ($size2)
    @media ($type1: $size1)
      @content
  @elseif ($type1) and not ($size1) and not ($type2) and not ($size2)
    $map: $type1
    @if map-has-key($map, "type2") and map-has-key($map, "size2")
      @media (#{map-get($map, "type1")}: #{map-get($map, "size1")}) and (#{map-get($map, "type2")}: #{map-get($map, "size2")})
        @content
    @else
      @media (#{map-get($map, "type1")}: #{map-get($map, "size1")})
        @content
  // ... add more conditions if aproppriate
  @else
    @error "Upsss...."
</code>```

_variables.sass

```<code>// width definition (optional)
$xs: "30em"
$s: "36em"
$m: "42em"
$ml: "48em"
$l: "54em"
$xl: "60em"
$xxl: "65em"

// options - types of restriction (optional)
$minw: "min-width"
$maxw: "max-width"
$minh: "min-height"
$maxh: "max-height"

// preset configuration (optional)
$mobile: ("type1": $minw, "size1": $s)
$tablet: ("type1": $minw, "size1": $m)
$laptop: ("type1": $minw, "size1": $ml)
$desktop: ("type1": $minw, "size1": $l)
$tv: ("type1": $minw, "size1": $xxl)
$wide: ("type1": $minw, "size1": $m, "type2": $maxh, "size2": $s)
</code>```

main.sass

```<code>@import variables
@import mixins

// use examples1 -------------- using variables
+media($minw, $xs)
  p
    font-size: 1em
    padding: 0px

// use examples2 -------------- using both varible and string
+media($minw, "1000px")
  p
    font-size: 2em
    padding: 10px

// use examples3 -------------- using strings only
+media("min-width", "62.5em")
  p
    font-size: 3em
    padding: 15px

// use examples4 -------------- using predefind configuration
+media($tablet)
  p
    font-size: 4em
    padding: 20px
</code>```

Title: How do you do a media query using SASS?

Body:
It looks like a great place to use sass mixins.

You can use the sass @content to load inside everything within "brackets" (in my case within mixin use declaration indentions)

Here you have the sass mixin structure I use for handling media query. It is written in a way to give you freedom of implementation.

You can make some custom config preset and use it if that's what you want or you can customize it as you please. Even that you can find many different media query mixin handlers, I personally prefer to inject values into the mixins rather than define them within the mixing structure.

This is because of a couple of reasons. We can target device-specific width or height, or we could simply try to make it look good without width breakpoints. Sometimes this is simply more convenient and a better solution which is why we need a mixin that gives us full flexibility.

_mixins.sass

// mixin
=media($type1, $size1: null, $type2: null, $size2: null)
  @if ($type1) and ($size1) and ($type2) and ($size2)
    @media ($type1: $size1) and ($type2: $size2)
      @content
  @elseif ($type1) and ($size1) and not ($type2) and not ($size2)
    @media ($type1: $size1)
      @content
  @elseif ($type1) and not ($size1) and not ($type2) and not ($size2)
    $map: $type1
    @if map-has-key($map, "type2") and map-has-key($map, "size2")
      @media (#{map-get($map, "type1")}: #{map-get($map, "size1")}) and (#{map-get($map, "type2")}: #{map-get($map, "size2")})
        @content
    @else
      @media (#{map-get($map, "type1")}: #{map-get($map, "size1")})
        @content
  // ... add more conditions if aproppriate
  @else
    @error "Upsss...."

_variables.sass

// width definition (optional)
$xs: "30em"
$s: "36em"
$m: "42em"
$ml: "48em"
$l: "54em"
$xl: "60em"
$xxl: "65em"

// options - types of restriction (optional)
$minw: "min-width"
$maxw: "max-width"
$minh: "min-height"
$maxh: "max-height"

// preset configuration (optional)
$mobile: ("type1": $minw, "size1": $s)
$tablet: ("type1": $minw, "size1": $m)
$laptop: ("type1": $minw, "size1": $ml)
$desktop: ("type1": $minw, "size1": $l)
$tv: ("type1": $minw, "size1": $xxl)
$wide: ("type1": $minw, "size1": $m, "type2": $maxh, "size2": $s)

main.sass

@import variables
@import mixins

// use examples1 -------------- using variables
+media($minw, $xs)
  p
    font-size: 1em
    padding: 0px

// use examples2 -------------- using both varible and string
+media($minw, "1000px")
  p
    font-size: 2em
    padding: 10px

// use examples3 -------------- using strings only
+media("min-width", "62.5em")
  p
    font-size: 3em
    padding: 15px

// use examples4 -------------- using predefind configuration
+media($tablet)
  p
    font-size: 4em
    padding: 20px


问:
Xcode warns about missing protocol definition, even though @protocol is used
Since I had a import-cycle recently, I'm moving all #import statements (concerning my own files) from the header into the corresponding .m-file. I also added @class and @protocol forward-declarations to soothe the compiler. However, I still get he following warning:

```<code>Cannot find the protocol definition for 'MyCustomDelegate'.
</code>```

As I said, there is an @protocol MyCustomDelegate before I use it in the @interface-Block. Interestingly this warning only occurs if the corresponding delegate is declared in another file (whose header is imported in the .m-file).

I read that one solution is to declare the delegate in a separate header file and import that file directly in the header of the class that implements the delegate. Is this really the way to go? Are there any other solutions? I think those delegates already bloated our code enough, now I should go on and even declare an own file for it?

Small sample code to better illustrate the problem:

NewFooController.h

```<code>#import <UIKit/UIKit.h>

@protocol NewFooControllerDelegate;

@interface NewFooController : UITableViewController
  @property (nonatomic, weak) id<NewFooControllerDelegate> delegate;
@end

@protocol NewFooControllerDelegate
@end
</code>```

HomeTableViewController.h

```<code>#import <UIKit/UIKit.h>
@protocol NewFooControllerDelegate;

// warning points to line below
@interface HomeTableViewController : UITableViewController <NewFooControllerDelegate>
@end
</code>```

HomeTableViewController.m

```<code>#import "HomeTableViewController.h"
#import "NewFooController.h"
@implementation HomeTableViewController
@end
</code>```

答:
Not sure if this is "best way", but try import header of class that implement protocol before class header file.

HomeTableViewController.m

```<code>#import "NewFooController.h"
#import "HomeTableViewController.h"

@implementation HomeTableViewController
@end
</code>```

And you can remove protocol declaration in HomeTableViewController.h

```<code>#import <UIKit/UIKit.h>

@interface HomeTableViewController : UITableViewController <NewFooControllerDelegate>
@end
</code>```

Body:
Since I had a import-cycle recently, I'm moving all #import statements (concerning my own files) from the header into the corresponding .m-file. I also added @class and @protocol forward-declarations to soothe the compiler. However, I still get he following warning:

Cannot find the protocol definition for 'MyCustomDelegate'.

As I said, there is an @protocol MyCustomDelegate before I use it in the @interface-Block. Interestingly this warning only occurs if the corresponding delegate is declared in another file (whose header is imported in the .m-file).

I read that one solution is to declare the delegate in a separate header file and import that file directly in the header of the class that implements the delegate. Is this really the way to go? Are there any other solutions? I think those delegates already bloated our code enough, now I should go on and even declare an own file for it?

Small sample code to better illustrate the problem:

NewFooController.h

#import <UIKit/UIKit.h>

@protocol NewFooControllerDelegate;

@interface NewFooController : UITableViewController
  @property (nonatomic, weak) id<NewFooControllerDelegate> delegate;
@end

@protocol NewFooControllerDelegate
@end

HomeTableViewController.h

#import <UIKit/UIKit.h>
@protocol NewFooControllerDelegate;

// warning points to line below
@interface HomeTableViewController : UITableViewController <NewFooControllerDelegate>
@end

HomeTableViewController.m

#import "HomeTableViewController.h"
#import "NewFooController.h"
@implementation HomeTableViewController
@end

Body:
Not sure if this is "best way", but try import header of class that implement protocol before class header file.

HomeTableViewController.m

#import "NewFooController.h"
#import "HomeTableViewController.h"

@implementation HomeTableViewController
@end

And you can remove protocol declaration in HomeTableViewController.h

#import <UIKit/UIKit.h>

@interface HomeTableViewController : UITableViewController <NewFooControllerDelegate>
@end


问:
how to configure jest with webpack, node_modules and scss

Update: edited jest config in package.json to include identity-obj-proxy and added transform-es2015-modules-commonjs to .babelrc

Trying to setup jest and enzyme to run unit tests on a React.js project.  This configuration setting works fine as long as I'm not requiring a node_module in the target component. But if the component I want to test imports a node_module that itself imports a scss file it throws this error:

import('../../scss/bulkAction.scss');
^^^^^^

SyntaxError: Unexpected token import```
</div>
</div>
</p>
<p>This is my jest config file:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"jest": {
  "testPathIgnorePatterns": [
    "<rootDir>/(node_modules)"
  ],
  "moduleFileExtensions": [
    "js",
    "jsx"
  ],
  "moduleDirectories": [
    "node_modules"
  ],
  "moduleNameMapper": {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/app/_tests_/config/fileMock.js",
          "\\.(css|scss)$": "identity-obj-proxy"
  },
  "transform": {
    "^.+\\.(js|jsx)$": "babel-jest",
    "^.+\\.(css|scss)$": "<rootDir>/app/_tests_/config/scssTransform.js",
    "^(?!.*\\.(js|jsx|json)$)": "<rootDir>/app/_tests_/config/fileTransform.js"
  }
},</code>```

this is my .babelrc file

{
  "presets": [
    ["es2015", {"modules": false}], "react", "stage-0"],
  "env": {
    "start": {
      "presets": [
        "react-hmre"
      ]
    },
    "test": {
      "presets": ["es2015", "react", "stage-0"],
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}```

I've tried multiple different configurations and have been reading the docs for quite awhile and haven't been able to solve this problem. I'm hoping someone can help!

Note about our file structure:

/WebApps/ProjectName/ProjectFolder/app

/WebApps/ProjectName/ProjectFolder/package.json
/WebApps/ProjectName/ProjectFolder/.babelrc
/WebApps/ProjectName/ProjectFolder/node_modules

I add this just incase the file pathing of the  may be part of the problem.

答:
You've missed probably transform-es2015-modules-commonjs babel plugin.

Add this to your .babelrc

```<code>// .babelrc
{
  "presets": [
    ["es2015", {"modules": false}]
  ],

  "env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}
</code>```

Remember to install this plugin before using:

```<code>babel-plugin-transform-es2015-modules-commonjs --save-dev
</code>```

When you run your tests with jest, it set the environment as test by default.

In my project I use also identity-obj-proxy, like:

```<code>// jest.config.json
{
  "moduleNameMapper": {
    "\\.(css|scss)$": "identity-obj-proxy"
  },
}
</code>```

Also, first install it before using:

```<code>npm install --save-dev identity-obj-proxy
</code>```

I highly recommend reading the page from official jest documentation about integration jest with webpack.

https://facebook.github.io/jest/docs/webpack.html#mocking-css-modules

https://facebook.github.io/jest/docs/webpack.html#using-with-webpack-2

Body:
Update: edited jest config in package.json to include identity-obj-proxy and added transform-es2015-modules-commonjs to .babelrc

Trying to setup jest and enzyme to run unit tests on a React.js project.  This configuration setting works fine as long as I'm not requiring a node_module in the target component. But if the component I want to test imports a node_module that itself imports a scss file it throws this error:

import('../../scss/bulkAction.scss');
^^^^^^

SyntaxError: Unexpected token import

This is my jest config file:

"jest": {
  "testPathIgnorePatterns": [
    "<rootDir>/(node_modules)"
  ],
  "moduleFileExtensions": [
    "js",
    "jsx"
  ],
  "moduleDirectories": [
    "node_modules"
  ],
  "moduleNameMapper": {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/app/_tests_/config/fileMock.js",
          "\\.(css|scss)$": "identity-obj-proxy"
  },
  "transform": {
    "^.+\\.(js|jsx)$": "babel-jest",
    "^.+\\.(css|scss)$": "<rootDir>/app/_tests_/config/scssTransform.js",
    "^(?!.*\\.(js|jsx|json)$)": "<rootDir>/app/_tests_/config/fileTransform.js"
  }
},

this is my .babelrc file

{
  "presets": [
    ["es2015", {"modules": false}], "react", "stage-0"],
  "env": {
    "start": {
      "presets": [
        "react-hmre"
      ]
    },
    "test": {
      "presets": ["es2015", "react", "stage-0"],
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

I've tried multiple different configurations and have been reading the docs for quite awhile and haven't been able to solve this problem. I'm hoping someone can help!

Note about our file structure:

/WebApps/ProjectName/ProjectFolder/app

/WebApps/ProjectName/ProjectFolder/package.json
/WebApps/ProjectName/ProjectFolder/.babelrc
/WebApps/ProjectName/ProjectFolder/node_modules

I add this just incase the file pathing of the  may be part of the problem.

Body:
You've missed probably transform-es2015-modules-commonjs babel plugin.

Add this to your .babelrc

// .babelrc
{
  "presets": [
    ["es2015", {"modules": false}]
  ],

  "env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

Remember to install this plugin before using:

babel-plugin-transform-es2015-modules-commonjs --save-dev

When you run your tests with jest, it set the environment as test by default.

In my project I use also identity-obj-proxy, like:

// jest.config.json
{
  "moduleNameMapper": {
    "\\.(css|scss)$": "identity-obj-proxy"
  },
}

Also, first install it before using:

npm install --save-dev identity-obj-proxy

I highly recommend reading the page from official jest documentation about integration jest with webpack.

https://facebook.github.io/jest/docs/webpack.html#mocking-css-modules

https://facebook.github.io/jest/docs/webpack.html#using-with-webpack-2


问:
Writing Regex in Python to Parse Preceding and Succeeding Texts
I am working on parsing XML dumps of English Wikipedia and have got stuck at writing killing regular expression in Python. I am attaching a sample data snippet as follows:

Amy Jean Klobuchar''' ({{IPAc-en|ˈ|k|l|oʊ|b|ə|ʃ|ɑr}}; born May 25,
  1960) is the [[Seniority in the United States Senate|senior]] [[United
  States Senator]] from [[Minnesota]]. She is a member of the
  [[Minnesota Democratic-Farmer-Labor Party]], an affiliate of the
  [[Democratic Party (United States)|Democratic Party]]. She is the
  first woman to be elected as a senator for Minnesota and is one of
  twenty-one women serving in the current [[United States Senate]].

She previously served as the [[county attorney]] for [[Hennepin
  County, Minnesota]], the most populous county in Minnesota. As an
  attorney, she worked with former [[Vice President of the United
  States|Vice President]] [[Walter Mondale]].{{cite web|
  author= Senate Web site| title = U.S. Senator for Minnesota Amy
  Klobuchar: Biography| year = 2007| url=
  [URL]| accessdate=
  2007-02-23|archiveurl =
  [URL]
  |archivedate = February 21, 2007}} She has been calld a "rising
  star" in the Democratic Party.{{Cite
  news|url=[URL]|title=Huffington
  Post names Klobuchar the smartest U.S.
  Senator|last=Tsukayama|first=Hayley|date=March 15,
  2010|work=|access-date=May 14,
  2017|archive-url=|archive-date=|dead-url=}}{{Cite
  news|url=[URL]|title=As
  state's only senator, Klobuchar gains sympathetic
  attention|last=Dizikes|first=Cynthia|date=May 20,
  2009|work=MinnPost|access-date=May 14,
  2017|archive-url=|archive-date=|dead-url=|language=en}}

==Early life and education==

Born in [[Plymouth, Minnesota]], Klobuchar is the daughter of Rose Katherine (née Heuberger), who
  retired at age 70 from teaching second grade,{{Cite
  news|url=[URL]|title=Rose
  Klobuchar, mother of Sen. Amy Klobuchar,
  dies|last=Nelson|first=Tim|access-date=2017-02-22}} and [[Jim
  Klobuchar|James John "Jim" Klobuchar]], an author and a retired
  sportswriter and columnist for the ''[[Star Tribune]]''.{{Cite
  news|url=[URL]|title=Born
  to ride: Jim Klobuchar and the birth of the Minnesota bike
  tour|newspaper=Star Tribune|access-date=2017-02-22}} Amy has one
  younger sister. Jim's grandparents were [[Slovene
  American|Slovene]] immigrants, and his father was a miner on the
  [[Iron Range]]; Amy's maternal grandparents were from
  [[Switzerland]].{{cite
  web|url=[URL]|title=1|work=rootsweb.com|accessdate=11
  September 2015}}

From this data, I want to parse 1) ref tags and content between and 2) section headers. For instance, ref tags and its content indicate

```<code><ref name=bio>
{{cite web
  |author=Senate Web site
  |title=U.S.Senator for Minnesota Amy Klobuchar: Biography
  |year=2007
  |url=[URL]
  |accessdate=2007-02-23
  |archiveurl=[URL]
  |archivedate = February 21, 2007}}
</ref>
</code>```

whereas a section header means

```<code>==Early life and education==
</code>```

I've actually succeeded in parsing these fields with following code:

```<code>import re

LEXEME = [
  ('ref', re.compile(r'<ref[^/>]*>[\s\S]*?</ref>)',
    re.M | re.I)),
  ('header', re.compile(r'(^|\n)((==[^=]+==)|(===[^=]+===)|(====[^=]+====))\s*$',
    re.M | re.I))]

GROUP_RE = re.compile(
  '|'.join('(?P<{0}>{1})'.format(name, regex.pattern)
    for name, regex in LEXEME),
  re.M | re.I)

for match in GROUP_RE.finditer(content):
  print(match.lastgroup, '\t', match.group(0), '\n')

# Output
ref  <ref name=bio>{{cite web| author= Senate Web site| title = U.S. Senator for Minnesota Amy Klobuchar: Biography| year = 2007| url= [URL]| accessdate= 2007-02-23|archiveurl = [URL] |archivedate = February 21, 2007}}</ref>
ref  <ref>{{Cite news|url=[URL]|title=Huffington Post names Klobuchar the smartest U.S. Senator|last=Tsukayama|first=Hayley|date=March 15, 2010|work=|access-date=May 14, 2017|archive-url=|archive-date=|dead-url=}}</ref>
ref  <ref>{{Cite news|url=[URL]|title=As state's only senator, Klobuchar gains sympathetic attention|last=Dizikes|first=Cynthia|date=May 20, 2009|work=MinnPost|access-date=May 14, 2017|archive-url=|archive-date=|dead-url=|language=en}}</ref>
header  ==Early life and education==
</code>```

I want to expand the current regex so that I can also get preceding and succeeding texts of up to 250 characters when parsing ref tags and its content.
For example, I want to get

```<code>She previously served as the [[county attorney]] for [[Hennepin County, Minnesota]], the most populous county in Minnesota. As an attorney, she worked with former [[Vice President of the United States|Vice President]] [[Walter Mondale]].
<ref name=bio>
{{cite web
  |author=Senate Web site
  |title=U.S. Senator for Minnesota Amy Klobuchar: Biography
  |year=2007
  |url=[URL]
  |accessdate=2007-02-23
  |archiveurl=[URL]
  |archivedate=February 21, 2007}}
</ref>
She has been called a "rising star" in the Democratic Party.<ref>{{Cite news|url=[URL]|title=Huffington Post names Klobuchar the smartest U.S
</code>```

instead of

```<code><ref name=bio>
{{cite web
  |author=Senate Web site
  |title=U.S. Senator for Minnesota Amy Klobuchar: Biography
  |year=2007
  |url=[URL]
  |accessdate=2007-02-23
  |archiveurl=[URL]
  |archivedate=February 21, 2007}}
</ref>
</code>```

So, I modified my code as follows:

```<code>LEXEME = [
  ('ref', re.compile(r'([\s\S]{1,250})(<ref[^/>]*>[\s\S]*?</ref>)([\s\S]{1,250}))',
    re.M | re.I)),
  ('header', re.compile(r'(^|\n)((==[^=]+==)|(===[^=]+===)|(====[^=]+====))\s*$',
    re.M | re.I))]
</code>```

Some problems arise

1) when multiple ref tags occur consecutively at the end of a sentence:

```<code><ref>{{Cite
news|url=[URL]|title=Huffington
Post names Klobuchar the smartest U.S.
Senator|last=Tsukayama|first=Hayley|date=March 15,
2010|work=|access-date=May 14,
2017|archive-url=|archive-date=|dead-url=}}</ref><ref>{{Cite
news|url=[URL]|title=As
state's only senator, Klobuchar gains sympathetic
attention|last=Dizikes|first=Cynthia|date=May 20,
2009|work=MinnPost|access-date=May 14,
2017|archive-url=|archive-date=|dead-url=|language=en}}</ref>
</code>```

The anticipated result was

```<code>ref  up-to-250-chars<ref>content</ref>up-to-250-chars
ref  up-to-250-chars<ref>content</ref>up-to-250-chars
</code>```

However, the code only captures the latter ref tags and related preceding/succeeding texts.

2) when section heading appears in succeeding text. ref regex captures the header as succeeding text and header regex is skipped as follows.

```<code>ref  s-date=May 14,
2017|archive-url=|archive-date=|dead-url=|language=en}}</ref>

==Early life and education== Born in [[Plymouth, Minnesota]], Klobuchar is the daughter of Rose Katherine (née Heuberger), who
retired at age 70 from teaching second grade,<ref>{{Cite
news|url=[URL]|title=Rose
Klobuchar, mother of Sen. Amy Klobuchar,
dies|last=Nelson|first=Tim|access-date=2017-02-22}}</ref> and [[Jim
Klobuchar|James John "Jim" Klobuchar]], an author and a retired
sportswriter and columnist for the ''[[Star Tribune]]''.<ref>{{Cite
news|url=[URL]
</code>```

I wonder how I can tackle this issue.

Happy coding!

答:
While this is (probably) possible with regex by making use of lookarounds, it's a lot easier to just use string operations:</p>

```<code>for match in GROUP_RE.finditer(content):
    start= max(0, match.start()-250)
    end= min(len(content), match.end()+250)
    matched_text= content[start:end]
</code>```

Body:
I am working on parsing XML dumps of English Wikipedia and have got stuck at writing killing regular expression in Python. I am attaching a sample data snippet as follows:

Amy Jean Klobuchar''' ({{IPAc-en|ˈ|k|l|oʊ|b|ə|ʃ|ɑr}}; born May 25,
  1960) is the [[Seniority in the United States Senate|senior]] [[United
  States Senator]] from [[Minnesota]]. She is a member of the
  [[Minnesota Democratic-Farmer-Labor Party]], an affiliate of the
  [[Democratic Party (United States)|Democratic Party]]. She is the
  first woman to be elected as a senator for Minnesota and is one of
  twenty-one women serving in the current [[United States Senate]].

She previously served as the [[county attorney]] for [[Hennepin
  County, Minnesota]], the most populous county in Minnesota. As an
  attorney, she worked with former [[Vice President of the United
  States|Vice President]] [[Walter Mondale]].{{cite web|
  author= Senate Web site| title = U.S. Senator for Minnesota Amy
  Klobuchar: Biography| year = 2007| url=
  [URL]| accessdate=
  2007-02-23|archiveurl =
  [URL]
  |archivedate = February 21, 2007}} She has been calld a "rising
  star" in the Democratic Party.{{Cite
  news|url=[URL]|title=Huffington
  Post names Klobuchar the smartest U.S.
  Senator|last=Tsukayama|first=Hayley|date=March 15,
  2010|work=|access-date=May 14,
  2017|archive-url=|archive-date=|dead-url=}}{{Cite
  news|url=[URL]|title=As
  state's only senator, Klobuchar gains sympathetic
  attention|last=Dizikes|first=Cynthia|date=May 20,
  2009|work=MinnPost|access-date=May 14,
  2017|archive-url=|archive-date=|dead-url=|language=en}}

==Early life and education==

Born in [[Plymouth, Minnesota]], Klobuchar is the daughter of Rose Katherine (née Heuberger), who
  retired at age 70 from teaching second grade,{{Cite
  news|url=[URL]|title=Rose
  Klobuchar, mother of Sen. Amy Klobuchar,
  dies|last=Nelson|first=Tim|access-date=2017-02-22}} and [[Jim
  Klobuchar|James John "Jim" Klobuchar]], an author and a retired
  sportswriter and columnist for the ''[[Star Tribune]]''.{{Cite
  news|url=[URL]|title=Born
  to ride: Jim Klobuchar and the birth of the Minnesota bike
  tour|newspaper=Star Tribune|access-date=2017-02-22}} Amy has one
  younger sister. Jim's grandparents were [[Slovene
  American|Slovene]] immigrants, and his father was a miner on the
  [[Iron Range]]; Amy's maternal grandparents were from
  [[Switzerland]].{{cite
  web|url=[URL]|title=1|work=rootsweb.com|accessdate=11
  September 2015}}

From this data, I want to parse 1) ref tags and content between and 2) section headers. For instance, ref tags and its content indicate

<ref name=bio>
{{cite web
  |author=Senate Web site
  |title=U.S.Senator for Minnesota Amy Klobuchar: Biography
  |year=2007
  |url=[URL]
  |accessdate=2007-02-23
  |archiveurl=[URL]
  |archivedate = February 21, 2007}}
</ref>

whereas a section header means

==Early life and education==

I've actually succeeded in parsing these fields with following code:

import re

LEXEME = [
  ('ref', re.compile(r'<ref[^/>]*>[\s\S]*?</ref>)',
    re.M | re.I)),
  ('header', re.compile(r'(^|\n)((==[^=]+==)|(===[^=]+===)|(====[^=]+====))\s*$',
    re.M | re.I))]

GROUP_RE = re.compile(
  '|'.join('(?P<{0}>{1})'.format(name, regex.pattern)
    for name, regex in LEXEME),
  re.M | re.I)

for match in GROUP_RE.finditer(content):
  print(match.lastgroup, '\t', match.group(0), '\n')

# Output
ref  <ref name=bio>{{cite web| author= Senate Web site| title = U.S. Senator for Minnesota Amy Klobuchar: Biography| year = 2007| url= [URL]| accessdate= 2007-02-23|archiveurl = [URL] |archivedate = February 21, 2007}}</ref>
ref  <ref>{{Cite news|url=[URL]|title=Huffington Post names Klobuchar the smartest U.S. Senator|last=Tsukayama|first=Hayley|date=March 15, 2010|work=|access-date=May 14, 2017|archive-url=|archive-date=|dead-url=}}</ref>
ref  <ref>{{Cite news|url=[URL]|title=As state's only senator, Klobuchar gains sympathetic attention|last=Dizikes|first=Cynthia|date=May 20, 2009|work=MinnPost|access-date=May 14, 2017|archive-url=|archive-date=|dead-url=|language=en}}</ref>
header  ==Early life and education==

I want to expand the current regex so that I can also get preceding and succeeding texts of up to 250 characters when parsing ref tags and its content.
For example, I want to get

She previously served as the [[county attorney]] for [[Hennepin County, Minnesota]], the most populous county in Minnesota. As an attorney, she worked with former [[Vice President of the United States|Vice President]] [[Walter Mondale]].
<ref name=bio>
{{cite web
  |author=Senate Web site
  |title=U.S. Senator for Minnesota Amy Klobuchar: Biography
  |year=2007
  |url=[URL]
  |accessdate=2007-02-23
  |archiveurl=[URL]
  |archivedate=February 21, 2007}}
</ref>
She has been called a "rising star" in the Democratic Party.<ref>{{Cite news|url=[URL]|title=Huffington Post names Klobuchar the smartest U.S

instead of

<ref name=bio>
{{cite web
  |author=Senate Web site
  |title=U.S. Senator for Minnesota Amy Klobuchar: Biography
  |year=2007
  |url=[URL]
  |accessdate=2007-02-23
  |archiveurl=[URL]
  |archivedate=February 21, 2007}}
</ref>

So, I modified my code as follows:

LEXEME = [
  ('ref', re.compile(r'([\s\S]{1,250})(<ref[^/>]*>[\s\S]*?</ref>)([\s\S]{1,250}))',
    re.M | re.I)),
  ('header', re.compile(r'(^|\n)((==[^=]+==)|(===[^=]+===)|(====[^=]+====))\s*$',
    re.M | re.I))]

Some problems arise

1) when multiple ref tags occur consecutively at the end of a sentence:

<ref>{{Cite
news|url=[URL]|title=Huffington
Post names Klobuchar the smartest U.S.
Senator|last=Tsukayama|first=Hayley|date=March 15,
2010|work=|access-date=May 14,
2017|archive-url=|archive-date=|dead-url=}}</ref><ref>{{Cite
news|url=[URL]|title=As
state's only senator, Klobuchar gains sympathetic
attention|last=Dizikes|first=Cynthia|date=May 20,
2009|work=MinnPost|access-date=May 14,
2017|archive-url=|archive-date=|dead-url=|language=en}}</ref>

The anticipated result was

ref  up-to-250-chars<ref>content</ref>up-to-250-chars
ref  up-to-250-chars<ref>content</ref>up-to-250-chars

However, the code only captures the latter ref tags and related preceding/succeeding texts.

2) when section heading appears in succeeding text. ref regex captures the header as succeeding text and header regex is skipped as follows.

ref  s-date=May 14,
2017|archive-url=|archive-date=|dead-url=|language=en}}</ref>

==Early life and education== Born in [[Plymouth, Minnesota]], Klobuchar is the daughter of Rose Katherine (née Heuberger), who
retired at age 70 from teaching second grade,<ref>{{Cite
news|url=[URL]|title=Rose
Klobuchar, mother of Sen. Amy Klobuchar,
dies|last=Nelson|first=Tim|access-date=2017-02-22}}</ref> and [[Jim
Klobuchar|James John "Jim" Klobuchar]], an author and a retired
sportswriter and columnist for the ''[[Star Tribune]]''.<ref>{{Cite
news|url=[URL]

I wonder how I can tackle this issue.

Happy coding!

Body:
While this is (probably) possible with regex by making use of lookarounds, it's a lot easier to just use string operations:

for match in GROUP_RE.finditer(content):
    start= max(0, match.start()-250)
    end= min(len(content), match.end()+250)
    matched_text= content[start:end]


问:
Python - Using attributes to parse XML tree
There are a lot of examples on how to parse XML using tags in the tree, but what if (as in the example below) many of the tags have the same name?

```<code><SoccerFeed timestamp="20161221T144346+0000">
  <SoccerDocument Type="SQUADS Latest">
    <Team country="USA">
      <Founded>1998</Founded>
      <Name>Chicago Fire</Name>
      <Player uID="p113757">
        <Name>Patrick McLain</Name>
        <Position>Goalkeeper</Position>
        <Stat Type="first_name">Patrick</Stat>
        <Stat Type="last_name">McLain</Stat>
        <Stat Type="birth_date">1988-08-22</Stat>
        <Stat Type="birth_place">Eau Claire</Stat>
        <Stat Type="first_nationality">USA</Stat>
        <Stat Type="weight">94</Stat>
        <Stat Type="height">191</Stat>
        <Stat Type="jersey_num">23</Stat>
        <Stat Type="real_position">Goalkeeper</Stat>
        <Stat Type="real_position_side">Unknown</Stat>
        <Stat Type="join_date">2016-01-18</Stat>
        <Stat Type="country">USA</Stat>
      </Player>
    </Team>
  </SoccerDocument>
</SoccerFeed>
</code>```

If I wanted to parse only elements with a 'Stat' tag and a 'first_name' attribute, how would I do that?

答:
You can use BeautifulSoup within XML parser, like this example:

```<code>from bs4 import BeautifulSoup as bs

data = '''<SoccerFeed timestamp="20161221T144346+0000">
  <SoccerDocument Type="SQUADS Latest">
    <Team country="USA">
      <Founded>1998</Founded>
      <Name>Chicago Fire</Name>
      <Player uID="p113757">
        <Name>Patrick McLain</Name>
        <Position>Goalkeeper</Position>
        <Stat Type="first_name">Patrick</Stat>
        <Stat Type="last_name">McLain</Stat>
        <Stat Type="birth_date">1988-08-22</Stat>
        <Stat Type="birth_place">Eau Claire</Stat>
        <Stat Type="first_nationality">USA</Stat>
        <Stat Type="weight">94</Stat>
        <Stat Type="height">191</Stat>
        <Stat Type="jersey_num">23</Stat>
        <Stat Type="real_position">Goalkeeper</Stat>
        <Stat Type="real_position_side">Unknown</Stat>
        <Stat Type="join_date">2016-01-18</Stat>
        <Stat Type="country">USA</Stat>
      </Player>
    </Team>
  </SoccerDocument>
</SoccerFeed>'''

sub = bs(data, 'xml')
# Find all the 'Stat' tags
stat_tags = sub.findAll('Stat')
for k in stat_tags:
    # Extract the text between 'Stat' tags
    print(k.text)
</code>```

Output:

```<code>Patrick
McLain
1988-08-22
Eau Claire
USA
94
191
23
Goalkeeper
Unknown
2016-01-18
USA
</code>```

Body:
There are a lot of examples on how to parse XML using tags in the tree, but what if (as in the example below) many of the tags have the same name?

<SoccerFeed timestamp="20161221T144346+0000">
  <SoccerDocument Type="SQUADS Latest">
    <Team country="USA">
      <Founded>1998</Founded>
      <Name>Chicago Fire</Name>
      <Player uID="p113757">
        <Name>Patrick McLain</Name>
        <Position>Goalkeeper</Position>
        <Stat Type="first_name">Patrick</Stat>
        <Stat Type="last_name">McLain</Stat>
        <Stat Type="birth_date">1988-08-22</Stat>
        <Stat Type="birth_place">Eau Claire</Stat>
        <Stat Type="first_nationality">USA</Stat>
        <Stat Type="weight">94</Stat>
        <Stat Type="height">191</Stat>
        <Stat Type="jersey_num">23</Stat>
        <Stat Type="real_position">Goalkeeper</Stat>
        <Stat Type="real_position_side">Unknown</Stat>
        <Stat Type="join_date">2016-01-18</Stat>
        <Stat Type="country">USA</Stat>
      </Player>
    </Team>
  </SoccerDocument>
</SoccerFeed>

If I wanted to parse only elements with a 'Stat' tag and a 'first_name' attribute, how would I do that?

Body:
You can use BeautifulSoup within XML parser, like this example:

from bs4 import BeautifulSoup as bs

data = '''<SoccerFeed timestamp="20161221T144346+0000">
  <SoccerDocument Type="SQUADS Latest">
    <Team country="USA">
      <Founded>1998</Founded>
      <Name>Chicago Fire</Name>
      <Player uID="p113757">
        <Name>Patrick McLain</Name>
        <Position>Goalkeeper</Position>
        <Stat Type="first_name">Patrick</Stat>
        <Stat Type="last_name">McLain</Stat>
        <Stat Type="birth_date">1988-08-22</Stat>
        <Stat Type="birth_place">Eau Claire</Stat>
        <Stat Type="first_nationality">USA</Stat>
        <Stat Type="weight">94</Stat>
        <Stat Type="height">191</Stat>
        <Stat Type="jersey_num">23</Stat>
        <Stat Type="real_position">Goalkeeper</Stat>
        <Stat Type="real_position_side">Unknown</Stat>
        <Stat Type="join_date">2016-01-18</Stat>
        <Stat Type="country">USA</Stat>
      </Player>
    </Team>
  </SoccerDocument>
</SoccerFeed>'''

sub = bs(data, 'xml')
# Find all the 'Stat' tags
stat_tags = sub.findAll('Stat')
for k in stat_tags:
    # Extract the text between 'Stat' tags
    print(k.text)

Output:

Patrick
McLain
1988-08-22
Eau Claire
USA
94
191
23
Goalkeeper
Unknown
2016-01-18
USA


问:
Get SVG root element and its children from an <object> node to export SVG with dynamic content
I have made a billing model made in InkScape (because I love SVG).
I'd like to generate new SVG without having to do it manually in InkScape (update the date, the amount, the customer email etc).

To achieve that this is what I've came up so far (a lot of this code where found on other post about SVG and Javscript) :

To make it easy, let's say I have a HTML page with an  which is displaying my billing model

```<code><button onclick="addDownloadLink()">Add download hyperlink</button>
<br />
<div id="exportLinkContainer"></div>
<br />
<!-- Size is based on a ratio of 210x297 -->
<object id="svgObject" data="./BillingModel.svg" type="image/svg+xml" width="630" height="891">No SVG support</object>
</code>```

On a button action, i call a javascript function

```<code>function addDownloadLink() {
    var svgObject = document.getElementById("svgObject").contentDocument;

    // THIS IS HERE where I can't find how to get the root svg element and all its attributs.
    var svg = svgObject.getElementById("svg").innerHTML;
    var svg2 = svgObject.getElementsByTagName("svg")[0].innerHTML;
    console.log("svg: " + svg);
    console.log("svg2: " + svg2);

    var blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
    var dateNow = new Date().toLocaleDateString();
    var downloadLink = document.createElement("a");
    downloadLink.appendChild(document.createTextNode("Download " + dateNow));
    downloadLink.setAttribute("download", "BillingExport___" + dateNow + ".svg");
    downloadLink.setAttribute("target", "_blank");
    downloadLink.setAttribute("href-lang", 'image/svg+xml');
    downloadLink.setAttribute("href", URL.createObjectURL(blob));

    var exportLinkContainer = document.getElementById("exportLinkContainer");
    exportContainer.innerHTML = '';
    exportContainer.appendChild(downloadLink);
}
</code>```

And here is an exemple of my svg file named BillingExportModel.svg :

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:cc="http://creativecommons.org/ns#"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:svg="http://www.w3.org/2000/svg"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
    xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
    sodipodi:docname="BillingExportModel.svg"
    inkscape:export-filename="/Users/Racine/Desktop/facture_1703_microsoft.png"
    height="297mm"
    width="210mm"
    inkscape:export-xdpi="202"
    version="1.1"
    inkscape:export-ydpi="202"
    inkscape:version="0.91 r13725"
    viewBox="0 0 210 297"
    id="svg">
    <!-- My script manage to get everything here inside the SVG root element. I need to get its parent and all its attributs. -->
    <!-- presentation stuff etc hidden because of not being usefull -->
    <text
        style="word-spacing:0px;letter-spacing:0px"
        line-height="125%"
        xml:space="preserve"
        y="134.65009"
        x="175.17645"
        sodipodi:linespacing="125%"
        id="text206">
        <tspan
            id="TextArticleTotal"
            sodipodi:role="line"
            x="175.17645"
            y="134.65009">1 450,00 €</tspan>
    </text>
    <!-- etc etc etc -->
</svg>
</code>```

It almost works expet that I don't manage to get the svg root element and all attributs like viewbox etc. But I have all the SVG content which is nice.

I can still copy all the svg root node inside my script in a var and concatenate that with I manage to have but I'm not happy with this solution and think I can do better.

Any help would be very appreciate ;)
Thanks

答:
Substitute outerHTML where you currently have innerHTML and use documentElement to get the root element. outerHTML returns the element itself and its descendants rather than just the descendants.

So the working lines are:

```<code>var svgObject = document.getElementById("svgObject");
var svg = svgObject.documentElement.outerHTML;
</code>```

You don't need to give the root element an id unless you particularly want to.

As an aside setting href-lang to image/svg+xml is wrong too. The attribute to set with that value is type.

Body:
I have made a billing model made in InkScape (because I love SVG).
I'd like to generate new SVG without having to do it manually in InkScape (update the date, the amount, the customer email etc).

To achieve that this is what I've came up so far (a lot of this code where found on other post about SVG and Javscript) :

To make it easy, let's say I have a HTML page with an  which is displaying my billing model

<button onclick="addDownloadLink()">Add download hyperlink</button>

<object id="svgObject" data="./BillingModel.svg" type="image/svg+xml" width="630" height="891">No SVG support</object>

On a button action, i call a javascript function

function addDownloadLink() {
    var svgObject = document.getElementById("svgObject").contentDocument;

    // THIS IS HERE where I can't find how to get the root svg element and all its attributs.
    var svg = svgObject.getElementById("svg").innerHTML;
    var svg2 = svgObject.getElementsByTagName("svg")[0].innerHTML;
    console.log("svg: " + svg);
    console.log("svg2: " + svg2);

    var blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
    var dateNow = new Date().toLocaleDateString();
    var downloadLink = document.createElement("a");
    downloadLink.appendChild(document.createTextNode("Download " + dateNow));
    downloadLink.setAttribute("download", "BillingExport___" + dateNow + ".svg");
    downloadLink.setAttribute("target", "_blank");
    downloadLink.setAttribute("href-lang", 'image/svg+xml');
    downloadLink.setAttribute("href", URL.createObjectURL(blob));

    var exportLinkContainer = document.getElementById("exportLinkContainer");
    exportContainer.innerHTML = '';
    exportContainer.appendChild(downloadLink);
}

And here is an exemple of my svg file named BillingExportModel.svg :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:cc="http://creativecommons.org/ns#"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:svg="http://www.w3.org/2000/svg"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
    xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
    sodipodi:docname="BillingExportModel.svg"
    inkscape:export-filename="/Users/Racine/Desktop/facture_1703_microsoft.png"
    height="297mm"
    width="210mm"
    inkscape:export-xdpi="202"
    version="1.1"
    inkscape:export-ydpi="202"
    inkscape:version="0.91 r13725"
    viewBox="0 0 210 297"
    id="svg">

    <text
        style="word-spacing:0px;letter-spacing:0px"
        line-height="125%"
        xml:space="preserve"
        y="134.65009"
        x="175.17645"
        sodipodi:linespacing="125%"
        id="text206">
        <tspan
            id="TextArticleTotal"
            sodipodi:role="line"
            x="175.17645"
            y="134.65009">1 450,00 €</tspan>
    </text>

</svg>

It almost works expet that I don't manage to get the svg root element and all attributs like viewbox etc. But I have all the SVG content which is nice.

I can still copy all the svg root node inside my script in a var and concatenate that with I manage to have but I'm not happy with this solution and think I can do better.

Any help would be very appreciate ;)
Thanks

Body:
Substitute outerHTML where you currently have innerHTML and use documentElement to get the root element. outerHTML returns the element itself and its descendants rather than just the descendants.

So the working lines are:

var svgObject = document.getElementById("svgObject");
var svg = svgObject.documentElement.outerHTML;

You don't need to give the root element an id unless you particularly want to.

As an aside setting href-lang to image/svg+xml is wrong too. The attribute to set with that value is type.


问:
Best and worst case runtimes of my search algorithm (similar to bubble sort)?
So I know this algorithm is pretty simple, but I can't wrap my head around the time complexity of the code. It takes in an array (say 5 numbers) and sorts it in increasing order and in a similar manner to bubble sort (but not quite the same). What are the best and worst case runtimes of this algorithm?

```<code>int sort(int arr[1...n]){
  while(i <= n){
    k = n;
    while(k >= i+1){
      if (arr[k-1] > arr[k]){
        tmp = arr[k-1];
        arr[k-1] = arr[k];
        arr[k] = tmp;
      }
      k--;
    }
    i++;
  }
}
</code>```

My reasoning:

The worst case would be if the array was in reverse sorted order, say [5,4,3,2,1]. I know the outer while loop would be executed n times, but the inner while loop is what throws me off. For each iteration of the outer while, I think the inner while executes i+1 times, so with the array I gave, it would execute the inner while 4,3,2,and then finally 1 time (that's a total of (n-1) executions of the inner while loop)...Putting it together I have n*(n-1), so does that mean worst case is O(n^2)?

The best case is when the array is already sorted, say [1,2,3,4,5].So in that case we would never need to do nay swapping of numbers, and the if statement in the inner while is never executed. But the code seems to loop through everything despite the fact that the array is already sorted. We still go through both while loops which leads me to believe it's still n*(n-1), but that seems off to me. Any help is appreciated.

答:
It's no surprise that the code "loops through everything," even when the array is already sorted. You don't tell it not to.

You need to add a sentinel value that tells it stop when the array is already sorted.

In your code, if the internal if statement is never entered during a single pass, then you know that the array is sorted. So what you do is initialize a flag at the start of each iteration of the outer loop. If the if statement is ever entered, then you set the flag. If, the flag is not set at the end of the out loop iteration, then you know that the array is sorted. Here's the code:

```<code>int sort(int arr[1...n]){
  bool didSwap = true;
  while(i <= n && didSwap){
    didSwap = false;
    k = n;
    while(k >= i+1){
      if (arr[k-1] > arr[k]){
        tmp = arr[k-1];
        arr[k-1] = arr[k];
        arr[k] = tmp;
        didSwap = true;
      }
      k--;
    }
    i++;
  }
}
</code>```

That will make your code "early out" when the array is sorted.

Body:
So I know this algorithm is pretty simple, but I can't wrap my head around the time complexity of the code. It takes in an array (say 5 numbers) and sorts it in increasing order and in a similar manner to bubble sort (but not quite the same). What are the best and worst case runtimes of this algorithm?

int sort(int arr[1...n]){
  while(i <= n){
    k = n;
    while(k >= i+1){
      if (arr[k-1] > arr[k]){
        tmp = arr[k-1];
        arr[k-1] = arr[k];
        arr[k] = tmp;
      }
      k--;
    }
    i++;
  }
}

My reasoning:

The worst case would be if the array was in reverse sorted order, say [5,4,3,2,1]. I know the outer while loop would be executed n times, but the inner while loop is what throws me off. For each iteration of the outer while, I think the inner while executes i+1 times, so with the array I gave, it would execute the inner while 4,3,2,and then finally 1 time (that's a total of (n-1) executions of the inner while loop)...Putting it together I have n*(n-1), so does that mean worst case is O(n^2)?

The best case is when the array is already sorted, say [1,2,3,4,5].So in that case we would never need to do nay swapping of numbers, and the if statement in the inner while is never executed. But the code seems to loop through everything despite the fact that the array is already sorted. We still go through both while loops which leads me to believe it's still n*(n-1), but that seems off to me. Any help is appreciated.

Body:
It's no surprise that the code "loops through everything," even when the array is already sorted. You don't tell it not to.

You need to add a sentinel value that tells it stop when the array is already sorted.

In your code, if the internal if statement is never entered during a single pass, then you know that the array is sorted. So what you do is initialize a flag at the start of each iteration of the outer loop. If the if statement is ever entered, then you set the flag. If, the flag is not set at the end of the out loop iteration, then you know that the array is sorted. Here's the code:

int sort(int arr[1...n]){
  bool didSwap = true;
  while(i <= n && didSwap){
    didSwap = false;
    k = n;
    while(k >= i+1){
      if (arr[k-1] > arr[k]){
        tmp = arr[k-1];
        arr[k-1] = arr[k];
        arr[k] = tmp;
        didSwap = true;
      }
      k--;
    }
    i++;
  }
}

That will make your code "early out" when the array is sorted.


问:
Storing DOUBLE vs INT --> Query time and Ingest time
I have a column that is of numeric type. I'm not sure whether it will be a whole number or a decimal number. There are two options here:

I can store the numbers as a DOUBLE whether it's whole or decimal.

I can infer the type and store the numbers as a DOUBLE if it's a decimal or INT if it's whole.

My question then is, it is much simpler to store it as a DOUBLE (because an int can just be represented as "5.0"), so what's the difference in Ingest time and query time if something is stored as a double vs an int. How 'expensive' is it to incorrectly store the type of an INT as a DOUBLE?

答:
According to the BigQuery pricing table, both integers and floating point numbers use 8 bytes, so actual cost will be the same.

The BigQuery floating point type is 64 bits. (I believe DOUBLE, FLOAT, and FLOAT64 are synonyms, based on the REST docs)


问:
How do I make a placeholder for a 'select' box?
I'm using placeholders for text inputs which is working out just fine. But I'd like to use a placeholder for my selectboxes as well. Of course I can just use this code:

```<code><select>
    <option value="">Select your option</option>
    <option value="hurr">Durr</option>
</select>
</code>```

But the 'Select your option' is in black instead of lightgrey. So my solution could possibly be CSS-based. jQuery is fine too.

This only makes the option grey in the dropdown (so after clicking the arrow):

option:first {
    color: #999;
}
```

<p>The question is: How do people create placeholders in selectboxes? But it has already been answered, cheers.</p>

<p>And using this results in the selected value always being grey (even after selecting a real option):</p>

<pre class="lang-css prettyprint-override"><code>select {
    color: #999;
}
</code>```

答:
Here is a CSS solution that works beautifully. The content is added (and absolutely positioned relative to the container) after the containing element (via :after pseudo-class).

It gets its text from the placeholder attribute that I defined where I used the directive (attr(placeholder)). Another key factor is pointer-events: none - this allows clicks on the placeholder text to pass through to the select. Otherwise it won't drop down if the user clicks the text.

I add the .empty class myself in my select directive, but normally I find that angular adds/removes .ng-empty for me (I assume it's because I'm injecting version 1.2 of Angular in my code sample).

(The sample also demonstrates how to wrap HTML elements in AngularJS to create your own custom inputs)

var app = angular.module("soDemo", []);
app.controller("soDemoController", function($scope) {
  var vm = {};
  vm.names = [{
      id: 1,
      name: 'Jon'
    },
    {
      id: 2,
      name: 'Joe'
    }, {
      id: 3,
      name: 'Bob'
    }, {
      id: 4,
      name: 'Jane'
    }
  ];
  vm.nameId;
  $scope.vm = vm;
});

app.directive('soSelect', function soSelect() {
  var directive = {
    restrict: 'E',
    require: 'ngModel',
    scope: {
      'valueProperty': '@',
      'displayProperty': '@',
      'modelProperty': '=',
      'source': '=',
    },
    link: link,
    template: getTemplate
  };
  return directive;

  /////////////////////////////////
  function link(scope, element, attrs, ngModelController) {
    init();
    return;

    ///////////// IMPLEMENTATION

    function init() {
      initDataBinding();
    }

    function initDataBinding() {
      ngModelController.$render = function() {
        if (scope.model === ngModelController.$viewValue) return;
        scope.model = ngModelController.$viewValue;
      }

      scope.$watch('model', function(newValue) {
        if (newValue === undefined) {
          element.addClass('empty');
          return;
        }
        element.removeClass('empty');
        ngModelController.$setViewValue(newValue);
      });
    }
  }

  function getTemplate(element, attrs) {
    var attributes = [
      'ng-model="model"',
      'ng-required="true"'
    ];

    if (angular.isDefined(attrs.placeholder)) {
      attributes.push('placeholder="{{placeholder}}"');
    }

    var ngOptions = '';

    if (angular.isDefined(attrs.valueProperty)) {
      ngOptions += 'item.' + attrs.valueProperty + ' as ';
    }

    ngOptions += 'item.' + attrs.displayProperty + ' for item in source';
    ngOptions += '"';
    attributes.push('ng-options="' + ngOptions + '"');

    var html = '<select ' + attributes.join(' ') + '></select>';

    return html;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>so-select {
  position: relative;
}

so-select select {
  font-family: 'Helvetica';
  display: inline-block;
  height: 24px;
  width: 200px;
  padding: 0 1px;
  font-size: 12px;
  color: #222;
  border: 1px solid #c7c7c7;
  border-radius: 4px;
}

so-select.empty:before {
  font-family: 'Helvetica';
  font-size: 12px;
  content: attr(placeholder);
  position: absolute;
  pointer-events: none;
  left: 6px;
  top: 3px;
  z-index: 0;
  color: #888;
}</code>```

  <so-select value-property="id" display-property="name" source="vm.names" ng-model="vm.nameId" placeholder="(select name)"></so-select>

```

Body:
I'm using placeholders for text inputs which is working out just fine. But I'd like to use a placeholder for my selectboxes as well. Of course I can just use this code:

<select>
    <option value="">Select your option</option>
    <option value="hurr">Durr</option>
</select>

But the 'Select your option' is in black instead of lightgrey. So my solution could possibly be CSS-based. jQuery is fine too.

This only makes the option grey in the dropdown (so after clicking the arrow):

option:first {
    color: #999;
}

The question is: How do people create placeholders in selectboxes? But it has already been answered, cheers.

And using this results in the selected value always being grey (even after selecting a real option):

select {
    color: #999;
}

Body:
Here is a CSS solution that works beautifully. The content is added (and absolutely positioned relative to the container) after the containing element (via :after pseudo-class).

It gets its text from the placeholder attribute that I defined where I used the directive (attr(placeholder)). Another key factor is pointer-events: none - this allows clicks on the placeholder text to pass through to the select. Otherwise it won't drop down if the user clicks the text.

I add the .empty class myself in my select directive, but normally I find that angular adds/removes .ng-empty for me (I assume it's because I'm injecting version 1.2 of Angular in my code sample).

(The sample also demonstrates how to wrap HTML elements in AngularJS to create your own custom inputs)

var app = angular.module("soDemo", []);
app.controller("soDemoController", function($scope) {
  var vm = {};
  vm.names = [{
      id: 1,
      name: 'Jon'
    },
    {
      id: 2,
      name: 'Joe'
    }, {
      id: 3,
      name: 'Bob'
    }, {
      id: 4,
      name: 'Jane'
    }
  ];
  vm.nameId;
  $scope.vm = vm;
});

app.directive('soSelect', function soSelect() {
  var directive = {
    restrict: 'E',
    require: 'ngModel',
    scope: {
      'valueProperty': '@',
      'displayProperty': '@',
      'modelProperty': '=',
      'source': '=',
    },
    link: link,
    template: getTemplate
  };
  return directive;

  /////////////////////////////////
  function link(scope, element, attrs, ngModelController) {
    init();
    return;

    ///////////// IMPLEMENTATION

    function init() {
      initDataBinding();
    }

    function initDataBinding() {
      ngModelController.$render = function() {
        if (scope.model === ngModelController.$viewValue) return;
        scope.model = ngModelController.$viewValue;
      }

      scope.$watch('model', function(newValue) {
        if (newValue === undefined) {
          element.addClass('empty');
          return;
        }
        element.removeClass('empty');
        ngModelController.$setViewValue(newValue);
      });
    }
  }

  function getTemplate(element, attrs) {
    var attributes = [
      'ng-model="model"',
      'ng-required="true"'
    ];

    if (angular.isDefined(attrs.placeholder)) {
      attributes.push('placeholder="{{placeholder}}"');
    }

    var ngOptions = '';

    if (angular.isDefined(attrs.valueProperty)) {
      ngOptions += 'item.' + attrs.valueProperty + ' as ';
    }

    ngOptions += 'item.' + attrs.displayProperty + ' for item in source';
    ngOptions += '"';
    attributes.push('ng-options="' + ngOptions + '"');

    var html = '<select ' + attributes.join(' ') + '></select>';

    return html;
  }
});

so-select {
  position: relative;
}

so-select select {
  font-family: 'Helvetica';
  display: inline-block;
  height: 24px;
  width: 200px;
  padding: 0 1px;
  font-size: 12px;
  color: #222;
  border: 1px solid #c7c7c7;
  border-radius: 4px;
}

so-select.empty:before {
  font-family: 'Helvetica';
  font-size: 12px;
  content: attr(placeholder);
  position: absolute;
  pointer-events: none;
  left: 6px;
  top: 3px;
  z-index: 0;
  color: #888;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="soDemo" ng-controller="soDemoController">
  <so-select value-property="id" display-property="name" source="vm.names" ng-model="vm.nameId" placeholder="(select name)"></so-select>
</div>


问:
Whats wrote with this break;
After adding break, my code no longer works.

```<code>alert("Warning: Game is made for the age of 18 and over.");
var a = prompt("Are you ready to enter this game?");
if (a == "yes") {alert("Entering");}
else if (a == "no") {while(true)
var a = prompt("Are you ready to enter this game?");
if(a == "yes") {break; alert("Entering");} }
</code>```

答:
I believe you intend to prompt the user repeatedly until he answers yes. In that case, use this code:

alert("Warning: Game is made for the age of 18 and over.");

let response = "";
while(response !== "yes") {
    response = prompt("Are you ready to enter this game?");
}

alert("Entering");```

Title: Whats wrote with this break;

Body:
After adding break, my code no longer works.

alert("Warning: Game is made for the age of 18 and over.");
var a = prompt("Are you ready to enter this game?");
if (a == "yes") {alert("Entering");}
else if (a == "no") {while(true)
var a = prompt("Are you ready to enter this game?");
if(a == "yes") {break; alert("Entering");} }


问:
Bootstrap align navbar items to the right
How do I align a navbar item to right?

I want to have the login and register to the right.
But everything I try does not seem to work.

 This is what I have tried so far:

 around the
 with the atribute: style="float: right"

 around the
 with the atribute: style="text-align: right"

tried those two things on the
 tags

tried all those things again with !important added to the end

changed nav-item to nav-right in the

added a pull-sm-right class to the

added a align-content-end class to the

This is my code:

```<code><div id="app" class="container">
  <nav class="navbar navbar-toggleable-md navbar-light bg-faded">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Navbar</a>
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricingg</a>
      </li>
    </ul>
    <ul class="navbar-nav " >
      <li  class="nav-item">
        <a class="nav-link" href="{{ url('/login') }}">Login</a>
      </li>
      <li  class="nav-item">
        <a class="nav-link" href="{{ url('/register') }}">Register</a>
      </li>
    </ul>
  </nav>
  @yield('content')
</div>
</code>```

答:
If you want Home, Features and Pricing on left immediately after your nav-brand, and then login and register on right then wrap the two lists in
 and use .justify-content-between:

```<code><div class="collapse navbar-collapse justify-content-between">
<ul>....</ul>
<ul>...</ul>
</div>
</code>```

Body:
How do I align a navbar item to right?

I want to have the login and register to the right.
But everything I try does not seem to work.

 This is what I have tried so far:

 around the
 with the atribute: style="float: right"

 around the
 with the atribute: style="text-align: right"

tried those two things on the
 tags

tried all those things again with !important added to the end

changed nav-item to nav-right in the

added a pull-sm-right class to the

added a align-content-end class to the

This is my code:

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

    </button>
    Navbar

        Home (current)

        Features

        Pricingg

        Login

        Register

  @yield('content')

Body:
If you want Home, Features and Pricing on left immediately after your nav-brand, and then login and register on right then wrap the two lists in <div> and use .justify-content-between:

<div class="collapse navbar-collapse justify-content-between">
<ul>....</ul>
<ul>...</ul>
</div>


问:
Stripe - change placholders of iframe inputs
I'm working on embedded form, I'm using stripe for online payments, and using their API to call this form.

I want to change placeholder of inputs because in Ireland they're straight different then in US.

We've got:

```<code><div class="line_1">
      <input name="line_1" id="line_1" type="text" placeholder="City" autocompletetype="address-line1" required="">
    </div>
</code>```

That's part of the iframe code.

I'm calling form on click action:

```<code>StripeCheckout.open({
            key:         '50m3s3cr3tk3y',
            amount:      0000,
            currency:    'eur',
            address: true,
            image: '/someimage.png',
            name:        'Product name',
            description: 'Marketing speech',
            panelLabel:  'Call to Action',
            token:       token
          });
jQuery("#line_1").attr("placeholder", "Town/City");
</code>```

This doesn't seem to work for me, looks like it doesn't even recognize field such as "line_1"

What's the best way to achieve it? As Stripe API doesn't provide it, on other hand there is an option to create own form.

Thanks,
Adam

答:
You wouldn't be able to modify the content of iframes of Stripe Element due to Same Origin Policy.

However, there is an undocumented placeholder option in Stripe API which can solve your problem. Take a look at this example:

```<code>var elements = stripe.elements();
var cardNumber = elements.create('cardNumber', {placeholder: '****-****-****'});
var cardExpiry = elements.create('cardExpiry');
var cardCvc = elements.create('cardCvc');

// you can also update the placeholder after the initialization
cardNumber.update({placeholder: 'bla bla bla'});

cardNumber.mount($form.find('#card_number')[0]);
cardExpiry.mount($form.find('#card_expiry')[0]);
cardCvc.mount($form.find('#card_cvc')[0]);

stripe.createToken(cardNumber).then(function(result){
    var token = result.error ? null : result.token;
    // do something with the stripe token
});
</code>```

Body:
I'm working on embedded form, I'm using stripe for online payments, and using their API to call this form.

I want to change placeholder of inputs because in Ireland they're straight different then in US.

We've got:

      <input name="line_1" id="line_1" type="text" placeholder="City" autocompletetype="address-line1" required="">

That's part of the iframe code.

I'm calling form on click action:

StripeCheckout.open({
            key:         '50m3s3cr3tk3y',
            amount:      0000,
            currency:    'eur',
            address: true,
            image: '/someimage.png',
            name:        'Product name',
            description: 'Marketing speech',
            panelLabel:  'Call to Action',
            token:       token
          });
jQuery("#line_1").attr("placeholder", "Town/City");

This doesn't seem to work for me, looks like it doesn't even recognize field such as "line_1"

What's the best way to achieve it? As Stripe API doesn't provide it, on other hand there is an option to create own form.

Thanks,
Adam

Body:
You wouldn't be able to modify the content of iframes of Stripe Element due to Same Origin Policy.

However, there is an undocumented placeholder option in Stripe API which can solve your problem. Take a look at this example:

var elements = stripe.elements();
var cardNumber = elements.create('cardNumber', {placeholder: '****-****-****'});
var cardExpiry = elements.create('cardExpiry');
var cardCvc = elements.create('cardCvc');

// you can also update the placeholder after the initialization
cardNumber.update({placeholder: 'bla bla bla'});

cardNumber.mount($form.find('#card_number')[0]);
cardExpiry.mount($form.find('#card_expiry')[0]);
cardCvc.mount($form.find('#card_cvc')[0]);

stripe.createToken(cardNumber).then(function(result){
    var token = result.error ? null : result.token;
    // do something with the stripe token
});


问:
Is it possible that I request an EC2 instance but can't get fulfilled?
Edit: This question is NOT to ask about "Spot Instances"; this question is to ask regular "On Demand Instance". I think I need to clarify this, after reading comments below.

Basically, my question is about whether I should consider the risk that when I need to launch an EC2 instance, but that EC2 region has run out of capacity and can't fulfill my request.

I understand the chance for the above situation is extremely low, but I'd like to understand if AWS has any SLA to make sure that situation/risk won't happen.

答:
The answer is yes, your launch request can fail because there is no available capacity in the relevant Availability Zone. I would say that it's a rare occurrence, but certainly possible.

You can mitigate by using multiple zones in the same region, other regions, or by using Reserved Instances.


问:
Rewrite rule that works for different domains and subdomains
I am wondering if it is possible to set up a rewrite rule where you do not specify the domain, only the page accessed and the page to redirect to. My goal for this is to not have to have different versions of the same rule for different sites (i.e. dev.mysite.com, qa.mysite.com, etc), so one rule works for multiple subdomains. For example, I need to redirect someone going to dev.mysite.com/mexico to mx.dev.mysite.com/es/mexico, but that also has to work for QA. Additionally, production has a slightly different domain which would make this even more difficult. This is what I came up with - it definitely needs work:

```<code><rule name="Test Mexico Redirect">
  <match url="^mexico"/>
  <action type="Redirect" url="http://mx.{R:2}/es/mexico" redirectType="Permanent"/>
</rule>
</code>```

Unfortunately it just does not work; I get a blank page. Probably because {R:2} is looking for the domain in the rule and one isn't specified. I can't think of a way to do this, because not even the domain is the same across all environments.

It would be cool if you could use regex in the <action> element, then I would do something like this: ^(mx\.).*com/es/mexico.

答:
It's possible using {HTTP_HOST} and back references like {C:#}. The IIS Rewrite module is extremely useful for setting this up. Here is a screenshot with some notes that explains how it's done:

By using {HTTP_HOST} and conditions I was able to make a rewrite rule that can apply to all environments. The actual XML result:

```<code>  <rule name="Mexico Redirect" stopProcessing="true">
    <match url="mexico" />
    <conditions>
      <add input="{HTTP_HOST}" pattern="^((?!mx))" />
      <add input="{CACHE_URL}" pattern="^(.+)://" />
    </conditions>
    <action type="Redirect" url="{C:1}://mx.{HTTP_HOST}/es/search" redirectType="Temporary" />
  </rule>
</code>```

Also I may have been incorrect saying you won't need to recycle the app pool with a Temporary (307) redirect. I still needed to recycle it but only in production... no verdict on this yet.

Body:
I am wondering if it is possible to set up a rewrite rule where you do not specify the domain, only the page accessed and the page to redirect to. My goal for this is to not have to have different versions of the same rule for different sites (i.e. dev.mysite.com, qa.mysite.com, etc), so one rule works for multiple subdomains. For example, I need to redirect someone going to dev.mysite.com/mexico to mx.dev.mysite.com/es/mexico, but that also has to work for QA. Additionally, production has a slightly different domain which would make this even more difficult. This is what I came up with - it definitely needs work:

<rule name="Test Mexico Redirect">
  <match url="^mexico"/>
  <action type="Redirect" url="http://mx.{R:2}/es/mexico" redirectType="Permanent"/>
</rule>

Unfortunately it just does not work; I get a blank page. Probably because {R:2} is looking for the domain in the rule and one isn't specified. I can't think of a way to do this, because not even the domain is the same across all environments.

It would be cool if you could use regex in the <action> element, then I would do something like this: ^(mx\.).*com/es/mexico.

Body:
It's possible using {HTTP_HOST} and back references like {C:#}. The IIS Rewrite module is extremely useful for setting this up. Here is a screenshot with some notes that explains how it's done:

By using {HTTP_HOST} and conditions I was able to make a rewrite rule that can apply to all environments. The actual XML result:

  <rule name="Mexico Redirect" stopProcessing="true">
    <match url="mexico" />
    <conditions>
      <add input="{HTTP_HOST}" pattern="^((?!mx))" />
      <add input="{CACHE_URL}" pattern="^(.+)://" />
    </conditions>
    <action type="Redirect" url="{C:1}://mx.{HTTP_HOST}/es/search" redirectType="Temporary" />
  </rule>

Also I may have been incorrect saying you won't need to recycle the app pool with a Temporary (307) redirect. I still needed to recycle it but only in production... no verdict on this yet.


问:
how to let the parent view know that the subview has been removed - iphone
My app has a tab view controller as the main access point.
However, when it runs for the first time, I need to check for some basic data, and if that is missing, I need to show a view to capture this information first . The table in the tab view uses this information to display the data.

The way I am doing it is like this:
In my app-delegate, I show the tab view.
Then check for information x. If not present, add subview view2 and show it on top.
In view2, I capture the information, and on click of a button remove it from superview. The required data is stored in global variables in the model.
Now, the control goes back to the tab view which showed it.
The problem is that I need to reload the table data in the tab view so that it reflects the correct information. However, I am not able to capture this in my parent tab view. So, the only way I can do a refresh is by manually clicking a button, which is not ideal. I want it to automatically refresh as soon as the subview is removed from the stack.

答:
Registering and calling notifications is the way to go.

For the view you want to send the notification:

```<code>- (void) viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateView:) name:@"updateView" object:nil];
}

- (void)updateView:(NSNotification *)notification {
    /*  this is where the updates will take place,
        such as a [tableView reloadData];
     */
}
</code>```

And to call that notification:

```<code>[[NSNotificationCenter defaultCenter] postNotificationName:@"updateView" object:nil];
</code>```

Body:
Registering and calling notifications is the way to go.

For the view you want to send the notification:

- (void) viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateView:) name:@"updateView" object:nil];
}

- (void)updateView:(NSNotification *)notification {
    /*  this is where the updates will take place,
        such as a [tableView reloadData];
     */
}

And to call that notification:

[[NSNotificationCenter defaultCenter] postNotificationName:@"updateView" object:nil];


问:
Adding TypeScript definitions for wrapped classes
I'm using a package called react-server that can take any class and will add methods to it at runtime.  It expects to have the class that it wraps to have an interface like

```<code>interface {
    getElements(): Array<React.Component>
}
</code>```

and it will add methods to the class like getRequest(), which can be referenced from inside the class as well.

Imagine a page class like:

```<code>class SimplePage {
  getElements() {
    // Right now, this wouldn't compile, because this.getRequest() is
    // not an available method.
    const request: Request = this.getRequest();
    // ...
  }
}
</code>```

Given that this.getRequest() doesn't actually exist at compile time, and that react-server doesn't actually provide any real classes or interfaces that I can reference from my definition file, is there any way that I can create a definition that I can use that calls out that something is, in fact, a Page type and has these methods available to it?

Ideally, I'd love to be able to provide these in a definition file (.d.ts) somewhere so that I can reference them in any app that uses react-server.  I'd also love to do this without being forced to cast this to something else every time I wanted to reference the method.

答:
You have 2 options that I can think of.

Given the following interface:

```<code>interface ExtendedPage {
    getRequest(): Request;
}
</code>```

(1) The this parameter:

```<code>class SimplePage {
    getElements(this: SimplePage & ExtendedPage) {
        const request: Request = this.getRequest();
        // ...
    }
}
</code>```

(2) Implement the interface with stand-in properties (like with mixins):

```<code>class SimplePage implements ExtendedPage {
    getElements() {
        const request: Request = this.getRequest();
        // ...
    }

    getRequest: () => Request;
}
</code>```

Edit

You can declare a class and extend it:

```<code>declare class ExtendedPage {
    getRequest(): Request;
}

class SimplePage extends ExtendedPage {
    ...
}
</code>```

Body:
I'm using a package called react-server that can take any class and will add methods to it at runtime.  It expects to have the class that it wraps to have an interface like

interface {
    getElements(): Array<React.Component>
}

and it will add methods to the class like getRequest(), which can be referenced from inside the class as well.

Imagine a page class like:

class SimplePage {
  getElements() {
    // Right now, this wouldn't compile, because this.getRequest() is
    // not an available method.
    const request: Request = this.getRequest();
    // ...
  }
}

Given that this.getRequest() doesn't actually exist at compile time, and that react-server doesn't actually provide any real classes or interfaces that I can reference from my definition file, is there any way that I can create a definition that I can use that calls out that something is, in fact, a Page type and has these methods available to it?

Ideally, I'd love to be able to provide these in a definition file (.d.ts) somewhere so that I can reference them in any app that uses react-server.  I'd also love to do this without being forced to cast this to something else every time I wanted to reference the method.

Body:
You have 2 options that I can think of.

Given the following interface:

interface ExtendedPage {
    getRequest(): Request;
}

(1) The this parameter:

class SimplePage {
    getElements(this: SimplePage & ExtendedPage) {
        const request: Request = this.getRequest();
        // ...
    }
}

(2) Implement the interface with stand-in properties (like with mixins):

class SimplePage implements ExtendedPage {
    getElements() {
        const request: Request = this.getRequest();
        // ...
    }

    getRequest: () => Request;
}

Edit

You can declare a class and extend it:

declare class ExtendedPage {
    getRequest(): Request;
}

class SimplePage extends ExtendedPage {
    ...
}