问:
Bootstrap 3 Glyphicons CDN

PAY ATTENTION!

The Bootstrap icons are back after this pull request merge.

After going back and forth on this for the last couple weeks, I've decided to restore the Glyphicons icon font to the main repo. Given how prevalent icons are in UIs, it's probably a disservice to most folks to not include them (or some other icon font) in the same spot as the CSS and JS.

With this update comes the following:

Restores documentation (on the Components page)

New variables, @icon-font-path and @icon-font-name, for flexibility in adding and removing icon fonts

Upgrades to latest Glyphicons (adding 40 new icons)

Removes the old Glyphicons mention from the CSS page

We'll work on improving the customization of icon fonts in the future so swapping font libraries can be easier (which was the whole motivation for the original removal).

Which is the CDN url of the new version of Twitter Bootstrap Glyphicons?

From the Bootstrap 3 they were moved into a separate repository, but I didn't find any CDN.

From the official documentation:

With the launch of Bootstrap 3, icons have been moved to a separate repository. This keeps the primary project as lean as possible, makes it easier for folks to swap icon libraries, and makes Glyphicons icon fonts more readily available to more people outside Bootstrap.

On the official website they don't provide a CDN url for icons.

Where can find it? I don't want to download the repository and include it into my project.

答:
If you only want to have glyphicons icons without any additional css you can create a css file and put the code below and include it into main css file.

I have to create this extra file as link below was messing with my site styles too.

```<code>//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css
</code>```

Instead to using it directly I created a css file bootstrap-glyphicons.css

@font-face{font-family:'Glyphicons Halflings';src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot');src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff') format('woff'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;}
.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
.glyphicon-minus:before{content:"\2212";}
.glyphicon-cloud:before{content:"\2601";}
.glyphicon-envelope:before{content:"\2709";}
.glyphicon-pencil:before{content:"\270f";}
.glyphicon-glass:before{content:"\e001";}
.glyphicon-music:before{content:"\e002";}
.glyphicon-search:before{content:"\e003";}
.glyphicon-heart:before{content:"\e005";}
.glyphicon-star:before{content:"\e006";}
.glyphicon-star-empty:before{content:"\e007";}
.glyphicon-user:before{content:"\e008";}
.glyphicon-film:before{content:"\e009";}
.glyphicon-th-large:before{content:"\e010";}
.glyphicon-th:before{content:"\e011";}
.glyphicon-th-list:before{content:"\e012";}
.glyphicon-ok:before{content:"\e013";}
.glyphicon-remove:before{content:"\e014";}
.glyphicon-zoom-in:before{content:"\e015";}
.glyphicon-zoom-out:before{content:"\e016";}
.glyphicon-off:before{content:"\e017";}
.glyphicon-signal:before{content:"\e018";}
.glyphicon-cog:before{content:"\e019";}
.glyphicon-trash:before{content:"\e020";}
.glyphicon-home:before{content:"\e021";}
.glyphicon-file:before{content:"\e022";}
.glyphicon-time:before{content:"\e023";}
.glyphicon-road:before{content:"\e024";}
.glyphicon-download-alt:before{content:"\e025";}
.glyphicon-download:before{content:"\e026";}
.glyphicon-upload:before{content:"\e027";}
.glyphicon-inbox:before{content:"\e028";}
.glyphicon-play-circle:before{content:"\e029";}
.glyphicon-repeat:before{content:"\e030";}
.glyphicon-refresh:before{content:"\e031";}
.glyphicon-list-alt:before{content:"\e032";}
.glyphicon-flag:before{content:"\e034";}
.glyphicon-headphones:before{content:"\e035";}
.glyphicon-volume-off:before{content:"\e036";}
.glyphicon-volume-down:before{content:"\e037";}
.glyphicon-volume-up:before{content:"\e038";}
.glyphicon-qrcode:before{content:"\e039";}
.glyphicon-barcode:before{content:"\e040";}
.glyphicon-tag:before{content:"\e041";}
.glyphicon-tags:before{content:"\e042";}
.glyphicon-book:before{content:"\e043";}
.glyphicon-print:before{content:"\e045";}
.glyphicon-font:before{content:"\e047";}
.glyphicon-bold:before{content:"\e048";}
.glyphicon-italic:before{content:"\e049";}
.glyphicon-text-height:before{content:"\e050";}
.glyphicon-text-width:before{content:"\e051";}
.glyphicon-align-left:before{content:"\e052";}
.glyphicon-align-center:before{content:"\e053";}
.glyphicon-align-right:before{content:"\e054";}
.glyphicon-align-justify:before{content:"\e055";}
.glyphicon-list:before{content:"\e056";}
.glyphicon-indent-left:before{content:"\e057";}
.glyphicon-indent-right:before{content:"\e058";}
.glyphicon-facetime-video:before{content:"\e059";}
.glyphicon-picture:before{content:"\e060";}
.glyphicon-map-marker:before{content:"\e062";}
.glyphicon-adjust:before{content:"\e063";}
.glyphicon-tint:before{content:"\e064";}
.glyphicon-edit:before{content:"\e065";}
.glyphicon-share:before{content:"\e066";}
.glyphicon-check:before{content:"\e067";}
.glyphicon-move:before{content:"\e068";}
.glyphicon-step-backward:before{content:"\e069";}
.glyphicon-fast-backward:before{content:"\e070";}
.glyphicon-backward:before{content:"\e071";}
.glyphicon-play:before{content:"\e072";}
.glyphicon-pause:before{content:"\e073";}
.glyphicon-stop:before{content:"\e074";}
.glyphicon-forward:before{content:"\e075";}
.glyphicon-fast-forward:before{content:"\e076";}
.glyphicon-step-forward:before{content:"\e077";}
.glyphicon-eject:before{content:"\e078";}
.glyphicon-chevron-left:before{content:"\e079";}
.glyphicon-chevron-right:before{content:"\e080";}
.glyphicon-plus-sign:before{content:"\e081";}
.glyphicon-minus-sign:before{content:"\e082";}
.glyphicon-remove-sign:before{content:"\e083";}
.glyphicon-ok-sign:before{content:"\e084";}
.glyphicon-question-sign:before{content:"\e085";}
.glyphicon-info-sign:before{content:"\e086";}
.glyphicon-screenshot:before{content:"\e087";}
.glyphicon-remove-circle:before{content:"\e088";}
.glyphicon-ok-circle:before{content:"\e089";}
.glyphicon-ban-circle:before{content:"\e090";}
.glyphicon-arrow-left:before{content:"\e091";}
.glyphicon-arrow-right:before{content:"\e092";}
.glyphicon-arrow-up:before{content:"\e093";}
.glyphicon-arrow-down:before{content:"\e094";}
.glyphicon-share-alt:before{content:"\e095";}
.glyphicon-resize-full:before{content:"\e096";}
.glyphicon-resize-small:before{content:"\e097";}
.glyphicon-exclamation-sign:before{content:"\e101";}
.glyphicon-gift:before{content:"\e102";}
.glyphicon-leaf:before{content:"\e103";}
.glyphicon-eye-open:before{content:"\e105";}
.glyphicon-eye-close:before{content:"\e106";}
.glyphicon-warning-sign:before{content:"\e107";}
.glyphicon-plane:before{content:"\e108";}
.glyphicon-random:before{content:"\e110";}
.glyphicon-comment:before{content:"\e111";}
.glyphicon-magnet:before{content:"\e112";}
.glyphicon-chevron-up:before{content:"\e113";}
.glyphicon-chevron-down:before{content:"\e114";}
.glyphicon-retweet:before{content:"\e115";}
.glyphicon-shopping-cart:before{content:"\e116";}
.glyphicon-folder-close:before{content:"\e117";}
.glyphicon-folder-open:before{content:"\e118";}
.glyphicon-resize-vertical:before{content:"\e119";}
.glyphicon-resize-horizontal:before{content:"\e120";}
.glyphicon-hdd:before{content:"\e121";}
.glyphicon-bullhorn:before{content:"\e122";}
.glyphicon-certificate:before{content:"\e124";}
.glyphicon-thumbs-up:before{content:"\e125";}
.glyphicon-thumbs-down:before{content:"\e126";}
.glyphicon-hand-right:before{content:"\e127";}
.glyphicon-hand-left:before{content:"\e128";}
.glyphicon-hand-up:before{content:"\e129";}
.glyphicon-hand-down:before{content:"\e130";}
.glyphicon-circle-arrow-right:before{content:"\e131";}
.glyphicon-circle-arrow-left:before{content:"\e132";}
.glyphicon-circle-arrow-up:before{content:"\e133";}
.glyphicon-circle-arrow-down:before{content:"\e134";}
.glyphicon-globe:before{content:"\e135";}
.glyphicon-tasks:before{content:"\e137";}
.glyphicon-filter:before{content:"\e138";}
.glyphicon-fullscreen:before{content:"\e140";}
.glyphicon-dashboard:before{content:"\e141";}
.glyphicon-heart-empty:before{content:"\e143";}
.glyphicon-link:before{content:"\e144";}
.glyphicon-phone:before{content:"\e145";}
.glyphicon-usd:before{content:"\e148";}
.glyphicon-gbp:before{content:"\e149";}
.glyphicon-sort:before{content:"\e150";}
.glyphicon-sort-by-alphabet:before{content:"\e151";}
.glyphicon-sort-by-alphabet-alt:before{content:"\e152";}
.glyphicon-sort-by-order:before{content:"\e153";}
.glyphicon-sort-by-order-alt:before{content:"\e154";}
.glyphicon-sort-by-attributes:before{content:"\e155";}
.glyphicon-sort-by-attributes-alt:before{content:"\e156";}
.glyphicon-unchecked:before{content:"\e157";}
.glyphicon-expand:before{content:"\e158";}
.glyphicon-collapse-down:before{content:"\e159";}
.glyphicon-collapse-up:before{content:"\e160";}
.glyphicon-log-in:before{content:"\e161";}
.glyphicon-flash:before{content:"\e162";}
.glyphicon-log-out:before{content:"\e163";}
.glyphicon-new-window:before{content:"\e164";}
.glyphicon-record:before{content:"\e165";}
.glyphicon-save:before{content:"\e166";}
.glyphicon-open:before{content:"\e167";}
.glyphicon-saved:before{content:"\e168";}
.glyphicon-import:before{content:"\e169";}
.glyphicon-export:before{content:"\e170";}
.glyphicon-send:before{content:"\e171";}
.glyphicon-floppy-disk:before{content:"\e172";}
.glyphicon-floppy-saved:before{content:"\e173";}
.glyphicon-floppy-remove:before{content:"\e174";}
.glyphicon-floppy-save:before{content:"\e175";}
.glyphicon-floppy-open:before{content:"\e176";}
.glyphicon-credit-card:before{content:"\e177";}
.glyphicon-transfer:before{content:"\e178";}
.glyphicon-cutlery:before{content:"\e179";}
.glyphicon-header:before{content:"\e180";}
.glyphicon-compressed:before{content:"\e181";}
.glyphicon-earphone:before{content:"\e182";}
.glyphicon-phone-alt:before{content:"\e183";}
.glyphicon-tower:before{content:"\e184";}
.glyphicon-stats:before{content:"\e185";}
.glyphicon-sd-video:before{content:"\e186";}
.glyphicon-hd-video:before{content:"\e187";}
.glyphicon-subtitles:before{content:"\e188";}
.glyphicon-sound-stereo:before{content:"\e189";}
.glyphicon-sound-dolby:before{content:"\e190";}
.glyphicon-sound-5-1:before{content:"\e191";}
.glyphicon-sound-6-1:before{content:"\e192";}
.glyphicon-sound-7-1:before{content:"\e193";}
.glyphicon-copyright-mark:before{content:"\e194";}
.glyphicon-registration-mark:before{content:"\e195";}
.glyphicon-cloud-download:before{content:"\e197";}
.glyphicon-cloud-upload:before{content:"\e198";}
.glyphicon-tree-conifer:before{content:"\e199";}
.glyphicon-tree-deciduous:before{content:"\e200";}
.glyphicon-briefcase:before{content:"\1f4bc";}
.glyphicon-calendar:before{content:"\1f4c5";}
.glyphicon-pushpin:before{content:"\1f4cc";}
.glyphicon-paperclip:before{content:"\1f4ce";}
.glyphicon-camera:before{content:"\1f4f7";}
.glyphicon-lock:before{content:"\1f512";}
.glyphicon-bell:before{content:"\1f514";}
.glyphicon-bookmark:before{content:"\1f516";}
.glyphicon-fire:before{content:"\1f525";}
.glyphicon-wrench:before{content:"\1f527";}```
</div>
</div>
</p>

<p>And imported the created css file into my main css file which enable me to just import the glyphicons only. Hope this help </p>

```@import url("bootstrap-glyphicons.css");
```

Title: Bootstrap 3 Glyphicons CDN

Body:
If you only want to have glyphicons icons without any additional css you can create a css file and put the code below and include it into main css file.

I have to create this extra file as link below was messing with my site styles too.

//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css

Instead to using it directly I created a css file bootstrap-glyphicons.css

@font-face{font-family:'Glyphicons Halflings';src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot');src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff') format('woff'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;}
.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
.glyphicon-minus:before{content:"\2212";}
.glyphicon-cloud:before{content:"\2601";}
.glyphicon-envelope:before{content:"\2709";}
.glyphicon-pencil:before{content:"\270f";}
.glyphicon-glass:before{content:"\e001";}
.glyphicon-music:before{content:"\e002";}
.glyphicon-search:before{content:"\e003";}
.glyphicon-heart:before{content:"\e005";}
.glyphicon-star:before{content:"\e006";}
.glyphicon-star-empty:before{content:"\e007";}
.glyphicon-user:before{content:"\e008";}
.glyphicon-film:before{content:"\e009";}
.glyphicon-th-large:before{content:"\e010";}
.glyphicon-th:before{content:"\e011";}
.glyphicon-th-list:before{content:"\e012";}
.glyphicon-ok:before{content:"\e013";}
.glyphicon-remove:before{content:"\e014";}
.glyphicon-zoom-in:before{content:"\e015";}
.glyphicon-zoom-out:before{content:"\e016";}
.glyphicon-off:before{content:"\e017";}
.glyphicon-signal:before{content:"\e018";}
.glyphicon-cog:before{content:"\e019";}
.glyphicon-trash:before{content:"\e020";}
.glyphicon-home:before{content:"\e021";}
.glyphicon-file:before{content:"\e022";}
.glyphicon-time:before{content:"\e023";}
.glyphicon-road:before{content:"\e024";}
.glyphicon-download-alt:before{content:"\e025";}
.glyphicon-download:before{content:"\e026";}
.glyphicon-upload:before{content:"\e027";}
.glyphicon-inbox:before{content:"\e028";}
.glyphicon-play-circle:before{content:"\e029";}
.glyphicon-repeat:before{content:"\e030";}
.glyphicon-refresh:before{content:"\e031";}
.glyphicon-list-alt:before{content:"\e032";}
.glyphicon-flag:before{content:"\e034";}
.glyphicon-headphones:before{content:"\e035";}
.glyphicon-volume-off:before{content:"\e036";}
.glyphicon-volume-down:before{content:"\e037";}
.glyphicon-volume-up:before{content:"\e038";}
.glyphicon-qrcode:before{content:"\e039";}
.glyphicon-barcode:before{content:"\e040";}
.glyphicon-tag:before{content:"\e041";}
.glyphicon-tags:before{content:"\e042";}
.glyphicon-book:before{content:"\e043";}
.glyphicon-print:before{content:"\e045";}
.glyphicon-font:before{content:"\e047";}
.glyphicon-bold:before{content:"\e048";}
.glyphicon-italic:before{content:"\e049";}
.glyphicon-text-height:before{content:"\e050";}
.glyphicon-text-width:before{content:"\e051";}
.glyphicon-align-left:before{content:"\e052";}
.glyphicon-align-center:before{content:"\e053";}
.glyphicon-align-right:before{content:"\e054";}
.glyphicon-align-justify:before{content:"\e055";}
.glyphicon-list:before{content:"\e056";}
.glyphicon-indent-left:before{content:"\e057";}
.glyphicon-indent-right:before{content:"\e058";}
.glyphicon-facetime-video:before{content:"\e059";}
.glyphicon-picture:before{content:"\e060";}
.glyphicon-map-marker:before{content:"\e062";}
.glyphicon-adjust:before{content:"\e063";}
.glyphicon-tint:before{content:"\e064";}
.glyphicon-edit:before{content:"\e065";}
.glyphicon-share:before{content:"\e066";}
.glyphicon-check:before{content:"\e067";}
.glyphicon-move:before{content:"\e068";}
.glyphicon-step-backward:before{content:"\e069";}
.glyphicon-fast-backward:before{content:"\e070";}
.glyphicon-backward:before{content:"\e071";}
.glyphicon-play:before{content:"\e072";}
.glyphicon-pause:before{content:"\e073";}
.glyphicon-stop:before{content:"\e074";}
.glyphicon-forward:before{content:"\e075";}
.glyphicon-fast-forward:before{content:"\e076";}
.glyphicon-step-forward:before{content:"\e077";}
.glyphicon-eject:before{content:"\e078";}
.glyphicon-chevron-left:before{content:"\e079";}
.glyphicon-chevron-right:before{content:"\e080";}
.glyphicon-plus-sign:before{content:"\e081";}
.glyphicon-minus-sign:before{content:"\e082";}
.glyphicon-remove-sign:before{content:"\e083";}
.glyphicon-ok-sign:before{content:"\e084";}
.glyphicon-question-sign:before{content:"\e085";}
.glyphicon-info-sign:before{content:"\e086";}
.glyphicon-screenshot:before{content:"\e087";}
.glyphicon-remove-circle:before{content:"\e088";}
.glyphicon-ok-circle:before{content:"\e089";}
.glyphicon-ban-circle:before{content:"\e090";}
.glyphicon-arrow-left:before{content:"\e091";}
.glyphicon-arrow-right:before{content:"\e092";}
.glyphicon-arrow-up:before{content:"\e093";}
.glyphicon-arrow-down:before{content:"\e094";}
.glyphicon-share-alt:before{content:"\e095";}
.glyphicon-resize-full:before{content:"\e096";}
.glyphicon-resize-small:before{content:"\e097";}
.glyphicon-exclamation-sign:before{content:"\e101";}
.glyphicon-gift:before{content:"\e102";}
.glyphicon-leaf:before{content:"\e103";}
.glyphicon-eye-open:before{content:"\e105";}
.glyphicon-eye-close:before{content:"\e106";}
.glyphicon-warning-sign:before{content:"\e107";}
.glyphicon-plane:before{content:"\e108";}
.glyphicon-random:before{content:"\e110";}
.glyphicon-comment:before{content:"\e111";}
.glyphicon-magnet:before{content:"\e112";}
.glyphicon-chevron-up:before{content:"\e113";}
.glyphicon-chevron-down:before{content:"\e114";}
.glyphicon-retweet:before{content:"\e115";}
.glyphicon-shopping-cart:before{content:"\e116";}
.glyphicon-folder-close:before{content:"\e117";}
.glyphicon-folder-open:before{content:"\e118";}
.glyphicon-resize-vertical:before{content:"\e119";}
.glyphicon-resize-horizontal:before{content:"\e120";}
.glyphicon-hdd:before{content:"\e121";}
.glyphicon-bullhorn:before{content:"\e122";}
.glyphicon-certificate:before{content:"\e124";}
.glyphicon-thumbs-up:before{content:"\e125";}
.glyphicon-thumbs-down:before{content:"\e126";}
.glyphicon-hand-right:before{content:"\e127";}
.glyphicon-hand-left:before{content:"\e128";}
.glyphicon-hand-up:before{content:"\e129";}
.glyphicon-hand-down:before{content:"\e130";}
.glyphicon-circle-arrow-right:before{content:"\e131";}
.glyphicon-circle-arrow-left:before{content:"\e132";}
.glyphicon-circle-arrow-up:before{content:"\e133";}
.glyphicon-circle-arrow-down:before{content:"\e134";}
.glyphicon-globe:before{content:"\e135";}
.glyphicon-tasks:before{content:"\e137";}
.glyphicon-filter:before{content:"\e138";}
.glyphicon-fullscreen:before{content:"\e140";}
.glyphicon-dashboard:before{content:"\e141";}
.glyphicon-heart-empty:before{content:"\e143";}
.glyphicon-link:before{content:"\e144";}
.glyphicon-phone:before{content:"\e145";}
.glyphicon-usd:before{content:"\e148";}
.glyphicon-gbp:before{content:"\e149";}
.glyphicon-sort:before{content:"\e150";}
.glyphicon-sort-by-alphabet:before{content:"\e151";}
.glyphicon-sort-by-alphabet-alt:before{content:"\e152";}
.glyphicon-sort-by-order:before{content:"\e153";}
.glyphicon-sort-by-order-alt:before{content:"\e154";}
.glyphicon-sort-by-attributes:before{content:"\e155";}
.glyphicon-sort-by-attributes-alt:before{content:"\e156";}
.glyphicon-unchecked:before{content:"\e157";}
.glyphicon-expand:before{content:"\e158";}
.glyphicon-collapse-down:before{content:"\e159";}
.glyphicon-collapse-up:before{content:"\e160";}
.glyphicon-log-in:before{content:"\e161";}
.glyphicon-flash:before{content:"\e162";}
.glyphicon-log-out:before{content:"\e163";}
.glyphicon-new-window:before{content:"\e164";}
.glyphicon-record:before{content:"\e165";}
.glyphicon-save:before{content:"\e166";}
.glyphicon-open:before{content:"\e167";}
.glyphicon-saved:before{content:"\e168";}
.glyphicon-import:before{content:"\e169";}
.glyphicon-export:before{content:"\e170";}
.glyphicon-send:before{content:"\e171";}
.glyphicon-floppy-disk:before{content:"\e172";}
.glyphicon-floppy-saved:before{content:"\e173";}
.glyphicon-floppy-remove:before{content:"\e174";}
.glyphicon-floppy-save:before{content:"\e175";}
.glyphicon-floppy-open:before{content:"\e176";}
.glyphicon-credit-card:before{content:"\e177";}
.glyphicon-transfer:before{content:"\e178";}
.glyphicon-cutlery:before{content:"\e179";}
.glyphicon-header:before{content:"\e180";}
.glyphicon-compressed:before{content:"\e181";}
.glyphicon-earphone:before{content:"\e182";}
.glyphicon-phone-alt:before{content:"\e183";}
.glyphicon-tower:before{content:"\e184";}
.glyphicon-stats:before{content:"\e185";}
.glyphicon-sd-video:before{content:"\e186";}
.glyphicon-hd-video:before{content:"\e187";}
.glyphicon-subtitles:before{content:"\e188";}
.glyphicon-sound-stereo:before{content:"\e189";}
.glyphicon-sound-dolby:before{content:"\e190";}
.glyphicon-sound-5-1:before{content:"\e191";}
.glyphicon-sound-6-1:before{content:"\e192";}
.glyphicon-sound-7-1:before{content:"\e193";}
.glyphicon-copyright-mark:before{content:"\e194";}
.glyphicon-registration-mark:before{content:"\e195";}
.glyphicon-cloud-download:before{content:"\e197";}
.glyphicon-cloud-upload:before{content:"\e198";}
.glyphicon-tree-conifer:before{content:"\e199";}
.glyphicon-tree-deciduous:before{content:"\e200";}
.glyphicon-briefcase:before{content:"\1f4bc";}
.glyphicon-calendar:before{content:"\1f4c5";}
.glyphicon-pushpin:before{content:"\1f4cc";}
.glyphicon-paperclip:before{content:"\1f4ce";}
.glyphicon-camera:before{content:"\1f4f7";}
.glyphicon-lock:before{content:"\1f512";}
.glyphicon-bell:before{content:"\1f514";}
.glyphicon-bookmark:before{content:"\1f516";}
.glyphicon-fire:before{content:"\1f525";}
.glyphicon-wrench:before{content:"\1f527";}

And imported the created css file into my main css file which enable me to just import the glyphicons only. Hope this help

@import url("bootstrap-glyphicons.css");


来源: stackexchange

问:
Detached DOM node memory leak in React
EDIT
It appears that this is due to an issue in React and is being fixed in a future release.
https://github.com/facebook/react/issues/18066

Given a table in react that displays data from an API which can be refreshed with completely new information, I observed a detached DOM node leak (observe the green numbers):

Here is the code executed in the gif (code included below for posterity).
To see the leak, go to the full page, open chrome dev tools, view the "Performance Monitor" tab and click the "Regen" button quickly as seen in the gif.

In this codesandbox, where the nodes are not generated in a loop, the leak does not occur.

The only difference is the {rows} array within the jsx.  The confounding part is that {rows} is not a global variable, so I don't see how it would prevent the old nodes from being GC'd.

Why does using the local variable rows result in a detached DOM node leak?

Note: The DOM Nodes seem to settle at 21,000 but there shouldn't be that many nodes anyway, as you can see it starts at 7,000 after the first table generation.  In my real-world app, these detached nodes persist even through navigation (with react router) which leads me to believe that it is an actual leak and not just nodes waiting to be GC'd.

Full code simulating the leak:

```<code>import React, { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div className="App">
      <button onClick={() => setCount(prev => prev + 1)}>Regen</button>
      <FTable count={count} />
    </div>
  );
}

function Cell() {
  const num = Math.floor(Math.random() * 100);
  return <td>{num}</td>;
}
function FTable(props) {
  const { count } = props;
  const rows = [];
  if (count > 0) {
    for (let i = 0; i < 1000; i++) {
      rows.push(
        // Use a different key for each time the
        // table is regenerated to simulate a new API
        // call bringing in new data
        <tr key={`${i} ${count}`}>
          <Cell row={i} />
          <Cell row={i} />
          <Cell row={i} />
        </tr>
      );
    }
  }
  return (
    <div>
      <table>
        <tbody>{rows}</tbody>
      </table>
    </div>
  );
}

</code>```

答:
At first, I thought this is a bug with Hooks API. Because if you replace the <FTable count={count} /> with <FTable count={1} /> then bug will gone. But this is not a solution.

There is an issue about unexpected behavior with Hooks. But in this case, instead of DOM Nodes, the JS Heap size is growing.

Then I thought "okay, I'll try this case with class component" and I did this demo. The same problem is still here. Okay, what if this problem was introduced along with Hooks in version 16.3? But, no. The same issue exist in 16.0.

And then I realize. The key question is what is common between all of these cases? The key!

Documentation says:

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.

Turned out, that React doesn't "Garbage Collect" old nodes if the key is unique on each render (well, in this case). That's why if you're using
 then everything is okay because React "rewrite" those nodes, and when you're using ${i * count} or ${i} ${count} or "whatever unique on every render", then nodes will be in memory. After some point, old nodes will be replaced with new ones, but I guess this is browser related behavior, not React. But I'm not a react expert and I don't know, where and how exactly this happens.

At this point, you can create an issue on GitHub and be aware of this problem.

ContentLicense: CC BY-SA 4.0

Title: Detached DOM node memory leak in React

Body:
EDIT
It appears that this is due to an issue in React and is being fixed in a future release.
https://github.com/facebook/react/issues/18066

Given a table in react that displays data from an API which can be refreshed with completely new information, I observed a detached DOM node leak (observe the green numbers):

Here is the code executed in the gif (code included below for posterity).
To see the leak, go to the full page, open chrome dev tools, view the "Performance Monitor" tab and click the "Regen" button quickly as seen in the gif.

In this codesandbox, where the nodes are not generated in a loop, the leak does not occur.

The only difference is the {rows} array within the jsx.  The confounding part is that {rows} is not a global variable, so I don't see how it would prevent the old nodes from being GC'd.

Why does using the local variable rows result in a detached DOM node leak?

Note: The DOM Nodes seem to settle at 21,000 but there shouldn't be that many nodes anyway, as you can see it starts at 7,000 after the first table generation.  In my real-world app, these detached nodes persist even through navigation (with react router) which leads me to believe that it is an actual leak and not just nodes waiting to be GC'd.

Full code simulating the leak:

import React, { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);
  return (

      <button onClick={() => setCount(prev => prev + 1)}>Regen</button>
      <FTable count={count} />

  );
}

function Cell() {
  const num = Math.floor(Math.random() * 100);
  return {num}	;
}
function FTable(props) {
  const { count } = props;
  const rows = [];
  if (count > 0) {
    for (let i = 0; i < 1000; i++) {
      rows.push(
        // Use a different key for each time the
        // table is regenerated to simulate a new API
        // call bringing in new data
        <tr key={`${i} ${count}`}>
          <Cell row={i} />
          <Cell row={i} />
          <Cell row={i} />

      );
    }
  }
  return (

{rows}

  );
}

Body:
At first, I thought this is a bug with Hooks API. Because if you replace the <FTable count={count} /> with <FTable count={1} /> then bug will gone. But this is not a solution.

There is an issue about unexpected behavior with Hooks. But in this case, instead of DOM Nodes, the JS Heap size is growing.

Then I thought "okay, I'll try this case with class component" and I did this demo. The same problem is still here. Okay, what if this problem was introduced along with Hooks in version 16.3? But, no. The same issue exist in 16.0.

And then I realize. The key question is what is common between all of these cases? The key!

Documentation says:

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.

Turned out, that React doesn't "Garbage Collect" old nodes if the key is unique on each render (well, in this case). That's why if you're using <tr key={i}> then everything is okay because React "rewrite" those nodes, and when you're using ${i * count} or ${i} ${count} or "whatever unique on every render", then nodes will be in memory. After some point, old nodes will be replaced with new ones, but I guess this is browser related behavior, not React. But I'm not a react expert and I don't know, where and how exactly this happens.

At this point, you can create an issue on GitHub and be aware of this problem.


问:
I have installed pytz via pip but "import pytz" throws a module not found exception
I installed pytz on Debian Buster via

```<code>sudo pip install pytz
</code>```

and the install completed cleanly.  However, when I attempt to

```<code>import pytz
</code>```

python throws an exception

```<code>    import pytz
ModuleNotFoundError: No module named 'pytz'
</code>```

I installed pytz 2019.3 via pip 18.1.   Any thoughts on why pytz is not found?

Update:  I ran pip -v and now see that it is using python2.7.  Is there a way to tell pip to use python3?  I cannot remove python2 as it is a dependency for a number of packages.

答:
Adding to @emrah-diril answer:

```<code>sudo apt-get -y install python3-pip
</code>```

and then use

```<code>sudo pip3 install pytz
</code>```

Body:
I installed pytz on Debian Buster via

sudo pip install pytz

and the install completed cleanly.  However, when I attempt to

import pytz

python throws an exception

    import pytz
ModuleNotFoundError: No module named 'pytz'

I installed pytz 2019.3 via pip 18.1.   Any thoughts on why pytz is not found?

Update:  I ran pip -v and now see that it is using python2.7.  Is there a way to tell pip to use python3?  I cannot remove python2 as it is a dependency for a number of packages.

Body:
Adding to @emrah-diril answer:

sudo apt-get -y install python3-pip

and then use

sudo pip3 install pytz


问:
In C# (or any language) what is/are your favourite way of removing repetition?
I've just coded a 700 line class. Awful. I hang my head in shame.  It's as opposite to DRY as a British summer.

It's full of cut and paste with minor tweaks here and there.  This makes it's a prime candidate for refactoring.  Before I embark on this, I'd thought I'd ask when you have lots of repetition, what are the first refactoring opportunities you look for?

For the record, mine are probably using:

Generic classes and methods

Method overloading/chaining.

What are yours?

答:
Sometimes by the time you "complete functionality" using copy and paste code, you've come to a point that it is maimed and mangled enough that any attempt at refactoring will actually take much, much longer than refactoring it at the point where it was obvious.

In my personal experience my favorite "way of removing repetition" has been the "Extract Method" functionality of Resharper (although this is also available in vanilla Visual Studio).

Many times I would see repeated code (some legacy app I'm maintaining) not as whole methods but in chunks within completely separate methods. That gives a perfect opportunity to turn those chunks into methods.

Monster classes also tend to reveal that they contain more than one functionality. That in turn becomes an opportunity to separate each distinct functionality into its own (hopefully smaller) class.

I have to reiterate that doing all of these is not a pleasurable experience at all (for me), so I really would rather do it right while it's a small ball of mud, rather than let the big ball of mud roll and then try to fix that.

OwnerDisplayName: IainMH

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jon Limjap


问:
try-catch blocks with the return type
If I have a method that returns something, like

```<code>public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}
</code>```

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

答:
Store your return value in a temporary variable like this:</p>

```<code>public DataTable ReturnSomething()
{
    DataTable returnValue = null;

    try
    {
        //logic here
        returnValue = ds.Tables[0];
    }
    catch (Exception e)
    {
        ErrorString=e.Message;
    }

    return returnValue;
}
</code>```

OwnerDisplayName: Julia

LastEditorDisplayName: Daniel L

Title: try-catch blocks with the return type

Body:
If I have a method that returns something, like

public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

Body:
Store your return value in a temporary variable like this:

public DataTable ReturnSomething()
{
    DataTable returnValue = null;

    try
    {
        //logic here
        returnValue = ds.Tables[0];
    }
    catch (Exception e)
    {
        ErrorString=e.Message;
    }

    return returnValue;
}

OwnerDisplayName: Simon


问:
How do add an animated button in my css and html
I am new to CSS and downloaded a pre-made login page online.
I wanted to customize and add some effects when the user clicks the button and after 2 days of research but I got nothing.
It would be great if could get some tips on how do I set up.

this is the animation I am trying to achieve: "https://codemyui.com/submit-button-loading-animation-click/"

here's my HTML.

<!DOCTYPE html>

      <meta charset="UTF-8">
      <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css'>
    <link rel="stylesheet" href="./style.css">

                <form id="signup-form">

Create Account

Use your Email for Registration
                    <input type="text" placeholder="Name" id="up_name" />
                    <input type="email" placeholder="Email" id="up_email"/>
                    <input type="password" placeholder="Password" id="up_password"/>
                    <button id="signUpBtn">Sign Up</button>
                </form>

                <form id="signin-form">

Sign in

Use your Email Account to Login
                    <input type="email" placeholder="Email" id="in_email"/>
                    <input type="password" placeholder="Password" id="in_password"/>
                    <button id="signInBtn">Sign In</button>
                </form>

Welcome Back!

To keep connected with us please login with your personal info

                <button class="ghost" id="gotoSignIn">Sign In</button>

Hello, Friend!

Enter your personal details and start journey with us

                    <button class="ghost" id="gotoSignUp">Sign Up</button>

```
<p>here's my CSS.</p>
<pre class="lang-css prettyprint-override"><code>
@import url('https://fonts.googleapis.com/css?family=Montserrat:400,800');

* {
    box-sizing: border-box;
}

body {
    background: #f6f5f7;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    font-family: 'Montserrat', sans-serif;
    height: 100vh;
    margin: 0px;
}

h1 {
    font-weight: bold;
    margin: 0;
}

h2 {
    text-align: center;
}

p {
    font-size: 14px;
    font-weight: 100;
    line-height: 20px;
    letter-spacing: 0.5px;
    margin: 20px 0 30px;
}

span {
    font-size: 12px;
}

a {
    color: #333;
    font-size: 14px;
    text-decoration: none;
    margin: 15px 0;
}

button {
    border-radius: 20px;
    border: 1px solid #FF4B2B;
    background-color: #FF4B2B;
    color: #FFFFFF;
    font-size: 12px;
    font-weight: bold;
    padding: 12px 45px;
    letter-spacing: 1px;
    text-transform: uppercase;
    transition: transform 80ms ease-in;

}

button:active {
    transform: scale(0.95);
}

button:focus {
    outline: none;
}

button.ghost {
    background-color: transparent;
    border-color: #FFFFFF;
}

form {
    background-color: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding: 0 50px;
    height: 100%;
    text-align: center;
}

input {
    background-color: #eee;
    border: none;
    padding: 12px 15px;
    margin: 8px 0;
    width: 100%;
}

.container {
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 14px 28px rgba(0,0,0,0.25),
            0 10px 10px rgba(0,0,0,0.22);
    position: relative;
    overflow: hidden;
    width: 100%;
    max-width: 100%;
    min-height: 100%;
}

.form-container {
    position: absolute;
    top: 0;
    height: 100%;
    transition: all 0.6s ease-in-out;
}

.sign-in-container {
    left: 0;
    width: 50%;
    z-index: 2;
}

.container.right-panel-active .sign-in-container {
    transform: translateX(100%);
}

.sign-up-container {
    left: 0;
    width: 50%;
    opacity: 0;
    z-index: 1;
}

.container.right-panel-active .sign-up-container {
    transform: translateX(100%);
    opacity: 1;
    z-index: 5;
    animation: show 0.6s;
}

@keyframes show {
    0%, 49.99% {
        opacity: 0;
        z-index: 1;
    }

    50%, 100% {
        opacity: 1;
        z-index: 5;
    }
}

.overlay-container {
    position: absolute;
    top: 0;
    left: 50%;
    width: 50%;
    height: 100%;
    overflow: hidden;
    transition: transform 0.6s ease-in-out;
    z-index: 100;
}

.container.right-panel-active .overlay-container{
    transform: translateX(-100%);
}

.overlay {
    background: #FF416C;
    background: -webkit-linear-gradient(to right, #FF4B2B, #FF416C);
    background: linear-gradient(to right, #FF4B2B, #FF416C);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 0 0;
    color: #FFFFFF;
    position: relative;
    left: -100%;
    height: 100%;
    width: 200%;
    transform: translateX(0);
    transition: transform 0.6s ease-in-out;
}

.container.right-panel-active .overlay {
    transform: translateX(50%);
}

.overlay-panel {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding: 0 40px;
    text-align: center;
    top: 0;
    height: 100%;
    width: 50%;
    transform: translateX(0);
    transition: transform 0.6s ease-in-out;
}

.overlay-left {
    transform: translateX(-20%);
}

.container.right-panel-active .overlay-left {
    transform: translateX(0);
}

.overlay-right {
    right: 0;
    transform: translateX(0);
}

.container.right-panel-active .overlay-right {
    transform: translateX(20%);
}

.social-container {
    margin: 20px 0;
}

.social-container a {
    border: 1px solid #DDDDDD;
    border-radius: 50%;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    margin: 0 5px;
    height: 40px;
    width: 40px;
}

footer {
    background-color: #222;
    color: #fff;
    font-size: 14px;
    bottom: 0;
    position: fixed;
    left: 0;
    right: 0;
    text-align: center;
    z-index: 999;
}

footer p {
    margin: 10px 0;
}

footer i {
    color: red;
}

footer a {
    color: #3c97bf;
    text-decoration: none;
}
</code>```

my Script.js

```<code>const gotoSignUpButton = document.getElementById('gotoSignUp');
const gotoSignInButton = document.getElementById('gotoSignIn');
const container = document.getElementById('container');

gotoSignUpButton.addEventListener('click', () => {
    container.classList.add("right-panel-active");
});

gotoSignInButton.addEventListener('click', () => {
    container.classList.remove("right-panel-active");
});
</code>```

and my authen.js (which I think isn't needed)

```<code>

//listen for auth status changes

auth.onAuthStateChanged(user => {
    if(user != null){
          JavascriptInterface.toast("Login Successful!!");
          JavascriptInterface.openMain(user.uid);
    }

})

////logout
//const logout = document.querySelector('#lgout');
//logout.addEventListener('click',(e) => {
//    e.preventDefault();
//    auth.signOut();
//});

//signup
const signupForm = document.querySelector('#signup-form');
const signinForm = document.querySelector('#signin-form');

signupForm.addEventListener('submit',(e) => {

    e.preventDefault();
    //get user Info
    const name = signupForm['up_name'].value;
    const email = signupForm['up_email'].value;
    const password = signupForm['up_password'].value;

    //signup the user
    auth.createUserWithEmailAndPassword(email,password).then(cred => {
        return db.collection('users').doc(cred.user.uid).set({
            name: signupForm['up_name'].value,
            email: signupForm['up_email'].value,
            password: signupForm['up_password'].value
        })
    }).then(() => {
         signupForm.reset();
         container.classList.remove("right-panel-active");
    });
});

signinForm.addEventListener('submit',(e) => {

    e.preventDefault();
    //get user Info
    const email = signinForm['in_email'].value;
    const password = signinForm['in_password'].value;

    //signin the user
        auth.signInWithEmailAndPassword(email,password).then(cred => {
                signinForm.reset();
        });
});

auth.setPersistence(firebase.auth.Auth.Persistence.NONE)
</code>```

Well Thanks in advance :)

答:
Something like this?

You can just change the styling and make it more appealing.

var button = document.getElementById("button");

button.addEventListener('click', function(){
      button.innerHTML = "Wait...";
      button.classList.add("loading");
      button.classList.remove("submit");

    setTimeout(function()
    {
      if(button.classList.contains("loading"))
      {
        button.classList.remove("loading");
        button.innerHTML = "Success";
        button.classList.add("success");
      }
    }, 3000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@keyframes rotate{
  from{
    transform: rotateZ(0deg);
  }
  to{
    transform: rotateZ(360deg);
  }
}
.container{
  width: 180px;
}
div#button{
  box-sizing: border-box;
  width: 100%;
  margin: 0 auto;
}

.loading{
  max-width: 50px;
  height: 50px;
  border-width: 5px;
  border-color: transparent #27a80c transparent #27a80c;
  border-style: solid;
  border-radius: 25px;
  background-color: transparent;
  font-size: 10px;
  text-align: center;
  line-height: 40px;
  color: #27a80c;

  animation: rotate 1s infinite;
}

.submit, .success{
  text-align: center;
  max-width: 120px;
  padding: 15px;
  border: thin solid transparent;
  background-color: white;
  transition: background-color color .25s ease;
  border-radius: 5px;
  cursor: pointer;
  height: 50px;
}

.submit{
  border-color: red;
  color: red;
}
.success{
  border-color: #27a80c;
  color: white;
  background-color: #27a80c;
}

.submit:hover{
  background-color: red;
  color: white;
}</code>```

    Submit

```

Body:
I am new to CSS and downloaded a pre-made login page online.
I wanted to customize and add some effects when the user clicks the button and after 2 days of research but I got nothing.
It would be great if could get some tips on how do I set up.

this is the animation I am trying to achieve: "https://codemyui.com/submit-button-loading-animation-click/"

here's my HTML.

<!DOCTYPE html>

      <meta charset="UTF-8">
      <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css'>
    <link rel="stylesheet" href="./style.css">

                <form id="signup-form">

Create Account

Use your Email for Registration
                    <input type="text" placeholder="Name" id="up_name" />
                    <input type="email" placeholder="Email" id="up_email"/>
                    <input type="password" placeholder="Password" id="up_password"/>
                    <button id="signUpBtn">Sign Up</button>
                </form>

                <form id="signin-form">

Sign in

Use your Email Account to Login
                    <input type="email" placeholder="Email" id="in_email"/>
                    <input type="password" placeholder="Password" id="in_password"/>
                    <button id="signInBtn">Sign In</button>
                </form>

Welcome Back!

To keep connected with us please login with your personal info

                <button class="ghost" id="gotoSignIn">Sign In</button>

Hello, Friend!

Enter your personal details and start journey with us

                    <button class="ghost" id="gotoSignUp">Sign Up</button>

here's my CSS.

@import url('https://fonts.googleapis.com/css?family=Montserrat:400,800');

* {
    box-sizing: border-box;
}

body {
    background: #f6f5f7;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    font-family: 'Montserrat', sans-serif;
    height: 100vh;
    margin: 0px;
}

h1 {
    font-weight: bold;
    margin: 0;
}

h2 {
    text-align: center;
}

p {
    font-size: 14px;
    font-weight: 100;
    line-height: 20px;
    letter-spacing: 0.5px;
    margin: 20px 0 30px;
}

span {
    font-size: 12px;
}

a {
    color: #333;
    font-size: 14px;
    text-decoration: none;
    margin: 15px 0;
}

button {
    border-radius: 20px;
    border: 1px solid #FF4B2B;
    background-color: #FF4B2B;
    color: #FFFFFF;
    font-size: 12px;
    font-weight: bold;
    padding: 12px 45px;
    letter-spacing: 1px;
    text-transform: uppercase;
    transition: transform 80ms ease-in;

}

button:active {
    transform: scale(0.95);
}

button:focus {
    outline: none;
}

button.ghost {
    background-color: transparent;
    border-color: #FFFFFF;
}

form {
    background-color: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding: 0 50px;
    height: 100%;
    text-align: center;
}

input {
    background-color: #eee;
    border: none;
    padding: 12px 15px;
    margin: 8px 0;
    width: 100%;
}

.container {
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 14px 28px rgba(0,0,0,0.25),
            0 10px 10px rgba(0,0,0,0.22);
    position: relative;
    overflow: hidden;
    width: 100%;
    max-width: 100%;
    min-height: 100%;
}

.form-container {
    position: absolute;
    top: 0;
    height: 100%;
    transition: all 0.6s ease-in-out;
}

.sign-in-container {
    left: 0;
    width: 50%;
    z-index: 2;
}

.container.right-panel-active .sign-in-container {
    transform: translateX(100%);
}

.sign-up-container {
    left: 0;
    width: 50%;
    opacity: 0;
    z-index: 1;
}

.container.right-panel-active .sign-up-container {
    transform: translateX(100%);
    opacity: 1;
    z-index: 5;
    animation: show 0.6s;
}

@keyframes show {
    0%, 49.99% {
        opacity: 0;
        z-index: 1;
    }

    50%, 100% {
        opacity: 1;
        z-index: 5;
    }
}

.overlay-container {
    position: absolute;
    top: 0;
    left: 50%;
    width: 50%;
    height: 100%;
    overflow: hidden;
    transition: transform 0.6s ease-in-out;
    z-index: 100;
}

.container.right-panel-active .overlay-container{
    transform: translateX(-100%);
}

.overlay {
    background: #FF416C;
    background: -webkit-linear-gradient(to right, #FF4B2B, #FF416C);
    background: linear-gradient(to right, #FF4B2B, #FF416C);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 0 0;
    color: #FFFFFF;
    position: relative;
    left: -100%;
    height: 100%;
    width: 200%;
    transform: translateX(0);
    transition: transform 0.6s ease-in-out;
}

.container.right-panel-active .overlay {
    transform: translateX(50%);
}

.overlay-panel {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding: 0 40px;
    text-align: center;
    top: 0;
    height: 100%;
    width: 50%;
    transform: translateX(0);
    transition: transform 0.6s ease-in-out;
}

.overlay-left {
    transform: translateX(-20%);
}

.container.right-panel-active .overlay-left {
    transform: translateX(0);
}

.overlay-right {
    right: 0;
    transform: translateX(0);
}

.container.right-panel-active .overlay-right {
    transform: translateX(20%);
}

.social-container {
    margin: 20px 0;
}

.social-container a {
    border: 1px solid #DDDDDD;
    border-radius: 50%;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    margin: 0 5px;
    height: 40px;
    width: 40px;
}

footer {
    background-color: #222;
    color: #fff;
    font-size: 14px;
    bottom: 0;
    position: fixed;
    left: 0;
    right: 0;
    text-align: center;
    z-index: 999;
}

footer p {
    margin: 10px 0;
}

footer i {
    color: red;
}

footer a {
    color: #3c97bf;
    text-decoration: none;
}

my Script.js

const gotoSignUpButton = document.getElementById('gotoSignUp');
const gotoSignInButton = document.getElementById('gotoSignIn');
const container = document.getElementById('container');

gotoSignUpButton.addEventListener('click', () => {
    container.classList.add("right-panel-active");
});

gotoSignInButton.addEventListener('click', () => {
    container.classList.remove("right-panel-active");
});

and my authen.js (which I think isn't needed)

//listen for auth status changes

auth.onAuthStateChanged(user => {
    if(user != null){
          JavascriptInterface.toast("Login Successful!!");
          JavascriptInterface.openMain(user.uid);
    }

})

////logout
//const logout = document.querySelector('#lgout');
//logout.addEventListener('click',(e) => {
//    e.preventDefault();
//    auth.signOut();
//});

//signup
const signupForm = document.querySelector('#signup-form');
const signinForm = document.querySelector('#signin-form');

signupForm.addEventListener('submit',(e) => {

    e.preventDefault();
    //get user Info
    const name = signupForm['up_name'].value;
    const email = signupForm['up_email'].value;
    const password = signupForm['up_password'].value;

    //signup the user
    auth.createUserWithEmailAndPassword(email,password).then(cred => {
        return db.collection('users').doc(cred.user.uid).set({
            name: signupForm['up_name'].value,
            email: signupForm['up_email'].value,
            password: signupForm['up_password'].value
        })
    }).then(() => {
         signupForm.reset();
         container.classList.remove("right-panel-active");
    });
});

signinForm.addEventListener('submit',(e) => {

    e.preventDefault();
    //get user Info
    const email = signinForm['in_email'].value;
    const password = signinForm['in_password'].value;

    //signin the user
        auth.signInWithEmailAndPassword(email,password).then(cred => {
                signinForm.reset();
        });
});

auth.setPersistence(firebase.auth.Auth.Persistence.NONE)

Well Thanks in advance :)

Body:
Something like this?

You can just change the styling and make it more appealing.

var button = document.getElementById("button");

button.addEventListener('click', function(){
      button.innerHTML = "Wait...";
      button.classList.add("loading");
      button.classList.remove("submit");

    setTimeout(function()
    {
      if(button.classList.contains("loading"))
      {
        button.classList.remove("loading");
        button.innerHTML = "Success";
        button.classList.add("success");
      }
    }, 3000);
});

@keyframes rotate{
  from{
    transform: rotateZ(0deg);
  }
  to{
    transform: rotateZ(360deg);
  }
}
.container{
  width: 180px;
}
div#button{
  box-sizing: border-box;
  width: 100%;
  margin: 0 auto;
}

.loading{
  max-width: 50px;
  height: 50px;
  border-width: 5px;
  border-color: transparent #27a80c transparent #27a80c;
  border-style: solid;
  border-radius: 25px;
  background-color: transparent;
  font-size: 10px;
  text-align: center;
  line-height: 40px;
  color: #27a80c;

  animation: rotate 1s infinite;
}

.submit, .success{
  text-align: center;
  max-width: 120px;
  padding: 15px;
  border: thin solid transparent;
  background-color: white;
  transition: background-color color .25s ease;
  border-radius: 5px;
  cursor: pointer;
  height: 50px;
}

.submit{
  border-color: red;
  color: red;
}
.success{
  border-color: #27a80c;
  color: white;
  background-color: #27a80c;
}

.submit:hover{
  background-color: red;
  color: white;
}

<div class="container">
  <div class="submit" id="button">
    Submit
  </div>
</div>


问:
Customize Twitter Bootstrap Classnames
http://getbootstrap.com/customize/

Above link, customizes Bootstrap's components, Less variables, and jQuery plugins to get your very own version.

I am wondering if it's possible to customize bootstrap by adding prefixes to it's classes, for example:

```<code>".container" = ".myid_container"
".btn-group" = ".myid_btn-group"
</code>```

答:
I know this is an old question, but this may help people coming here from search engines - you can do the following in scss to achieve the above:</p>

```<code>// allows this file to use bootstrap classes and functions
@forward "node_modules/bootstrap/scss/bootstrap";

.myid_container{
  @extend .container;
}

.myid_btn-group{
  @extend .btn-group;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Customize Twitter Bootstrap Classnames

Body:
http://getbootstrap.com/customize/

Above link, customizes Bootstrap's components, Less variables, and jQuery plugins to get your very own version.

I am wondering if it's possible to customize bootstrap by adding prefixes to it's classes, for example:

".container" = ".myid_container"
".btn-group" = ".myid_btn-group"

Body:
I know this is an old question, but this may help people coming here from search engines - you can do the following in scss to achieve the above:

// allows this file to use bootstrap classes and functions
@forward "node_modules/bootstrap/scss/bootstrap";

.myid_container{
  @extend .container;
}

.myid_btn-group{
  @extend .btn-group;
}


问:
How do I get Terraform to throw a specific error message depending on what account the user is in?
I have a terraform module that does domain delegation. For several variables there is some validation  against a hard-coded value to check that a user is using valid inputs, for example:

```<code>resource "null_resource" "validate_region" {
  count = contains(local.regions, var.region) == true ? 0 : "Please provide a valid AWS region. E.g. (us-west-2)"
}
</code>```

with local.regions being hard-coded and var.region being a user-set variable. The above code works in that when a user sets the variable wrong, it throws an error like this:

```<code>Error: Incorrect value type

  on .terraform/foo/main.tf line 46, in resource "null_resource" "validate_region":
  46:   count = contains(local.regions, var.region) == true ? 0 : "Please provide a valid AWS region. E.g. (us-west-2)"

Invalid expression value: a number is required.
</code>```

I now need to validate that the AWS account the user is currently using is the correct one. In this case it's up to the user to set the account id of the correct account in their variables, and my code needs to pull the account id of the account that's running the module and compare it against the user's variable. I've tried something like this:

```<code>data "aws_caller_identity" "account" {}

resource "null_resource" "validate_account" {
  count = data.aws_caller_identity.account.account_id == var.primary_account_id ? 0 : "Please check that you are using the AWS creds for the primary account for this domain."
}

data "aws_route53_zone" "primary" {
  name = local.primary_name
}
</code>```

with various syntax changes on the "{data.aws_caller_identity.account.account_id == var.primary_account_id}" ? 0 part in an effort to get the logic to work, but no luck. I would like it to throw an error like the region validation does, where it will show the error message I wrote. Instead(depending on syntax), it will work as expected for the correct account and throw a Error: no matching Route53Zone found error for the incorrect account, OR it will throw a completely different error presumably because the syntax is screwing things up.

How do I get this to work? is it possible?

答:
I figured out that this block:

```<code>data "aws_route53_zone" "primary" {
  name = local.primary_name
}
</code>```

was running before the account validation resource block. Add in a depends_on like so:

```<code>data "aws_route53_zone" "primary" {
  name       = local.primary_name
  depends_on = [null_resource.validate_account,
  ]
}
</code>```

And it's all good.

Body:
I have a terraform module that does domain delegation. For several variables there is some validation  against a hard-coded value to check that a user is using valid inputs, for example:

resource "null_resource" "validate_region" {
  count = contains(local.regions, var.region) == true ? 0 : "Please provide a valid AWS region. E.g. (us-west-2)"
}

with local.regions being hard-coded and var.region being a user-set variable. The above code works in that when a user sets the variable wrong, it throws an error like this:

Error: Incorrect value type

  on .terraform/foo/main.tf line 46, in resource "null_resource" "validate_region":
  46:   count = contains(local.regions, var.region) == true ? 0 : "Please provide a valid AWS region. E.g. (us-west-2)"

Invalid expression value: a number is required.

I now need to validate that the AWS account the user is currently using is the correct one. In this case it's up to the user to set the account id of the correct account in their variables, and my code needs to pull the account id of the account that's running the module and compare it against the user's variable. I've tried something like this:

data "aws_caller_identity" "account" {}

resource "null_resource" "validate_account" {
  count = data.aws_caller_identity.account.account_id == var.primary_account_id ? 0 : "Please check that you are using the AWS creds for the primary account for this domain."
}

data "aws_route53_zone" "primary" {
  name = local.primary_name
}

with various syntax changes on the "{data.aws_caller_identity.account.account_id == var.primary_account_id}" ? 0 part in an effort to get the logic to work, but no luck. I would like it to throw an error like the region validation does, where it will show the error message I wrote. Instead(depending on syntax), it will work as expected for the correct account and throw a Error: no matching Route53Zone found error for the incorrect account, OR it will throw a completely different error presumably because the syntax is screwing things up.

How do I get this to work? is it possible?

Body:
I figured out that this block:

data "aws_route53_zone" "primary" {
  name = local.primary_name
}

was running before the account validation resource block. Add in a depends_on like so:

data "aws_route53_zone" "primary" {
  name       = local.primary_name
  depends_on = [null_resource.validate_account,
  ]
}

And it's all good.


问:
Cannot prepare proper labels in Matplotlib
I have very simple code:

```<code>from matplotlib import dates
import matplotlib.ticker as ticker
my_plot=df_h.boxplot(by='Day',figsize=(12,5), showfliers=False, rot=90)
</code>```

I've got:

but I would like to have fewer labels on X axis. To do this I've add:

```<code>my_plot.xaxis.set_major_locator(ticker.MaxNLocator(12))
</code>```

It generates fewer labels but values of labels have wrong values (=first of few labels from whole list)
What am I doing wrong?

I have add additional information:

I've forgoten to show what is inside DataFrame.
I have three columns:
 reg_Date - datetime64 (index)
 temperature - float64
 Day - date converted from reg_Date to string, it looks like '2017-10'  (YYYY-MM)

Box plot group date by 'Day' and I would like to show values 'Day" as a label but not all values
, for example every third one.

答:
You were almost there. Just set ticker.MultipleLocator.

The pandas.DataFrame.boxplot also returns axes, which is an object of class matplotlib.axes.Axes. So you can use this code snippet to customize your labels:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

center = np.random.randint(50,size=(10, 20))
spread = np.random.rand(10, 20) * 30
flier_high = np.random.rand(10, 20) * 30 + 30
flier_low = np.random.rand(10, 20) * -30
y = np.concatenate((spread, center, flier_high, flier_low))

fig, ax = plt.subplots(figsize=(10, 5))
ax.boxplot(y)

x = ['Label '+str(i) for i in range(20)]
ax.set_xticklabels(x)
ax.set_xlabel('Day')

# Set a tick on each integer multiple of a base within the view interval.
ax.xaxis.set_major_locator(ticker.MultipleLocator(5))
plt.xticks(rotation=90)
</code>```

Body:
I have very simple code:

from matplotlib import dates
import matplotlib.ticker as ticker
my_plot=df_h.boxplot(by='Day',figsize=(12,5), showfliers=False, rot=90)

I've got:

but I would like to have fewer labels on X axis. To do this I've add:

my_plot.xaxis.set_major_locator(ticker.MaxNLocator(12))

It generates fewer labels but values of labels have wrong values (=first of few labels from whole list)
What am I doing wrong?

I have add additional information:

I've forgoten to show what is inside DataFrame.
I have three columns:
 reg_Date - datetime64 (index)
 temperature - float64
 Day - date converted from reg_Date to string, it looks like '2017-10'  (YYYY-MM)

Box plot group date by 'Day' and I would like to show values 'Day" as a label but not all values
, for example every third one.

Body:
You were almost there. Just set ticker.MultipleLocator.

The pandas.DataFrame.boxplot also returns axes, which is an object of class matplotlib.axes.Axes. So you can use this code snippet to customize your labels:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

center = np.random.randint(50,size=(10, 20))
spread = np.random.rand(10, 20) * 30
flier_high = np.random.rand(10, 20) * 30 + 30
flier_low = np.random.rand(10, 20) * -30
y = np.concatenate((spread, center, flier_high, flier_low))

fig, ax = plt.subplots(figsize=(10, 5))
ax.boxplot(y)

x = ['Label '+str(i) for i in range(20)]
ax.set_xticklabels(x)
ax.set_xlabel('Day')

# Set a tick on each integer multiple of a base within the view interval.
ax.xaxis.set_major_locator(ticker.MultipleLocator(5))
plt.xticks(rotation=90)


问:
What is a service mesh?
In the context of cloud computing, backend developers frequently refer to building (or using) "service mesh" but I don't fully understand what it is. Can you tell more?</p>

答:
In a typical distributed application architecture based on microservices, few of the functionalities that were present in centralized manner were moved into microservices level such that the business logic module handles functionalities & related business logic and the network functions take care of inter service communication, redundancy, health monitor, service discovery etc. The orchestration combined with containers and microservices helped in bringing in management of cloud setups and the scalability, however there was also a need for extensively managing the end-to-end (service to service) connectivity between the services & communication between them and also to reduce complexity at individual microservices in maintaining the inter service communications, resiliency, health monitor, service discovery etc..  This brought in the need for service mesh. Service mesh typically comes above CNI and and builds on its capabilities.

With the help of service mesh, the logic governing service-to-service communication has been pulled out of individual microservices and abstracted in the form of an infrastructure layer. All the inter service communication activities have been offloaded to service mesh which in-turn provides built-in support for network functions like redundancy, service discovery, health monitor etc. Hence, with a service mesh, all the service-to-service communications shall happen on-top of a software component called service mesh (or side-car proxy) and the microservices do not directly communicate with the other microservices.

Title: What is a service mesh?


问:
.htaccess redirect folder to a url
I'm trying to redirect a folder and all its sub files to a URL with a .htaccess file.

But

```<code>Redirect 301 /abc/cba/ http://www.aaa.com/
</code>```

Will make /abc/cba/ddd/index.html redirect to http://www.aaa.com/ddd/index.html

What I want is redirect /abc/cba/ /abc/cba/ddd/index.html to http://www.aaa.com/

Could anyone help? Thanks. If anything not clear, please let me know.

答:
I perfer the following method:</p>

```<code> RewriteEngine on
 RewriteCond %{REQUEST_URI}  ^/somedir           [NC]
 RewriteRule /(.*) http://somesite.com/lost/$1 [R=301,L]
</code>```

Title: .htaccess redirect folder to a url

Body:
I'm trying to redirect a folder and all its sub files to a URL with a .htaccess file.

But

Redirect 301 /abc/cba/ http://www.aaa.com/

Will make /abc/cba/ddd/index.html redirect to http://www.aaa.com/ddd/index.html

What I want is redirect /abc/cba/ /abc/cba/ddd/index.html to http://www.aaa.com/

Could anyone help? Thanks. If anything not clear, please let me know.

Body:
I perfer the following method:

 RewriteEngine on
 RewriteCond %{REQUEST_URI}  ^/somedir           [NC]
 RewriteRule /(.*) http://somesite.com/lost/$1 [R=301,L]


问:
How can I include a YAML file inside another?
So I have two YAML files, "A" and "B" and I want the contents of A to be inserted inside B, either spliced into the existing data structure, like an array, or as a child of an element, like the value for a certain hash key.

Is this possible at all? How? If not, any pointers to a normative reference?

答:
With Yglu, you can import other files like this:

A.yaml

```<code>foo: !? $import('B.yaml')
</code>```

B.yaml

```<code>bar: Hello
</code>```

```<code>$ yglu A.yaml
foo:
  bar: Hello
</code>```

As $import is a function, you can also pass an expression as argument:

```<code>  dep: !- b
  foo: !? $import($_.dep.toUpper() + '.yaml')
</code>```

This would give the same output as above.

Disclaimer: I am the author of Yglu.

OwnerDisplayName: kch

Body:
With Yglu, you can import other files like this:

A.yaml

foo: !? $import('B.yaml')

B.yaml

bar: Hello

$ yglu A.yaml
foo:
  bar: Hello

As $import is a function, you can also pass an expression as argument:

  dep: !- b
  foo: !? $import($_.dep.toUpper() + '.yaml')

This would give the same output as above.

Disclaimer: I am the author of Yglu.


问:
R data.table fast add with binom.test
I am trying to run binom.test on a data.table with both the X and N values provided for each row. I saw this post, which uses a static N value and tried to modify, but if I try I get:

```<code>dt = data.table(X=rbinom(100, 625, 1/5), N=rbinom(100, 625, 4/5))
dt[, P := binom.test(x=X, n=N)$p.value ]
# Error in binom.test(x = X, n = N) : incorrect length of 'x'
</code>```

The post also mentions aggregating by=X, but even still I get:

```<code>dt[, P := binom.test(x=X, n=N)$p.value, by=X ]
# Error in binom.test(x = X, n = N) : 'n' must be a positive integer >= 'x'
</code>```

Despite N always being a positive integer greater than X. My goal is not to group by values of X though, I want a binom.test p-value for every row.

答:
We could group by every row and apply binom.test on it.

```<code>library(data.table)

dt[, P := binom.test(x=X, n=N)$p.value, seq_len(nrow(dt))]
#which is same as
#dt[, P := binom.test(x=X, n=N)$p.value, 1:nrow(dt)]
</code>```

Title: R data.table fast add with binom.test

Body:
I am trying to run binom.test on a data.table with both the X and N values provided for each row. I saw this post, which uses a static N value and tried to modify, but if I try I get:

dt = data.table(X=rbinom(100, 625, 1/5), N=rbinom(100, 625, 4/5))
dt[, P := binom.test(x=X, n=N)$p.value ]
# Error in binom.test(x = X, n = N) : incorrect length of 'x'

The post also mentions aggregating by=X, but even still I get:

dt[, P := binom.test(x=X, n=N)$p.value, by=X ]
# Error in binom.test(x = X, n = N) : 'n' must be a positive integer >= 'x'

Despite N always being a positive integer greater than X. My goal is not to group by values of X though, I want a binom.test p-value for every row.

Body:
We could group by every row and apply binom.test on it.

library(data.table)

dt[, P := binom.test(x=X, n=N)$p.value, seq_len(nrow(dt))]
#which is same as
#dt[, P := binom.test(x=X, n=N)$p.value, 1:nrow(dt)]


问:
Updating entry widget live tkinter
I have two entry widgets, side by side, when entering a piece of text into one, I want the other the update with the SAME text.</p>

答:
If you associate an instance of StringVar with an entry, that instance and the widget will always be in sync -- a change to either is immediately reflected in another.

A side effect of this is that if two or more widgets share the same instance of StringVar, the widgets will also be in sync.

Example

```<code>import tkinter as tk

root = tk.Tk()

var = tk.StringVar()
e1 = tk.Entry(root, textvariable=var)
e2 = tk.Entry(root, textvariable=var)

e1.pack(side="top", fill="x")
e2.pack(side="top", fill="x")

root.mainloop()
</code>```

Title: Updating entry widget live tkinter

Body:
If you associate an instance of StringVar with an entry, that instance and the widget will always be in sync -- a change to either is immediately reflected in another.

A side effect of this is that if two or more widgets share the same instance of StringVar, the widgets will also be in sync.

Example

import tkinter as tk

root = tk.Tk()

var = tk.StringVar()
e1 = tk.Entry(root, textvariable=var)
e2 = tk.Entry(root, textvariable=var)

e1.pack(side="top", fill="x")
e2.pack(side="top", fill="x")

root.mainloop()


答:
We can use Map to loop over each of the corresponding elements of 'X' and 'N'

```<code>library(data.table)
dt[,  P := unlist(Map(function(x, y) binom.test(x = x, n = y)$p.value,  X, N))]
head(dt)
#     X   N            P
#1: 104 510 3.737474e-43
#2: 137 501 8.640380e-25
#3: 140 517 3.982312e-26
#4: 131 498 6.476382e-27
#5: 114 506 1.000591e-36
#6: 120 507 8.940756e-34
</code>```

Or without anonymous function call

```<code>dt[, P := sapply(Map(binom.test, x = X, n = N), `[[`, "p.value")]
</code>```

Title: R data.table fast add with binom.test

Body:
We can use Map to loop over each of the corresponding elements of 'X' and 'N'

library(data.table)
dt[,  P := unlist(Map(function(x, y) binom.test(x = x, n = y)$p.value,  X, N))]
head(dt)
#     X   N            P
#1: 104 510 3.737474e-43
#2: 137 501 8.640380e-25
#3: 140 517 3.982312e-26
#4: 131 498 6.476382e-27
#5: 114 506 1.000591e-36
#6: 120 507 8.940756e-34

Or without anonymous function call

dt[, P := sapply(Map(binom.test, x = X, n = N), `[[`, "p.value")]


问:
How to find all the colors between two colors?
I need to pick two colors, then find X colors (or tones) between them, each one separated with the same 'distance' of the other.

I still don't understand how colors are formed. Should I try using HSV, RGB, or hex?

答: Generally, colors between two colors is the colors that are on the line connecting the colors in given color space. So, in RGB color space the colors are different then in other color spaces.</p>


问:
file command generating 'invalid argument'
I have a perl script that traverses a set of directories and when it hits one of them it blows up with an Invalid Argument and I want to be able to programmatically skip it.  I thought I could start by finding out the file type with the file command but it too blows up like this:

```<code>$ file /sys/devices/virtual/net/br-ex/speed
/sys/devices/virtual/net/br-ex/speed: ERROR: cannot read `/sys/devices/virtual/net/br-ex/speed' (Invalid argument)
</code>```

If I print out the mode of the file with the perl or python stat function it tells me 33060 but I'm not sure what all the bits mean and I'm hoping a particular one would tell me not to try to look inside.  Any suggestions?

答:
Not related to this particular case, but I hit the same error when I ran it on a malicious ELF (Linux executable) file. In that case it was because the program headers of the ELF was intentionally corrupted. Looking at the source code for file command, this is clear as it checks the ELF headers and bails out with the same error in case the headers are corrupted:

```<code>    /*
     * Loop through all the program headers.
     */
    for ( ; num; num--) {
        if (pread(fd, xph_addr, xph_sizeof, off) <
            CAST(ssize_t, xph_sizeof)) {
            file_badread(ms);
            return -1;
        }
</code>```

TLDR; The file command checks not only the magic bytes, but it also performs other checks to validate a file type.

Body:
I have a perl script that traverses a set of directories and when it hits one of them it blows up with an Invalid Argument and I want to be able to programmatically skip it.  I thought I could start by finding out the file type with the file command but it too blows up like this:

$ file /sys/devices/virtual/net/br-ex/speed
/sys/devices/virtual/net/br-ex/speed: ERROR: cannot read `/sys/devices/virtual/net/br-ex/speed' (Invalid argument)

If I print out the mode of the file with the perl or python stat function it tells me 33060 but I'm not sure what all the bits mean and I'm hoping a particular one would tell me not to try to look inside.  Any suggestions?

Body:
Not related to this particular case, but I hit the same error when I ran it on a malicious ELF (Linux executable) file. In that case it was because the program headers of the ELF was intentionally corrupted. Looking at the source code for file command, this is clear as it checks the ELF headers and bails out with the same error in case the headers are corrupted:

    /*
     * Loop through all the program headers.
     */
    for ( ; num; num--) {
        if (pread(fd, xph_addr, xph_sizeof, off) <
            CAST(ssize_t, xph_sizeof)) {
            file_badread(ms);
            return -1;
        }

TLDR; The file command checks not only the magic bytes, but it also performs other checks to validate a file type.


问:
How can i convert this sql query in a eloquent laravel command?
in sql query this commando do exactly i wanted:

```<code>SELECT
    v.id,
    (
        SELECT sv.status_id
        FROM status_viagem sv
        WHERE sv.viagem_id = v.id
        ORDER BY sv.created_at DESC LIMIT 1 ) AS status_id
FROM viagens v
</code>```

Here is the sql results:

But i have no idea how can i do this using Laravel eloquent

Basically, a viagem entry can has a lot of status, but i need to get each viagem and their last status entry from status_viagem table (the pivot table)

by the way viagem/viagens means travel.

My class mapping:

```<code>class Viagem extends Model
{
  ...
  public function status()
  {
        return $this->belongsToMany('App\Status')->withTimestamps();
  }
  ...
}

class Status extends Model
{

    public function viagens()
    {
        return $this->belongsToMany('App\Viagem')->withTimestamps();
    }
}

</code>```

The belongsToMany at both classes gets me a many-to-many:

can someone help me? thanks

---------- Temporary Solution -------

Thanks for all help  guys. In fact i can't find a nice solution using only eloquent.

Step 1/3 - To bypass this situation i first execute the above sql to grab only the viagens under the desired status_id (last status_viagem entry):

$viagens_ids = DB::select(
            "SELECT viagem_id FROM (
                SELECT
                    v.id AS viagem_id,
                    (
                        SELECT sv.status_id
                        FROM status_viagem sv
                        WHERE sv.viagem_id = v.id
                        ORDER BY sv.id DESC LIMIT 1 ) AS status_id
                FROM viagens v
            ) AS tt

            WHERE tt.status_id = {$status->id}"
        );
```

<p>Step 2/3 - then i used the array_map to organize my viagens ids</p>

<pre class="lang-php prettyprint-override"><code>$a = array_map(
                function($obj) { return $obj->viagem_id; },
                $viagens_ids
            );
</code>```

Step 3/3 - And at last i used elequent whereIn to fetch my viagens:

 Viagem::with( 'status')->whereIn('id', $a)->get();
```

In fact i have solved the problem by a-old-sashion-way but i not happy with it because i wish i learn how to do it using eloquent. what bad to me.

答:
I am not sure what viagens and viagem represent, but I think one of the relationships has to be belongsToMany() and the other hasMany().

then after you set relationships correctly, you can use Eloquent like this :

```<code>$status_id = Viagem::with('status')->orderBy('created_at', 'desc')->first()->pluck('status_id');

</code>```

Body:
in sql query this commando do exactly i wanted:

SELECT
    v.id,
    (
        SELECT sv.status_id
        FROM status_viagem sv
        WHERE sv.viagem_id = v.id
        ORDER BY sv.created_at DESC LIMIT 1 ) AS status_id
FROM viagens v

Here is the sql results:

But i have no idea how can i do this using Laravel eloquent

Basically, a viagem entry can has a lot of status, but i need to get each viagem and their last status entry from status_viagem table (the pivot table)

by the way viagem/viagens means travel.

My class mapping:

class Viagem extends Model
{
  ...
  public function status()
  {
        return $this->belongsToMany('App\Status')->withTimestamps();
  }
  ...
}

class Status extends Model
{

    public function viagens()
    {
        return $this->belongsToMany('App\Viagem')->withTimestamps();
    }
}

The belongsToMany at both classes gets me a many-to-many:

can someone help me? thanks

---------- Temporary Solution -------

Thanks for all help  guys. In fact i can't find a nice solution using only eloquent.

Step 1/3 - To bypass this situation i first execute the above sql to grab only the viagens under the desired status_id (last status_viagem entry):

$viagens_ids = DB::select(
            "SELECT viagem_id FROM (
                SELECT
                    v.id AS viagem_id,
                    (
                        SELECT sv.status_id
                        FROM status_viagem sv
                        WHERE sv.viagem_id = v.id
                        ORDER BY sv.id DESC LIMIT 1 ) AS status_id
                FROM viagens v
            ) AS tt

            WHERE tt.status_id = {$status->id}"
        );

Step 2/3 - then i used the array_map to organize my viagens ids

$a = array_map(
                function($obj) { return $obj->viagem_id; },
                $viagens_ids
            );

Step 3/3 - And at last i used elequent whereIn to fetch my viagens:

 Viagem::with( 'status')->whereIn('id', $a)->get();

In fact i have solved the problem by a-old-sashion-way but i not happy with it because i wish i learn how to do it using eloquent. what bad to me.

Body:
I am not sure what viagens and viagem represent, but I think one of the relationships has to be belongsToMany() and the other hasMany().

then after you set relationships correctly, you can use Eloquent like this :

$status_id = Viagem::with('status')->orderBy('created_at', 'desc')->first()->pluck('status_id');


问:
XPath optimization to select a node if it does not have an ancestor
In very simple terms, I would like to write an XPath 1.0 query that selects 10 but not 15.  15 should not be selected since it has an ancestor ArgumentList.

Here is the XML.

```<code><IfStatement>
   <Expression>
      ...
         <PrimaryExpression>
            <PrimaryPrefix>
               <Literal Image="10"/>
            </PrimaryPrefix>
            <PrimarySuffix>
               <Arguments>
                  <ArgumentList>
                     <Expression>
                        ...
                           <PrimaryExpression>
                              <PrimaryPrefix>
                                 <Literal Image="15"/>
                              </PrimaryPrefix>
                           </PrimaryExpression>
                        ...
                     </Expression>
                  </ArgumentList>
               </Arguments>
            </PrimarySuffix>
         </PrimaryExpression>
      ...
   </Expression>
</IfStatement>
</code>```

Here is the XPath query I am using...

```<code>(//IfStatement | //ForStatement | //WhileStatement)
/Expression
//*
/PrimaryExpression
/PrimaryPrefix
/Literal[not(ancestor::ArgumentList)]
</code>```

The //* is required because of the unknown number of nodes in the hierarchy represented by the ... in the XML.

The problem is that ancestor::ArgumentList is a slow operation.  I would like to write the XPath query like the following.

```<code>(//IfStatement | //ForStatement | //WhileStatement)
/Expression
//*[not(self::ArgumentList)]
/PrimaryExpression
/PrimaryPrefix
/Literal
</code>```

The problem is that //*[not(self::ArgumentList)] does not prevent from selecting 15.

What do I put after //* to prevent from selecting 15 due to ArgumentList?

答:
With XPath 2.0 you could also do

```<code>//Literal except //ArgumentList//Literal
</code>```

but there is no reason to expect that this is better than the 1.0 solution using the ancestor axis. It all depends on the chosen XPath processor, of course,

Body:
In very simple terms, I would like to write an XPath 1.0 query that selects 10 but not 15.  15 should not be selected since it has an ancestor ArgumentList.

Here is the XML.

<IfStatement>
   <Expression>
      ...
         <PrimaryExpression>
            <PrimaryPrefix>
               <Literal Image="10"/>
            </PrimaryPrefix>
            <PrimarySuffix>
               <Arguments>
                  <ArgumentList>
                     <Expression>
                        ...
                           <PrimaryExpression>
                              <PrimaryPrefix>
                                 <Literal Image="15"/>
                              </PrimaryPrefix>
                           </PrimaryExpression>
                        ...
                     </Expression>
                  </ArgumentList>
               </Arguments>
            </PrimarySuffix>
         </PrimaryExpression>
      ...
   </Expression>
</IfStatement>

Here is the XPath query I am using...

(//IfStatement | //ForStatement | //WhileStatement)
/Expression
//*
/PrimaryExpression
/PrimaryPrefix
/Literal[not(ancestor::ArgumentList)]

The //* is required because of the unknown number of nodes in the hierarchy represented by the ... in the XML.

The problem is that ancestor::ArgumentList is a slow operation.  I would like to write the XPath query like the following.

(//IfStatement | //ForStatement | //WhileStatement)
/Expression
//*[not(self::ArgumentList)]
/PrimaryExpression
/PrimaryPrefix
/Literal

The problem is that //*[not(self::ArgumentList)] does not prevent from selecting 15.

What do I put after //* to prevent from selecting 15 due to ArgumentList?

Body:
With XPath 2.0 you could also do

//Literal except //ArgumentList//Literal

but there is no reason to expect that this is better than the 1.0 solution using the ancestor axis. It all depends on the chosen XPath processor, of course,


问:
Await socket.on('answerToRequest') possible with Socket.io?
Is the following somehow possible?</p>

```<code>async function doesSocketAgree(){
    socket.emit('doesOtherSocketAgree', otherSocketId);
    await socket.on('responseDoesSocketAgree', (answer)=>{
      console.log('answer');
});
}
</code>```

答:
It is, but not that way. You'll have to wrap things in a promise so that you can "return" from your await once data comes in as part of your "on" handling:

async function doesSocketAgree(){
  socket.emit('doesOtherSocketAgree', otherSocketId);
  await new Promise(resolve => {
    socket.on('responseDoesSocketAgree', answer => {
      resolve(answer);
    });
  });
}
```

And you probably want to remove that listener before you call resolve() so that it doesn't keep on triggering, because every time you call doesSocketAgree() you'd be adding a new listener to the "on:responseSocketAgree" pile. So that'll end up going wrong pretty quickly without cleanup.

On that note, you probably want to emit your "does it agree?" with a random token that your on handler can verify is the one that's scoped to the current function call, "because async".

Body:
Is the following somehow possible?

async function doesSocketAgree(){
    socket.emit('doesOtherSocketAgree', otherSocketId);
    await socket.on('responseDoesSocketAgree', (answer)=>{
      console.log('answer');
});
}

Body:
It is, but not that way. You'll have to wrap things in a promise so that you can "return" from your await once data comes in as part of your "on" handling:

async function doesSocketAgree(){
  socket.emit('doesOtherSocketAgree', otherSocketId);
  await new Promise(resolve => {
    socket.on('responseDoesSocketAgree', answer => {
      resolve(answer);
    });
  });
}

And you probably want to remove that listener before you call resolve() so that it doesn't keep on triggering, because every time you call doesSocketAgree() you'd be adding a new listener to the "on:responseSocketAgree" pile. So that'll end up going wrong pretty quickly without cleanup.

On that note, you probably want to emit your "does it agree?" with a random token that your on handler can verify is the one that's scoped to the current function call, "because async".


答:
Problem solved.

The issue lay in the way the dict was created. I had used dict.fromkeys() which I was unaware actually "uses the same object for all values... That means, all keys share the same empty list... When you try to .append to the value of one list, the changes are made in-place to the object, so changes to it are visible by all that reference it." See Append value to one list in dictionary appends value to all lists in dictionary

By instead using dict comprehension to create the dict, the issue was resolved and iterating and appending worked as expected.

Title: Appending to Nested Dict Lists

Body:
I have a nested dict of empty lists:

mom_fut = {'M2K': {'comm': [], 'mtm': []},
           'MNQ': {'comm': [], 'mtm': []},
           'NG': {'comm': [], 'mtm': []},
           'QM': {'comm': [], 'mtm': []},
           'VIX': {'comm': [], 'mtm': []},
           'ZS': {'comm': [], 'mtm': []},
           'ZW': {'comm': [], 'mtm': []}}

I am iterating through a list of strings that may contain the main dict keys. If the main key is present, I append corresponding values (from a separate df) to the respective nested lists ('comm' and 'mtm'):

for des in mom_fut_des:
    symb, mat = des.split()
        mom_fut[symb]['comm'].append(mtm_fut_mom.commissions[mtm_fut_mom.description == des].sum())
        mom_fut[symb]['mtm'].append(mtm_fut_mom.total[mtm_fut_mom.description == des].sum())

However, instead of appending the corresponding values to the respective key-value lists and returning the populated dict that I want (and expected):

{'M2K': {'comm': [-25.5777713], 'mtm': [-217.5835163]},
'MNQ': {'comm': [-1.8012515], 'mtm': [-3.7174765]},
 'NG': {'comm': [-12.7160691], 'mtm': [-326.9769691]},
 'QM': {'comm': [-1.5866343], 'mtm': [-49.4922593]},
 'VIX': {'comm': [-1.8242462], 'mtm': [-97.6354962]},
 'ZS': {'comm': [-12.9690108], 'mtm': [-415.3762608]},
 'ZW': {'comm': [-15.1305126], 'mtm': [-235.4963876]}}

It is returning all the values to each key's respective nested list:

{'M2K': {'comm': [-25.5777713,
   -1.8012515,
   -12.7160691,
   -1.5866343,
   -12.9690108,
   -1.8242462,
   -15.1305126],
  'mtm': [-217.5835163,
   -3.7174765,
   -326.9769691,
   -49.4922593,
   -415.3762608,
   -97.6354962,
   -235.4963876]},
 'MNQ': {'comm': [-25.5777713,
   -1.8012515,
   -12.7160691,
   -1.5866343,
   -12.9690108,
   -1.8242462,
   -15.1305126],
  'mtm': [-217.5835163,
   -3.7174765,
   -326.9769691,
   -49.4922593,
   -415.3762608,
   -97.6354962,
   -235.4963876]},
 'NG': {'comm': [-25.5777713,
   -1.8012515,
   -12.7160691,
   -1.5866343,
   -12.9690108,
   -1.8242462,
   -15.1305126],
  'mtm': [-217.5835163,
   -3.7174765,
   -326.9769691,
   -49.4922593,
   -415.3762608,
   -97.6354962,
   -235.4963876]},
 'QM': {'comm': [-25.5777713,
   -1.8012515,
   -12.7160691,
   -1.5866343,
   -12.9690108,
   -1.8242462,
   -15.1305126],
  'mtm': [-217.5835163,
   -3.7174765,
   -326.9769691,
   -49.4922593,
   -415.3762608,
   -97.6354962,
   -235.4963876]},
 'VIX': {'comm': [-25.5777713,
   -1.8012515,
   -12.7160691,
   -1.5866343,
   -12.9690108,
   -1.8242462,
   -15.1305126],
  'mtm': [-217.5835163,
   -3.7174765,
   -326.9769691,
   -49.4922593,
   -415.3762608,
   -97.6354962,
   -235.4963876]},
 'ZS': {'comm': [-25.5777713,
   -1.8012515,
   -12.7160691,
   -1.5866343,
   -12.9690108,
   -1.8242462,
   -15.1305126],
  'mtm': [-217.5835163,
   -3.7174765,
   -326.9769691,
   -49.4922593,
   -415.3762608,
   -97.6354962,
   -235.4963876]},
 'ZW': {'comm': [-25.5777713,
   -1.8012515,
   -12.7160691,
   -1.5866343,
   -12.9690108,
   -1.8242462,
   -15.1305126],
  'mtm': [-217.5835163,
   -3.7174765,
   -326.9769691,
   -49.4922593,
   -415.3762608,
   -97.6354962,
   -235.4963876]}}

I can get the "correct" output adjusting the code and using dict.update()

for des in mom_fut_des:
    symb, mat = des.split()
    comm = mtm_fut_mom.commissions[mtm_fut_mom.description == des].sum()
    mtm = mtm_fut_mom.total[mtm_fut_mom.description == des].sum()
    mom_fut.update({symb:{'comm':[comm],'mtm':[mtm]}})

But I need to use lists and append since I may have more than one instance of each key, so potentially multiple values in each nested list.


问:
How to set CORS headers to a client
I'm using this client

var client = new forcetk.Client();

To make requests. I'm trying to pass another URL but the

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

error shows up. Can i set up any headers to the client? Is there a way to make my client's request inside an XMLHttpRequest call? Any help would be much appreciated. Thanks in advance.

Here is my oversimplified code

```<code>> forcetk.Client.prototype.createBlob = function (objtype, fields,
> filename, payloadField, payload, callback, error, retry) {
> 'use strict';
>         let res = this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/',
>                          fields, filename, payloadField, payload, callback, error, retry);
>         res.header("Access-Control-Allow-Origin", "*");
>         return res;
>     };
</code>```

答:
For testing locally you must enable CORS on your server and add the following headers to your response from server not your client:

```<code>'Access-Control-Allow-Origin': '*'
</code>```

A production setup would have CORS disabled and header in response looks like this:

```<code>'Access-Control-Allow-Origin': 'https://www.google.com'
</code>```

Setting the Access-Control-Allow-Origin to a specific domain and disabling CORS makes it so no one could invoke your API outside of your domain, therefore giving you the error you are getting currently.

Here is an example response from the server in JavaScript

```<code>var response = {
 "isBase64Encoded": false,
 "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'},
 "statusCode": 200,
 "body": "{\"result\": \"Success.\"}"
 };
</code>```

When CORS is enabled and you are calling out to the server from localhost for example, it will send a Preflight request https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request. In the past this has triggered duplicate code invokes on me due to my unawareness of it. It was as simple as checking null parameter values on the server side code.

Title: How to set CORS headers to a client

Body:
I'm using this client

var client = new forcetk.Client();

To make requests. I'm trying to pass another URL but the

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

error shows up. Can i set up any headers to the client? Is there a way to make my client's request inside an XMLHttpRequest call? Any help would be much appreciated. Thanks in advance.

Here is my oversimplified code

> forcetk.Client.prototype.createBlob = function (objtype, fields,
> filename, payloadField, payload, callback, error, retry) {
> 'use strict';
>         let res = this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/',
>                          fields, filename, payloadField, payload, callback, error, retry);
>         res.header("Access-Control-Allow-Origin", "*");
>         return res;
>     };

Body:
For testing locally you must enable CORS on your server and add the following headers to your response from server not your client:

'Access-Control-Allow-Origin': '*'

A production setup would have CORS disabled and header in response looks like this:

'Access-Control-Allow-Origin': 'https://www.google.com'

Setting the Access-Control-Allow-Origin to a specific domain and disabling CORS makes it so no one could invoke your API outside of your domain, therefore giving you the error you are getting currently.

Here is an example response from the server in JavaScript

var response = {
 "isBase64Encoded": false,
 "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'},
 "statusCode": 200,
 "body": "{\"result\": \"Success.\"}"
 };

When CORS is enabled and you are calling out to the server from localhost for example, it will send a Preflight request https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request. In the past this has triggered duplicate code invokes on me due to my unawareness of it. It was as simple as checking null parameter values on the server side code.


问:
Order a list in Flutter
What's the best approach to order a list on a ListView (or similar widget)?

I'm using table_calendar to display events on the calendar so I need to order the different events on one day by date (this field is already created for each event).

答:
```<code>  final items = List.generate(10, (index) => index + 1);

  void order() {
    final ascending = items[0] > items[1];

    setState(() {
      if (ascending) {
        items.sort();
      } else {
        items.sort((a, b) => b - a);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: items.length + 1,
        itemBuilder: (context, index) {
          if (index == items.length) {
            return FlatButton(
              onPressed: order,
              child: Text("Order"),
            );
          }

          return Center(child: Text("Entry ${items[index]}"));
        });
  }
</code>```

Title: Order a list in Flutter