text:
<?xml version="1.0" encoding="UTF-8"?>
<taskbody class="- topic/body task/taskbody " xmlns:dita-ot="ns">
  <prereq class="- topic/section task/prereq ">
    <table class="- topic/table " colsep="1" frame="all"
      id="unique_6_Connect_42_table_e4z_lsl_gcb" rowsep="1">
      <title class="- topic/title ">Normal table.</title>
      <tgroup class="- topic/tgroup " cols="2">
        <colspec class="- topic/colspec " colname="col1" colnum="1"
          colwidth="1*" rowheader="headers" style="width:50%;"/>
        <colspec class="- topic/colspec " colname="col2" colnum="2"
          colwidth="1*" rowheader="headers" style="width:50%;"/>
        <thead class="- topic/thead ">
          <row class="- topic/row ">
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="1">fasf</entry>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="1"/>
          </row>
        </thead>
        <tbody class="- topic/tbody ">
          <row class="- topic/row ">
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="2">fasf</entry>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="2">324</entry>
          </row>
          <row class="- topic/row ">
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="3">fasd</entry>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="3">5ter</entry>
          </row>
          <row class="- topic/row ">
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="4">fas</entry>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="4">85</entry>
          </row>
          <row class="- topic/row ">
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="5">fasd</entry>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="5">twert</entry>
          </row>
          <row class="- topic/row ">
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="6">fas</entry>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="6">786</entry>
          </row>
          <row class="- topic/row ">
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="7">fas</entry>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="7">856</entry>
          </row>
          <row class="- topic/row ">
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="8">fas</entry>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="8">85586</entry>
          </row>
          <row class="- topic/row ">
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="9">fas</entry>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="9">856</entry>
          </row>
          <row class="- topic/row ">
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="10">fas</entry>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="10">856</entry>
          </row>
          <row class="- topic/row ">
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="11">fdasf</entry>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="11">33</entry>
          </row>
          <oxy:oxy-range-start hr_id="1" id="sc_1" xmlns:oxy="http://www.oxygenxml.com/extensions/author"/>
          <oxy:oxy-insert hr_id="1" href="#sc_1" xmlns:oxy="http://www.oxygenxml.com/extensions/author">
            <oxy:oxy-author>dan</oxy:oxy-author>
            <oxy:oxy-content>insert</oxy:oxy-content>
            <oxy:oxy-date>2017/12/20</oxy:oxy-date>
            <oxy:oxy-hour>15:09:05</oxy:oxy-hour>
            <oxy:oxy-tz>+02:00</oxy:oxy-tz>
          </oxy:oxy-insert>
          <oxy:oxy-insert-hl xmlns:oxy="http://www.oxygenxml.com/extensions/author"/>
          <row class="- topic/row ">
            <oxy:oxy-insert-hl xmlns:oxy="http://www.oxygenxml.com/extensions/author"/>
            <entry class="- topic/entry " colname="col1" dita-ot:x="1" dita-ot:y="12">
              <oxy:oxy-insert-hl xmlns:oxy="http://www.oxygenxml.com/extensions/author">XXXX</oxy:oxy-insert-hl>
            </entry>
            <oxy:oxy-insert-hl xmlns:oxy="http://www.oxygenxml.com/extensions/author"/>
            <entry class="- topic/entry " colname="col2" dita-ot:x="2" dita-ot:y="12">
              <oxy:oxy-insert-hl xmlns:oxy="http://www.oxygenxml.com/extensions/author">YYYY</oxy:oxy-insert-hl>
            </entry>
            <oxy:oxy-insert-hl xmlns:oxy="http://www.oxygenxml.com/extensions/author"/>
          </row>
          <oxy:oxy-insert-hl xmlns:oxy="http://www.oxygenxml.com/extensions/author"/>
          <oxy:oxy-range-end hr_id="1" xmlns:oxy="http://www.oxygenxml.com/extensions/author"/>
        </tbody>
      </tgroup>
    </table>
    <simpletable class="- topic/simpletable " frame="none"
      id="unique_6_Connect_42_simpletable_rvk_zrl_gcb" relcolwidth="1* 1*">
      <colspec class=" topic/colspec " style="width:50%;"/>
      <colspec class=" topic/colspec " style="width:50%;"/>
      <oxy:table-header-group class=" simpletable/table-header-group " xmlns:oxy="http://www.oxygenxml.com/extensions/author">
        <sthead class="- topic/sthead ">
          <stentry class="- topic/stentry ">fasdf</stentry>
          <stentry class="- topic/stentry "/>
        </sthead>
      </oxy:table-header-group>
      <oxy:table-row-group class=" simpletable/table-row-group " xmlns:oxy="http://www.oxygenxml.com/extensions/author">
        <strow class="- topic/strow ">
          <stentry class="- topic/stentry ">fasd</stentry>
          <stentry class="- topic/stentry ">23141234</stentry>
        </strow>
        <strow class="- topic/strow ">
          <stentry class="- topic/stentry ">fasd</stentry>
          <stentry class="- topic/stentry ">634</stentry>
        </strow>
        <strow class="- topic/strow ">
          <stentry class="- topic/stentry ">fasdffa</stentry>
          <stentry class="- topic/stentry ">6</stentry>
        </strow>
        <strow class="- topic/strow ">
          <stentry class="- topic/stentry ">fasd</stentry>
          <stentry class="- topic/stentry ">412341234</stentry>
        </strow>
        <strow class="- topic/strow ">
          <stentry class="- topic/stentry ">fasd</stentry>
          <stentry class="- topic/stentry ">634</stentry>
        </strow>
        <strow class="- topic/strow ">
          <stentry class="- topic/stentry ">ffasd</stentry>
          <stentry class="- topic/stentry ">41234</stentry>
        </strow>
        <strow class="- topic/strow ">
          <stentry class="- topic/stentry ">fasdf</stentry>
          <stentry class="- topic/stentry ">4123</stentry>
        </strow>
        <strow class="- topic/strow ">
          <stentry class="- topic/stentry ">fasd</stentry>
          <stentry class="- topic/stentry ">4</stentry>
        </strow>
        <strow class="- topic/strow ">
          <stentry class="- topic/stentry ">fasd</stentry>
          <stentry class="- topic/stentry ">34</stentry>
        </strow>
        <strow class="- topic/strow ">
          <stentry class="- topic/stentry ">fas</stentry>
          <stentry class="- topic/stentry ">634</stentry>
        </strow>
        <oxy:oxy-range-start hr_id="2" id="sc_2"/>
        <oxy:oxy-insert hr_id="2" href="#sc_2">
          <oxy:oxy-author>dan</oxy:oxy-author>
          <oxy:oxy-content>insert</oxy:oxy-content>
          <oxy:oxy-date>2017/12/20</oxy:oxy-date>
          <oxy:oxy-hour>15:05:13</oxy:oxy-hour>
          <oxy:oxy-tz>+02:00</oxy:oxy-tz>
        </oxy:oxy-insert>
        <strow class="- topic/strow ">
          <oxy:oxy-insert-hl/>
          <stentry class="- topic/stentry ">
            <oxy:oxy-insert-hl>AAA</oxy:oxy-insert-hl>
          </stentry>
          <oxy:oxy-insert-hl/>
          <stentry class="- topic/stentry ">
            <oxy:oxy-insert-hl>BBB</oxy:oxy-insert-hl>
          </stentry>
          <oxy:oxy-insert-hl/>
        </strow>
        <oxy:oxy-range-end hr_id="2"/>
      </oxy:table-row-group>
    </simpletable>
  </prereq>
</taskbody>


text:
<?php

namespace App\Http\Controllers\User;

use App\Models\Teacher;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class TeacherController extends Controller
{
    //
    public function index()
    {
        return Teacher::all();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<title>pwd</title>

pwd

OS/161 Reference Manual

Name

pwd - print working directory

Synopsis

<tt>/bin/pwd</tt>

Description

<tt>pwd</tt> prints the current working directory.

Requirements

<tt>pwd</tt> uses the following system calls:

 __getcwd

 write

 _exit

pwd should function properly once the basic system calls assignment is
completed, except on filesystems or in directories that do not support
getcwd.
Note that by default emufs does not
support getcwd except in its root directory.

<tt>pwd</tt> should function properly in all directories of your
filesystem once the file system assignment is completed.


text:
  background-image: none;
  background-color: #fff;
}
#category .has-header{
  top: 0;
}

#category div,ul,li,h1,h2,h3,img,a{
  font-family:'微软雅黑';
  font-size:16px;
  padding:0;
  margin:0;
  border:0;
  list-style:none;
  color:#666;
  font-weight:300;
}

#category a,span{
  display:block;
  text-decoration:none;
}

#category body{
  overflow:hidden;
}
#category #header{
  display:block;
  background-color: #333;
  background-image:url(../../img/common/header-bg.png);
  background-size:100% 44px;
  width:100%;
  height:44px;
  overflow:hidden;
}
#category .header-left{
  width:40px;
  height:44px;
  position:absolute;
}
#category .header-left span{
  width:20px;
  height:20px;
  margin:12px 0 0 10px;
  background-size:200px 200px;
  background-position:-20px 0;
  background-image:url(../../img/common/sprites.png);
}
#category .header-center{
  height:44px;
  position:absolute;
  left:40px;
  right:40px;
}
#category .header-center span{
  width:96%;
  height:30px;
  margin:6px 2%;
  background-color:#fff;
  border:2px solid #dfdfdf;
  border-radius: 5px;
}
#category .header-right{
  width:40px;
  height:44px;
  position:absolute;
  right:0;
}
#category .header-right span{
  width:20px;
  height:20px;
  margin:12px 0 0 10px;
  background-size:200px 200px;
  background-position:-60px 0;
  background-image:url(../../img/common/sprites.png);
}
#category #nav{
  position:absolute;
  top:45px;
  bottom:0;
  width:90px;
  overflow:hidden;
}
#category #nav ul{
  display:block;
  width:100px;
  height:100%;
  overflow-x:hidden;
  overflow-y:scroll;
}
#category #nav ul li{
  border-bottom:1px solid #e0e0e0;
  text-align:center;
  line-height:50px;
  width:89px;
  height:49px;
  font-size:12px;
}
#category #nav .nav-blur{
  color:#252525;
  border-right:1px solid #e0e0e0;
  background-color:#f3f4f6;
}
#category #nav .nav-current{
  color:red;
  border-right:1px solid #fff;
  background-color:#fff;
}
#category #pro{
  position:absolute;
  left:90px;
  top:45px;
  right:0;
  bottom:0;
  overflow:hidden;
}
#category .pro-scroll{
  width:200%;
  height:100%;
  overflow-y:scroll;
}
#category .pro-warp{
  width:50%;
  background-color: #fff;
}
#category #pro .banner{
  margin:10px 12px;
}
#category #pro img{
  width:100%;
}
#category #pro .content{
  overflow:hidden;
}
#category #pro .content-title{
  margin-top:15px;
  font-size:12px;
  font-weight:700;
  padding-left:10px;
  font-family:'宋体';
}
#category #pro .content-body{
  margin:0px 12px;
  overflow:hidden;
}
#category #pro .content-body-list{
  width:33%;
  margin-top:10px;
  float:left;
}
#category #pro .content-body-list span{
  font-size:14px;
  text-align:center;
  font-family:'宋体';
}


text:
[Leaflet](http://www.leafletjs.com) plugin to create map icons using [Maki Icons](https://www.mapbox.com/maki/) from MapBox. Markers are retrieved from MapBox's [Static Marker API](https://www.mapbox.com/developers/api/static/#markers).

[![Screenshot](https://raw.github.com/jseppi/Leaflet.MakiMarkers/master/images/screenshot.png "Screenshot of MakiMarkers")](http://jsfiddle.net/Zhzvp/)

## Usage

Simply include `Leaflet.MakiMarkers.js` in your page after you include `Leaflet.js`: `<script src="Leaflet.MakiMarkers.js"></script>`

```js
// Specify a Maki icon name, hex color, and size (s, m, or l).
// An array of icon names can be found in L.MakiMarkers.icons or at https://www.mapbox.com/maki/
// Lowercase letters a-z and digits 0-9 can also be used. A value of null will result in no icon.
// Color may also be set to null, which will result in a gray marker.
var icon = L.MakiMarkers.icon({icon: "rocket", color: "#b0b", size: "m"});
L.marker([30.287, -97.72], {icon: icon}).addTo(map);
```

[JSFiddle Demo](http://jsfiddle.net/Zhzvp/26/)

## Requirements

[Leaflet](http://www.leafletjs.com) 0.5+

## Thanks

Thanks to [MapBox](http://www.mapbox.com) for making their Marker API available and for the Maki icon set.


text:
<!DOCTYPE html><meta charset=utf-8><title>WICS</title>

Sentences about European capitals.

  Dublin is the capital of Ireland.  The capital of the Czech Republic is Prague. Madrid is the capital of Spain. Berlin is the capital of Germany.


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>frameset</title>
</head>
<frameset rows="50%,50%">

    <frame src="a.html">

    <frameset cols="25%,75%">
        <frame src="b.html">
        <frame src="c.html">
    </frameset>

</frameset>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="../../js/frame.js" type="text/javascript"></script>
</html>


text:
@interface SKBasicView : UIView <SKBasicViewProtocol>
@property (strong, nonatomic) SKBasicDataSource *basicDataSource;
@end


text:
* Proposal: [SE-0170](0170-nsnumber_bridge.md)
* Author(s): [Philippe Hausler](https://github.com/phausler)
* Review Manager: [Ben Cohen](https://github.com/airspeedswift)
* Status: **Active review (April 14...April 21, 2017)**

##### Revision history

* **v1** Initial version

## Introduction

`NSNumber` has been a strange duck in the Swift world especially when it has come to bridging and interacting with other protocols. An attempt was made to make a type preserving `NSNumber` subclass; however that defeated numerous optimizations in Foundation and also caused some rather unfortunate disparity between where and how the NSNumbers were created.

## Motivation

Swift should have a consistent experience across all the SDK. No matter if you are using Objective-C in your app/framework in addition to Swift or not the behavior should be easily understood and consistent. Furthermore performance optimizations like tagged pointers or other fast-path accessors in Objective-C or CoreFoundation based code should just work no matter the context in which a `NSNumber` is created.

There are some really spooky behaviors as of current; here are a few extreme examples -

#### Example 1
```swift
let n = NSNumber(value: Int64.max)
if n is Int16 {
    // this is true as of the current build of Swift!
}
```

#### Example 2
```swift
let n = NSNumber(value: Int64.max)
if n is Int16 {
    // this is true as of the current build of Swift!
} else if n is Int64 {
	// Ideally we should get to here
}
```

#### Example 3
```swift
let n = NSNumber(value: Int64(42))
if let value = n as? UInt8 {
    // This makes sense if NSNumber is viewed as an abstract numeric box
}
```

But there are some subtile failures that occur as well -

#### Example 4
```swift
// Serialization behind the scenes causes numeric failures if we were 100% strict
open class MyDocument : NSDocument {
	var myStateValue: Int16 = 0

	public static func restoreWindow(withIdentifier identifier: String, state: NSCoder, completionHandler: @escaping (NSWindow?, Error?) -> Swift.Void) {
		myStateValue = state.decodeObject(forKey: "myStateValue") as! Int16 // this is expected to pass since we encoded a Int16 value and we expect at least to get an Int16 out.
	}

	open func encodeRestorableState(with coder: NSCoder) {
		coder.encodeObject(myStateValue, forKey: "myStateValue")
	}
}
```

#### Example 5
```swift
// lets say you have a remote server you have no control over except getting JSON requests back
// the format specifies that the response will have a timestamp in a value that is the integral number of milliseconds since 1970
// e.g. { "timestamp" : 1487980252519 } is valid JSON, but a recent server upgrade changes it to be  "timestamp" : 1487980252519.0 } which is also valid JSON

// initially code could be written validly as

let payload = JSONSerialization.jsonObject(with: response, options: []) as? [String : Int]

// but a remote server change could break things if we were strict and requires this code change

let payload = JSONSerialization.jsonObject(with: response, options: []) as? [String : Double]

// But the responses are still integral!

```

#### Example 6
```swift
let itDoesntDoWhatYouThinkItDoes = Int8(NSNumber(value: Int64.max)) // counterintutively (as legacy baggage of C) this is Int8(-1)
```

All of these examples boil down to the simple question: what does `as?` mean for NSNumber. It is worth noting that `is` should follow the same logic as `as?`.

## Proposed solution

`as?` for NSNumber should mean "Can I safely express the value stored in this opaque box called a NSNumber as the value I want?".

#### Solution Example 1
```swift
// The trivial case of "what you put in the box is what you get out"
let n = NSNumber(value: UInt32(543))
let v = n as? UInt32
// v is UInt32(543)
```

#### Solution Example 2
```swift
// The trivial case of the other way around from Solution Example 1
let v: UInt32 = 543
let n = v as NSNumber
// n == NSNumber(value: 543)
```

#### Solution Example 3
```swift
// Safe "casting"
let n = NSNumber(value: UInt32(543))
let v = n as? Int16
// v is Int16(543)
```

In this case `n` is storing a value of 543 obtained from a `UInt32`. Asking the question "Can I safely express the value stored in this opaque box called a `NSNumber` as the value I want?"; we have 543, can it be expressed safely as a `Int16`? Absolutely!

#### Solution Example 4
```swift
// Failures when casting that lose the value stored
let n = NSNumber(value: UInt32(543))
let v = n as? Int8
// v is nil
```

In this case `n` is storing a value of 543 obtained from a `UInt32` but when asked can it be safely represented as the requested type `Int8` the answer is; of course not.

#### Solution Example 5
```swift
let v = Int8(NSNumber(value: Int64.max))
// v is nil because Int64.max cannot be safely expressed as Int8
```

## Detailed design

The following methods will be changed deprecated in swift 4 because the behavior is truncating not an assertion of exactly:

```swift
extension Int8 {
    init(_ number: NSNumber)
}

extension UInt8 {
    init(_ number: NSNumber)
}

extension Int16 {
    init(_ number: NSNumber)
}

extension UInt16 {
    init(_ number: NSNumber)
}

extension Int32 {
    init(_ number: NSNumber)
}

extension UInt32 {
    init(_ number: NSNumber)
}

extension Int64 {
    init(_ number: NSNumber)
}

extension UInt64 {
    init(_ number: NSNumber)
}

extension Float {
    init(_ number: NSNumber)
}

extension Double {
    init(_ number: NSNumber)
}

extension CGFloat {
    init(_ number: NSNumber)
}

extension Bool {
    init(_ number: NSNumber)
}

extension Int {
    init(_ number: NSNumber)
}

extension UInt {
    init(_ number: NSNumber)
}
```

To the optional variants as such:

```swift
extension Int8 {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension UInt8 {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension Int16 {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension UInt16 {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension Int32 {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension UInt32 {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension Int64 {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension UInt64 {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension Float {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension Double {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension CGFloat {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension Bool {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension Int {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

extension UInt {
    init?(exactly number: NSNumber)
    init(truncating number: NSNumber)
}

```

The behavior of exactly will be an exact bitwise representation for stored integer types such that any initialization must be able to express the initialized type with the stored representation in the NSNumber or it will fail and return nil. The truncating versions on the other hand will be similar to fetching the value via that type accessor. e.g. `Int8(truncating: myNSNumber)` will be tantamount to calling `int8Value `on said number

## Impact on existing code

The one big repercussion is that the bridging methods cannot be versioned for swift 3 and swift 4 availability so we must pick one implementation or another for the bridging. Swift 4 modules or frameworks must bridge in the same manner as Swift 3 since the implementation is the behavioral difference, not the calling module.

There are a number of places in frameworks where NSNumbers are used to provide results. For example CoreData queries can potentially yield NSNumbers, Coding and Archival use NSNumbers for storage under the hood, Serialization uses NSNumbers for numeric representations (there are many more that apply these are just a few that can easily lead to corruption or malformed data when users accidentally truncate via the current bridging behavior).

Overall I am of the belief that any case that this would break existing code it was potentially incorrect behavior on the part of the developer using the bridge of NSNumber and if it is not the facilities of NSNumber are still present (you can still call `NSNumber(value: Int64.max).int8Value` to get `-1` if that is what you really mean. That way is unambiguous and distinctly clear for maintainable code and reduces the overall magic/spooky behavior.

## Source compatibility

This does change the result of cast via `as?` so it does not change source compatibility but it does change runtime compatibility. In the end, round tripped NSNumbers into collections that bridge across are relatively rare and it is much more common to get NSNumbers out of APIs. The original `as?` cast required developers to be aware of potential failure by syntax, the change here is a safer way of expressing values for all numbers in one uniform methodology that is both more performant as well as more correct in more common cases. In short the runtime effect is a step in the right direction.

## Effect on ABI stability

This change should have no direct impact upon ABI.

## Effect on API resilience

The initializers that had no decoration are marked as deprecated so the remaining portion is considered additive only.

## Considerations for Objective-C platforms

This brings in line the concepts of the existing Objective-C APIs to the intent that was originally used for NSNumber and the usage. Bridging NSNumbers (for platforms that support it and cases that are supported) should always respect the concept of tagged pointers. In just property list cases alone it is approximately a 2% performance loss to avoid the tagged pointer cases; just by using swift there should be little to no performance penalty for sending these types either direction on the bridge in comparison to the equivalent Objective-C implementations.

## Considerations for Linux platforms

We do not have bridging on Linux so the `as?` cast is less important; but if it were to have bridging this would be the desired functionality.

## Alternatives considered

We have explored making NSNumbers created in Swift to be strongly type preserving. This unfortunately results in a severe inconsistency between APIs implemented in Swift and those implemented in Objective-C. Instead of having a disparate behavior depending on the spooky action determined in an opaque framework it is better to have a simple story no matter what language the NSNumber was made in and no matter what facility it was created with. To do so we have only one real way of representing numeric types; meet halfway in the middle between erasing all type information and requiring a pedantic matching of type information and always allow a safe expression of the numeric value.

Using initializers for `Integer` or `FloatingPoint` protocol adopters on NSNumber was considered but was determined out of scope for this change and may be considered separately from the behavior of NSNumber bridging.


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. See accompanying LICENSE file.
 */
package com.lucidworks.security.authentication.client;

import java.io.IOException;
import java.net.HttpURLConnection;

/**
 * Interface to configure  {@link HttpURLConnection} created by
 * {@link AuthenticatedURL} instances.
 */
public interface ConnectionConfigurator {

  /**
   * Configures the given {@link HttpURLConnection} instance.
   *
   * @param conn the {@link HttpURLConnection} instance to configure.
   * @return the configured {@link HttpURLConnection} instance.
   *
   * @throws IOException if an IO error occurred.
   */
  public HttpURLConnection configure(HttpURLConnection conn) throws IOException;

}


text:
import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","delta5fpv","vtx" )
cursor = db.cursor()

try:
	cursor.execute("UPDATE `setup` SET `commsStatus` = 0")
	db.commit()
except MySQLdb.Error as e:
	print e
	db.rollback()
except MySQLdb.Warning as e:
	print e

db.close()


text:
const path = require('path');
const assert = require('assert');
const common = require('../../common.js');
const CommandGlobals = require('../../lib/globals/commands.js');
const MockServer = require('../../lib/mockserver.js');
const {settings} = common;
const {runTests} = common.require('index.js');

describe('testRunWithServerErrors', function() {

  before(function(done) {
    this.server = MockServer.init();

    this.server.on('listening', () => {
      done();
    });
  });

  after(function(done) {
    CommandGlobals.afterEach.call(this, done);
  });

  beforeEach(function() {
    process.removeAllListeners('exit');
    process.removeAllListeners('uncaughtException');
    process.removeAllListeners('unhandledRejection');
  });

  afterEach(function() {
    Object.keys(require.cache).filter(i => i.includes('/sampletests')).forEach(function(module) {
      delete require.cache[module];
    });
  });

  it('testRunner with 502 server errors', function() {
    MockServer.addMock({
      url: '/wd/hub/session/1352110219202/elements',
      postdata: {
        using: 'css selector',
        value: '#element-server-error'
      },
      statusCode: 502,
      contentType: 'text/html',
      response: '\n\n<title>502 Bad Gateway</title>\n\n\n'
    });

    let testsPath = path.join(__dirname, '../../sampletests/withservererrors');
    let globals = {
      calls: 0,
      retryAssertionTimeout: 150,
      waitForConditionTimeout: 150,
      waitForConditionPollInterval: 50,
      reporter(results, cb) {
        assert.strictEqual(results.errmessages.length, 4);
        assert.strictEqual(results.passed, 0);
        assert.strictEqual(results.failed, 3);
        assert.strictEqual(results.assertions, 3);
        assert.strictEqual(results.errors, 4);
        assert.strictEqual(results.skipped, 0);
        const {completed} = results.modules.sampleTestWithServerError;
        assert.ok(completed.demoTest.lastError.message.includes('502 Bad Gateway'), `Result: ${completed.demoTest.lastError.message}`);

        cb();
      }
    };

    return runTests({
      _source: [testsPath]
    }, settings({
      output: false,
      skip_testcases_on_fail: false,
      report_command_errors: true,
      disable_error_log: 0,
      globals
    }));
  });

});


text:
var searchData=
[
  ['squarebuildinlay',['SquareBuildInlay',['../class_square_build_inlay.html',1,'']]]
];


text:
FROM python:2.7.9
COPY requirements.txt /src/
RUN cd /src && pip install ipython && pip install -r requirements.txt
COPY main.py /src/
COPY worker/ /src/worker/
WORKDIR /src
CMD ["python", "main.py"]


text:
package com.google.cloud.bigtable.emulator.v2;

import com.google.api.core.BetaApi;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Path;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Wraps the Bigtable emulator in a java api.
 *
 * <p>This class will use the golang binaries embedded in this jar to launch the emulator as an
 * external process and redirect its output to a {@link Logger}.
 */
@BetaApi("Surface for Bigtable emulator is not yet stable")
public class Emulator {

  private static final Logger LOGGER = Logger.getLogger(Emulator.class.getName());

  private final Path executable;
  private Process process;
  private boolean isStopped = true;
  private Thread shutdownHook;

  private int port;
  private ManagedChannel dataChannel;
  private ManagedChannel adminChannel;

  /**
   * Create a new instance of emulator. The emulator will use the bundled binaries in this jar.
   * Please note that the emulator is created in a stopped state, please use {@link #start()} after
   * creating it.
   */
  public static Emulator createBundled() throws IOException {
    String resourcePath = getBundledResourcePath();

    File tmpEmulator = File.createTempFile("cbtemulator", "");
    tmpEmulator.deleteOnExit();

    try (InputStream is = Emulator.class.getResourceAsStream(resourcePath);
        FileOutputStream os = new FileOutputStream(tmpEmulator)) {

      if (is == null) {
        throw new FileNotFoundException(
            "Failed to find the bundled emulator binary: " + resourcePath);
      }

      byte[] buff = new byte[2048];
      int length;

      while ((length = is.read(buff)) != -1) {
        os.write(buff, 0, length);
      }
    }
    tmpEmulator.setExecutable(true);

    return new Emulator(tmpEmulator.toPath());
  }

  private Emulator(Path executable) {
    this.executable = executable;
  }

  /** Starts the emulator process and waits for it to be ready. */
  public synchronized void start() throws IOException, TimeoutException, InterruptedException {
    if (!isStopped) {
      throw new IllegalStateException("Emulator is already started");
    }
    this.port = getAvailablePort();

    process = Runtime.getRuntime().exec(String.format("%s -port %d", executable, port));
    pipeStreamToLog(process.getInputStream(), Level.INFO);
    pipeStreamToLog(process.getErrorStream(), Level.WARNING);
    isStopped = false;

    shutdownHook =
        new Thread() {
          @Override
          public void run() {
            if (!isStopped) {
              isStopped = true;
              process.destroy();
            }
          }
        };

    Runtime.getRuntime().addShutdownHook(shutdownHook);

    waitForPort(port);
  }

  /** Stops the emulator process. */
  public synchronized void stop() {
    if (isStopped) {
      throw new IllegalStateException("Emulator already stopped");
    }

    try {
      Runtime.getRuntime().removeShutdownHook(shutdownHook);
      shutdownHook = null;

      // Shutdown channels in parallel
      if (dataChannel != null) {
        dataChannel.shutdownNow();
      }
      if (adminChannel != null) {
        adminChannel.shutdownNow();
      }

      // Then wait for actual shutdown
      if (dataChannel != null) {
        dataChannel.awaitTermination(1, TimeUnit.MINUTES);
        dataChannel = null;
      }
      if (adminChannel != null) {
        adminChannel.awaitTermination(1, TimeUnit.MINUTES);
        adminChannel = null;
      }
    } catch (InterruptedException e) {
      LOGGER.warning("Interrupted while waiting for client channels to close");
      Thread.currentThread().interrupt();
    } finally {
      isStopped = true;
      process.destroy();
    }
  }

  public synchronized int getPort() {
    if (isStopped) {
      throw new IllegalStateException("Emulator is not running");
    }
    return port;
  }

  public synchronized ManagedChannel getDataChannel() {
    if (isStopped) {
      throw new IllegalStateException("Emulator is not running");
    }

    if (dataChannel == null) {
      dataChannel = newChannelBuilder(port).maxInboundMessageSize(256 * 1024 * 1024).build();
    }
    return dataChannel;
  }

  public synchronized ManagedChannel getAdminChannel() {
    if (isStopped) {
      throw new IllegalStateException("Emulator is not running");
    }

    if (adminChannel == null) {
      adminChannel = newChannelBuilder(port).build();
    }
    return adminChannel;
  }

  // <editor-fold desc="Helpers">

  /** Gets the current platform, which will be used to select the appropriate emulator binary. */
  private static String getBundledResourcePath() {
    String unformattedOs = System.getProperty("os.name", "unknown").toLowerCase(Locale.ENGLISH);
    String os;
    String suffix = "";

    if (unformattedOs.contains("mac") || unformattedOs.contains("darwin")) {
      os = "darwin";
    } else if (unformattedOs.contains("win")) {
      os = "windows";
      suffix = ".exe";
    } else if (unformattedOs.contains("linux")) {
      os = "linux";
    } else {
      throw new UnsupportedOperationException(
          "Emulator is not supported on your platform: " + unformattedOs);
    }

    String unformattedArch = System.getProperty("os.arch");
    String arch;

    switch (unformattedArch) {
      case "x86":
        arch = "x86";
        break;
      case "x86_64":
      case "amd64":
        arch = "x86_64";
        break;
      default:
        throw new UnsupportedOperationException("Unsupported architecture: " + unformattedArch);
    }

    return String.format(
        "/gcloud/bigtable-%s-%s/platform/bigtable-emulator/cbtemulator%s", os, arch, suffix);
  }

  /** Gets a random open port number. */
  private static int getAvailablePort() {
    try (ServerSocket serverSocket = new ServerSocket(0)) {
      return serverSocket.getLocalPort();
    } catch (IOException e) {
      throw new RuntimeException("Failed to find open port");
    }
  }

  /** Waits for a port to open. It's used to wait for the emulator's gRPC server to be ready. */
  private static void waitForPort(int port) throws InterruptedException, TimeoutException {
    for (int i = 0; i < 100; i++) {
      try (Socket ignored = new Socket("localhost", port)) {
        return;
      } catch (IOException e) {
        Thread.sleep(200);
      }
    }

    throw new TimeoutException("Timed out waiting for server to start");
  }

  /** Creates a {@link io.grpc.ManagedChannelBuilder} preconfigured for the emulator's port. */
  private static ManagedChannelBuilder<?> newChannelBuilder(int port) {
    // NOTE: usePlaintext is currently @ExperimentalAPI.
    // See https://github.com/grpc/grpc-java/issues/1772 for discussion
    return ManagedChannelBuilder.forAddress("localhost", port).usePlaintext();
  }

  /** Creates a thread that will pipe an {@link java.io.InputStream} to this class' Logger. */
  private static void pipeStreamToLog(final InputStream stream, final Level level) {
    final BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

    Thread thread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  String line;
                  while ((line = reader.readLine()) != null) {
                    LOGGER.log(level, line);
                  }
                } catch (IOException e) {
                  if (!"Stream closed".equals(e.getMessage())) {
                    LOGGER.log(Level.WARNING, "Failed to read process stream", e);
                  }
                }
              }
            });
    thread.setDaemon(true);
    thread.start();
  }
  // </editor-fold>
}


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */

package test.fixtures.empty_struct;

import com.facebook.swift.codec.*;
import com.facebook.swift.codec.ThriftField.Requiredness;
import com.facebook.swift.codec.ThriftField.Recursiveness;
import java.util.*;

import static com.google.common.base.MoreObjects.toStringHelper;

@ThriftUnion("Nada")
public final class Nada
{
    private final Object value;
    private final int id;
    private final String name;

    @ThriftUnionId
    public int getThriftId()
    {
        return this.id;
    }

    public String getThriftName()
    {
        return this.name;
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
            .add("value", value)
            .add("id", id)
            .add("name", name)
            .add("type", value == null ? "<null>" : value.getClass().getSimpleName())
            .toString();
    }
}


text:
import sys, getopt

sys.path.insert(0, '/home/tzeng/caffe_3d/python')
sys.path.insert(0,'/home/tzeng/autoGenelable_multi_lables_proj/code/py-leveldb-read-only/build/lib.linux-x86_64-2.7')

import numpy as np
import hdf5storage
import leveldb
from leveldb import WriteBatch, LevelDB
import os
import imp
#import caffe
#sys.path.append('/home/tzeng/caffe_3d/python/caffe')
#foo = imp.load_source('caffe.io', '/home/tzeng/caffe_3d/python/caffe/__init__.py')
import caffe.io
from caffe.proto import caffe_pb2
print os.path.dirname(caffe_pb2.__file__)

db_path_data='/home/tzeng/caffe_3d/data/test'
db_data=leveldb.LevelDB(db_path_data)
datum = caffe_pb2.Datum()
mat_file='/home/tzeng/caffe_3d/data/test_out.mat'

window_num=0
for key in db_data.RangeIter(include_value = False):
  window_num=window_num+1

print window_num
n=0
# for key,value in db_data.RangeIter():
		# n=n+1
		# #f_size=len(value)
		# datum.ParseFromString(value)
		# f_size=len(datum.float_data)
		# if n>0:
		   # break

ft = np.zeros((1, 27))
lb = np.zeros((1, 27))
count=0
for key,value in db_data.RangeIter():
     datum.ParseFromString(value);
     #ft[count, :]=datum.data.tostring()
     lb[count,:]=datum.float_label
     count=count+1
print ft
data = {u'feat_label' : {
			u'feat' : ft,
			u'label' : lb,
		 }
	}

print 'save result to : %s' %(mat_file)
hdf5storage.savemat(mat_file,data, format='7.3')


text:
import uuid
from unittest.mock import patch
from xml.etree.ElementTree import XML

from django.test import SimpleTestCase, TestCase

from dimagi.utils.parsing import json_format_datetime

from corehq.apps.app_manager.tests.app_factory import AppFactory
from corehq.apps.app_manager.xform_builder import XFormBuilder
from corehq.apps.formplayer_api.smsforms.api import (
    FormplayerInterface,
    InvalidSessionIdException,
    TouchformsError,
    XformsResponse,
)
from corehq.apps.formplayer_api.smsforms.sms import SessionStartInfo
from corehq.apps.smsforms.app import (
    _clean_xml_for_partial_submission,
    _fetch_xml,
    start_session,
)
from corehq.apps.smsforms.models import SQLXFormsSession
from corehq.apps.users.models import WebUser
from corehq.form_processor.models import CommCareCase
from corehq.messaging.scheduling.util import utcnow

@patch('corehq.apps.smsforms.app.tfsms.start_session')
class TestStartSession(TestCase):
    domain = "test-domain"

    @classmethod
    def setUpClass(cls):
        cls.factory = AppFactory(domain=cls.domain)
        cls.app = cls.factory.app
        cls.module, cls.basic_form = cls.factory.new_basic_module('basic', 'patient')

        # necessary to render_xform
        builder = XFormBuilder(cls.basic_form.name)
        builder.new_question(name='name', label='Name')
        cls.basic_form.source = builder.tostring(pretty_print=True).decode('utf-8')

        cls.phone_number = "+919999999999"
        cls.case_id = uuid.uuid4().hex
        cls.recipient = None

        cls.case = CommCareCase(domain=cls.domain, case_id=cls.case_id, case_json={'language_code': 'fr'})
        cls.web_user = WebUser(username='web-user@example.com', _id=uuid.uuid4().hex, language='hin')

    @classmethod
    def tearDownClass(cls):
        SQLXFormsSession.objects.all().delete()

    def _start_session(self, yield_responses=False):
        if not self.recipient:
            raise Exception("Set recipient")
        return start_session(
            SQLXFormsSession.create_session_object(
                self.domain,
                self.recipient,
                self.phone_number,
                self.app,
                self.basic_form,
            ),
            self.domain,
            self.recipient,
            self.app,
            self.basic_form,
            yield_responses=yield_responses
        )

    def _mock_xform_response(self, tfsms_start_session_mock, status, additional_response=None):
        response_dict = {
            'session_id': uuid.uuid4().hex,
            'status': status
        }
        if additional_response:
            response_dict.update(additional_response)
        xform_response = XformsResponse(response_dict)
        tfsms_start_session_mock.return_value = SessionStartInfo(
            xform_response,
            self.domain
        )
        return xform_response

    @patch('corehq.apps.smsforms.app.XFormsConfig')
    def test_start_session_as_case(self, xform_config_mock, tfsms_start_session_mock):
        self.recipient = self.case

        event_response = {'output': 'result', 'type': 'question'}  # move to next question
        xform_response = self._mock_xform_response(tfsms_start_session_mock, status='success',
                                                   additional_response={'event': event_response})

        session, responses = self._start_session(yield_responses=True)

        expected_session_data = {
            'device_id': 'commconnect', 'app_version': self.app.version, 'domain': self.domain,
            'username': self.recipient.raw_username, 'user_id': self.recipient.get_id,
            'user_data': {},
            'app_id': None
        }
        xform_config_mock.assert_called_once_with(
            form_content=self.basic_form.render_xform().decode('utf-8'),
            language=self.recipient.get_language_code(),
            session_data=expected_session_data,
            domain=self.domain,
            restore_as_case_id=self.recipient.case_id
        )

        self.assertEqual(session.session_id, xform_response.session_id)
        self.assertEqual(len(responses), 1)
        self.assertEqual(responses[0], xform_response)

    @patch('corehq.apps.smsforms.app.XFormsConfig')
    def test_start_session_as_user(self, xform_config_mock, tfsms_start_session_mock):
        self.recipient = self.web_user

        xform_response = self._mock_xform_response(tfsms_start_session_mock, status="validation-error")

        session, responses = self._start_session(yield_responses=True)

        expected_session_data = {
            'device_id': 'commconnect', 'app_version': self.app.version, 'domain': self.domain,
            'username': self.recipient.raw_username, 'user_id': self.recipient.get_id,
            'user_data': {
                'commcare_first_name': None,
                'commcare_last_name': None,
                'commcare_phone_number': None,
                'commcare_project': self.domain,
            },
            'app_id': None
        }
        xform_config_mock.assert_called_once_with(
            form_content=self.basic_form.render_xform().decode('utf-8'),
            language=self.recipient.get_language_code(),
            session_data=expected_session_data,
            domain=self.domain,
            restore_as=self.recipient.raw_username
        )

        self.assertEqual(session.session_id, xform_response.session_id)
        self.assertEqual(len(responses), 1)
        self.assertEqual(responses[0], xform_response)

    def test_http_error(self, tfsms_start_session_mock):
        self.recipient = self.case

        xform_response = self._mock_xform_response(tfsms_start_session_mock, status='http-error')

        with self.assertRaisesMessage(TouchformsError, 'Cannot connect to touchforms.'):
            self._start_session()

        session = SQLXFormsSession.objects.first()
        self.assertFalse(session.completed)
        self.assertEqual(session.session_id, xform_response.session_id)

    def test_text_responses(self, tfsms_start_session_mock):
        self.recipient = self.case

        self._mock_xform_response(tfsms_start_session_mock, status="validation-error",
                                  additional_response={'reason': 'human-error'})

        session, responses = self._start_session(yield_responses=False)

        self.assertEqual(responses, ["human-error"])

class TestFetchXml(TestCase):

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.session = SQLXFormsSession(session_id='abc123', domain='test-domain', user_id='user_id')
        cls.formplayer_interface = FormplayerInterface(cls.session.session_id, cls.session.domain)

    def setUp(self) -> None:
        super().setUp()
        patcher = patch.object(self.formplayer_interface, 'get_raw_instance')
        self.mock_get_raw_instance = patcher.start()
        self.addCleanup(patcher.stop)

    def test_successful_response(self):
        expected_result = '<data><question>answer</question></data>'

        self.mock_get_raw_instance.return_value = {'status': 'success', 'output': expected_result}
        result = _fetch_xml(self.formplayer_interface)
        self.assertEqual(result, expected_result)

    def test_raises_exception_if_invalid_session_id(self):
        self.mock_get_raw_instance.side_effect = InvalidSessionIdException
        with self.assertRaises(InvalidSessionIdException):
            _fetch_xml(self.formplayer_interface)

    def test_raises_touchforms_error_if_response_errors(self):
        self.mock_get_raw_instance.return_value = {'status': 'error'}
        with self.assertRaises(TouchformsError):
            _fetch_xml(self.formplayer_interface)

class TestCleanXMLForPartialSubmission(SimpleTestCase):

    def test_timeEnd_value_is_set(self):
        xml_with_case_action = '''
        <data>
            <question>answer</question>
            <meta>
                <timeEnd/>
            </meta>
        </data>
        '''.strip()

        now = utcnow()
        expected_time_end = json_format_datetime(now)
        with patch('corehq.apps.smsforms.app.utcnow', return_value=now):
            cleaned_xml = _clean_xml_for_partial_submission(xml_with_case_action, should_remove_case_actions=True)

        xml = XML(cleaned_xml)
        self.assertEqual(xml.find('meta').find('timeEnd').text, expected_time_end)

    def test_case_actions_are_not_removed_when_false(self):
        xml_with_case_create = '''
                <data>
                    <question>answer</question>
                    <case>
                        <create></create>
                        <update></update>
                        <close></close>
                    </case>
                </data>
                '''.strip()

        cleaned_xml = _clean_xml_for_partial_submission(xml_with_case_create, should_remove_case_actions=False)
        xml = XML(cleaned_xml)
        self.assertIsNotNone(xml.find('case'))
        self.assertIsNotNone(xml.find('case').find('create'))
        self.assertIsNotNone(xml.find('case').find('update'))
        self.assertIsNotNone(xml.find('case').find('close'))

    def test_case_actions_are_removed_when_true(self):
        xml_with_case_create = '''
                <data>
                    <question>answer</question>
                    <case>
                        <create></create>
                        <update></update>
                        <close></close>
                    </case>
                </data>
                '''.strip()

        cleaned_xml = _clean_xml_for_partial_submission(xml_with_case_create, should_remove_case_actions=True)
        xml = XML(cleaned_xml)
        self.assertIsNotNone(xml.find('case'))
        self.assertIsNone(xml.find('case').find('create'))
        self.assertIsNone(xml.find('case').find('update'))
        self.assertIsNone(xml.find('case').find('close'))


text:
<fieldset>

       Title

          <input type="text" class="form-control" ng-model="data.title">
          Hopefully, it was purchased wisely

 </fieldset>


text:
Demonstrate how to implement the Line Transformation API in Visual Studio.

* Technologies: Visual Studio 2015 SDK
* Topics: Visual Studio Editor, VSX

**Description**

This sample extension for Visual Studio 2015 modifies the text editor using
the Line Transformation API. The extension visually scales lines so that they
gradually appear smaller as they get farther away from the text caret.

![image](./C%23/Example.CaretFishEye.png)

**Requirements**

[ Visual Studio 2015 ](https://www.visualstudio.com/products/visual-studio-community-vs?wt.mc_id=o~display~github~vssdk)

**Get all samples**

Clone the repo ([How to](https://git-scm.com/book/en/v2/Git-Basics-Getting-a-Git-Repository#Cloning-an-Existing-Repository)):

`git clone https://github.com/Microsoft/VSSDK-Extensibility-Samples.git`

**Run the sample**

  1. To run the sample, hit **F5** or choose the **Debug > Start Debugging** menu command. A new experimental instance of Visual Studio will launch.
  2. Once loaded, open any file in the **Text Editor**
  3. Move the text caret around the screen
  4. Compare the text size of the line that the caret is currently on to the size of surrounding lines

**Project Files**

* **AssemblyInfo.cs**

This file contains assembly custom attributes.

* **CaretFisheyeLineTransformSource.cs**

This class derives from ILineTransformSource, and implements all of the
functionality of Caret Fish Eye

* **CaretFisheyeLineTransformSourceProvider.cs**

This class a connector that produces the CaretFisheye
LineTransformSourceProvider

**Functional Tests**

  * Verify the sample builds in all configurations
  * Verify that the sample was registered. The About box should list the product as installed
  * Verify that lines visually change in size as the caret is moved about the screen

**Related topics**

  * [ Editor Documentation ](https://msdn.microsoft.com/en-us/library/dd885118(v=vs.140).aspx)
  * [ Visual Studio SDK Documentation ](https://msdn.microsoft.com/en-us/library/bb166441(v=vs.140).aspx)


text:
require 'uri'

module ApplicationHelper
  def show_avatar
    avatar = current_user.profile.avatar.present? ? current_user.profile.avatar : "https://assets.github.com/images/gravatars/gravatar-140.png"
    image_tag(avatar, class: 'avatar')
  end

  def markdown(text)
    unless text.nil?
      options = { autolink: true, highlight: true, fenced_code_blocks: true }
      renderer = Redcarpet::Render::HTML.new(hard_wrap: true)
      markdown = Redcarpet::Markdown.new(renderer, options)
      markdown.render(text).html_safe
    end
  end

  def body(&block)
    content = capture(&block)
    content_tag(:body, content, controller: params[:controller].gsub('/', ' ').titleize.gsub(' ', '.'),
      action: action_name.capitalize)
  end

  def parse_youtube(url)
    regex = /(?:.be\/|\/watch\?v=|\/(?=p\/))([\w\/\-]+)/
    url.match(regex)[1]
  end

  def youtube_image_preview(url)
    id = parse_youtube(url)
    "http://img.youtube.com/vi/#{id}/0.jpg"
  end
end


text:
PYTHON_REQUIREMENTS=""
APT_REQUIREMENTS=""

APT_PACKAGES=(
    asciidoctor
    bazel
    bazel-5.1.1
    bison
    build-essential
    ccache
    clang
    clang-format
    cmake
    cmake-curses-gui
    cpio
    curl
    device-tree-compiler
    doxygen
    flex
    fzf
    gdb
    git
    gtk-sharp2
    graphviz
    haskell-stack
    lcov
    libcanberra-gtk-module
    libclang-dev
    libcunit1-dev
    libc6-dev
    libtool
    llvm-13-tools
    gcc
    g++
    gcc-11
    g++-11
    libftdi1
    libftdi1-dev
    libfl2
    libfl-dev
    libglib2.0-dev
    libglib2.0-dev-bin
    libgtk2.0-0
    libpixman-1-dev
    libpython3-dev
    libsqlite3-dev
    libssl-dev
    libtinfo-dev
    libtinfo5
    libwww-perl
    libxml2-dev
    libxml2-utils
    libxslt-dev
    libzmq5
    lrzsz
    mono-complete
    ncurses-dev
    ninja-build
    perl
    protobuf-compiler
    pv
    python-is-python3
    python3-protobuf
    python3
    python3-dev
    python3-pip
    rsync
    srecord
    texinfo
    texlive-bibtex-extra
    texlive-fonts-recommended
    texlive-latex-extra
    texlive-metapost
    u-boot-tools
    uml-utilities
    policykit-1
    screen
    wget
    xxd
    zlib1g
    zlib1g-dev
)

function die {
    [[ ! -z "$@" ]] && echo "$@"
    exit 1
}

function try {
    "$@" || die
}

function sudo_try {
    echo "sudo $@"
    sudo "$@" || die
}

function try_install_apt_packages {
    sudo_try apt-get update
    sudo_try apt-get install -y "${APT_PACKAGES[@]}"

    if [[ ! -z "${APT_REQUIREMENTS}" ]]; then
        sed 's/#.*//' "${APT_REQUIREMENTS}" | sudo_try xargs apt-get install -y
    fi
}

function try_install_python_packages {
    local package
    if [[ ! -z ${PYTHON_REQUIREMENTS} ]]; then
        PIP_INSTALL_ARGS=""
        for REQ_FILE in ${PYTHON_REQUIREMENTS} ; do
            PIP_INSTALL_ARGS="${PIP_INSTALL_ARGS} -r ${REQ_FILE}"
        done
        pip3 install ${PIP_INSTALL_ARGS}
    fi
}

function main {
    local usage="Usage: install-prereqs.sh [-p python-requirements.txt] [-a apt-requirements.txt]"
    local args=$(getopt -o hp:a: \
                        --long help,python:,apt: \
                        -n install-prereqs.sh -- "$@")
    eval set -- "$args"

    while true; do
        case "$1" in
            -h|--help)
                echo $usage
                return 1
                ;;

            -p|--python)
                PYTHON_REQUIREMENTS="$2"
                shift 2
                ;;

            -a|--apt)
                APT_REQUIREMENTS="$2"
                shift 2
                ;;

            --)
                shift
                break
                ;;
        esac
    done

    echo "Installing apt package dependencies..."
    try_install_apt_packages

    echo "Installing python package dependencies..."
    try_install_python_packages

    echo "Installation complete."
}

main "$@"


text:
<?xml version="1.0" encoding="utf-8" ?>
<INTERACTIONS>
<INTERACTION>
<SOURCE>
<CLINICAL_SOURCE>ANSM</CLINICAL_SOURCE>
<SOURCE_FILE>524-NICOTINE-SUBSTITUTION-TREATMENT.html
</SOURCE_FILE>
</SOURCE>
<DRUG1>
<CLASS name="NICOTINE SUBSTITUION TREATMENT" code="N07BA" /></DRUG1>
<DRUG2>
<CLASS name="MEDICATIONS AT RISK WHEN WITHDRAWING FROM TOBACCO" code="N0-R0-002" /></DRUG2>
<DESCRIPTION>Risk of overdose when replacing tobacco by the substitution treatment</DESCRIPTION>
<SEVERITY>Take into account</SEVERITY>
</INTERACTION>
</INTERACTIONS>


text:
package compactext4

import (
	"bufio"
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"path"
	"sort"
	"strings"
	"time"

	"github.com/Microsoft/hcsshim/ext4/internal/format"
)

// Writer writes a compact ext4 file system.
type Writer struct {
	f                    io.ReadWriteSeeker
	bw                   *bufio.Writer
	inodes               []*inode
	curName              string
	curInode             *inode
	pos                  int64
	dataWritten, dataMax int64
	err                  error
	initialized          bool
	supportInlineData    bool
	maxDiskSize          int64
	gdBlocks             uint32
}

// Mode flags for Linux files.
const (
	S_IXOTH  = format.S_IXOTH
	S_IWOTH  = format.S_IWOTH
	S_IROTH  = format.S_IROTH
	S_IXGRP  = format.S_IXGRP
	S_IWGRP  = format.S_IWGRP
	S_IRGRP  = format.S_IRGRP
	S_IXUSR  = format.S_IXUSR
	S_IWUSR  = format.S_IWUSR
	S_IRUSR  = format.S_IRUSR
	S_ISVTX  = format.S_ISVTX
	S_ISGID  = format.S_ISGID
	S_ISUID  = format.S_ISUID
	S_IFIFO  = format.S_IFIFO
	S_IFCHR  = format.S_IFCHR
	S_IFDIR  = format.S_IFDIR
	S_IFBLK  = format.S_IFBLK
	S_IFREG  = format.S_IFREG
	S_IFLNK  = format.S_IFLNK
	S_IFSOCK = format.S_IFSOCK

	TypeMask = format.TypeMask
)

type inode struct {
	Size                        int64
	Atime, Ctime, Mtime, Crtime uint64
	Number                      format.InodeNumber
	Mode                        uint16
	Uid, Gid                    uint32
	LinkCount                   uint32
	XattrBlock                  uint32
	BlockCount                  uint32
	Devmajor, Devminor          uint32
	Flags                       format.InodeFlag
	Data                        []byte
	XattrInline                 []byte
	Children                    directory
}

func (node *inode) FileType() uint16 {
	return node.Mode & format.TypeMask
}

func (node *inode) IsDir() bool {
	return node.FileType() == S_IFDIR
}

// A File represents a file to be added to an ext4 file system.
type File struct {
	Linkname                    string
	Size                        int64
	Mode                        uint16
	Uid, Gid                    uint32
	Atime, Ctime, Mtime, Crtime time.Time
	Devmajor, Devminor          uint32
	Xattrs                      map[string][]byte
}

const (
	inodeFirst        = 11
	inodeLostAndFound = inodeFirst

	BlockSize               = 4096
	blocksPerGroup          = BlockSize * 8
	inodeSize               = 256
	maxInodesPerGroup       = BlockSize * 8 // Limited by the inode bitmap
	inodesPerGroupIncrement = BlockSize / inodeSize

	defaultMaxDiskSize = 16 * 1024 * 1024 * 1024        // 16GB
	maxMaxDiskSize     = 16 * 1024 * 1024 * 1024 * 1024 // 16TB

	groupDescriptorSize      = 32 // Use the small group descriptor
	groupsPerDescriptorBlock = BlockSize / groupDescriptorSize

	maxFileSize             = 128 * 1024 * 1024 * 1024 // 128GB file size maximum for now
	smallSymlinkSize        = 59                       // max symlink size that goes directly in the inode
	maxBlocksPerExtent      = 0x8000                   // maximum number of blocks in an extent
	inodeDataSize           = 60
	inodeUsedSize           = 152 // fields through CrtimeExtra
	inodeExtraSize          = inodeSize - inodeUsedSize
	xattrInodeOverhead      = 4 + 4                       // magic number + empty next entry value
	xattrBlockOverhead      = 32 + 4                      // header + empty next entry value
	inlineDataXattrOverhead = xattrInodeOverhead + 16 + 4 // entry + "data"
	inlineDataSize          = inodeDataSize + inodeExtraSize - inlineDataXattrOverhead
)

type exceededMaxSizeError struct {
	Size int64
}

func (err exceededMaxSizeError) Error() string {
	return fmt.Sprintf("disk exceeded maximum size of %d bytes", err.Size)
}

var directoryEntrySize = binary.Size(format.DirectoryEntry{})
var extraIsize = uint16(inodeUsedSize - 128)

type directory map[string]*inode

func splitFirst(p string) (string, string) {
	n := strings.IndexByte(p, '/')
	if n >= 0 {
		return p[:n], p[n+1:]
	}
	return p, ""
}

func (w *Writer) findPath(root *inode, p string) *inode {
	inode := root
	for inode != nil && len(p) != 0 {
		name, rest := splitFirst(p)
		p = rest
		inode = inode.Children[name]
	}
	return inode
}

func timeToFsTime(t time.Time) uint64 {
	if t.IsZero() {
		return 0
	}
	s := t.Unix()
	if s < -0x80000000 {
		return 0x80000000
	}
	if s > 0x37fffffff {
		return 0x37fffffff
	}
	return uint64(s) | uint64(t.Nanosecond())<<34
}

func fsTimeToTime(t uint64) time.Time {
	if t == 0 {
		return time.Time{}
	}
	s := int64(t & 0x3ffffffff)
	if s > 0x7fffffff && s < 0x100000000 {
		s = int64(int32(uint32(s)))
	}
	return time.Unix(s, int64(t>>34))
}

func (w *Writer) getInode(i format.InodeNumber) *inode {
	if i == 0 || int(i) > len(w.inodes) {
		return nil
	}
	return w.inodes[i-1]
}

var xattrPrefixes = []struct {
	Index  uint8
	Prefix string
}{
	{2, "system.posix_acl_access"},
	{3, "system.posix_acl_default"},
	{8, "system.richacl"},
	{7, "system."},
	{1, "user."},
	{4, "trusted."},
	{6, "security."},
}

func compressXattrName(name string) (uint8, string) {
	for _, p := range xattrPrefixes {
		if strings.HasPrefix(name, p.Prefix) {
			return p.Index, name[len(p.Prefix):]
		}
	}
	return 0, name
}

func decompressXattrName(index uint8, name string) string {
	for _, p := range xattrPrefixes {
		if index == p.Index {
			return p.Prefix + name
		}
	}
	return name
}

func hashXattrEntry(name string, value []byte) uint32 {
	var hash uint32
	for i := 0; i < len(name); i++ {
		hash = (hash << 5) ^ (hash >> 27) ^ uint32(name[i])
	}

	for i := 0; i+3 < len(value); i += 4 {
		hash = (hash << 16) ^ (hash >> 16) ^ binary.LittleEndian.Uint32(value[i:i+4])
	}

	if len(value)%4 != 0 {
		var last [4]byte
		copy(last[:], value[len(value)&^3:])
		hash = (hash << 16) ^ (hash >> 16) ^ binary.LittleEndian.Uint32(last[:])
	}
	return hash
}

type xattr struct {
	Name  string
	Index uint8
	Value []byte
}

func (x *xattr) EntryLen() int {
	return (len(x.Name)+3)&^3 + 16
}

func (x *xattr) ValueLen() int {
	return (len(x.Value) + 3) &^ 3
}

type xattrState struct {
	inode, block         []xattr
	inodeLeft, blockLeft int
}

func (s *xattrState) init() {
	s.inodeLeft = inodeExtraSize - xattrInodeOverhead
	s.blockLeft = BlockSize - xattrBlockOverhead
}

func (s *xattrState) addXattr(name string, value []byte) bool {
	index, name := compressXattrName(name)
	x := xattr{
		Index: index,
		Name:  name,
		Value: value,
	}
	length := x.EntryLen() + x.ValueLen()
	if s.inodeLeft >= length {
		s.inode = append(s.inode, x)
		s.inodeLeft -= length
	} else if s.blockLeft >= length {
		s.block = append(s.block, x)
		s.blockLeft -= length
	} else {
		return false
	}
	return true
}

func putXattrs(xattrs []xattr, b []byte, offsetDelta uint16) {
	offset := uint16(len(b)) + offsetDelta
	eb := b
	db := b
	for _, xattr := range xattrs {
		vl := xattr.ValueLen()
		offset -= uint16(vl)
		eb[0] = uint8(len(xattr.Name))
		eb[1] = xattr.Index
		binary.LittleEndian.PutUint16(eb[2:], offset)
		binary.LittleEndian.PutUint32(eb[8:], uint32(len(xattr.Value)))
		binary.LittleEndian.PutUint32(eb[12:], hashXattrEntry(xattr.Name, xattr.Value))
		copy(eb[16:], xattr.Name)
		eb = eb[xattr.EntryLen():]
		copy(db[len(db)-vl:], xattr.Value)
		db = db[:len(db)-vl]
	}
}

func getXattrs(b []byte, xattrs map[string][]byte, offsetDelta uint16) {
	eb := b
	for len(eb) != 0 {
		nameLen := eb[0]
		if nameLen == 0 {
			break
		}
		index := eb[1]
		offset := binary.LittleEndian.Uint16(eb[2:]) - offsetDelta
		valueLen := binary.LittleEndian.Uint32(eb[8:])
		attr := xattr{
			Index: index,
			Name:  string(eb[16 : 16+nameLen]),
			Value: b[offset : uint32(offset)+valueLen],
		}
		xattrs[decompressXattrName(index, attr.Name)] = attr.Value
		eb = eb[attr.EntryLen():]
	}
}

func (w *Writer) writeXattrs(inode *inode, state *xattrState) error {
	// Write the inline attributes.
	if len(state.inode) != 0 {
		inode.XattrInline = make([]byte, inodeExtraSize)
		binary.LittleEndian.PutUint32(inode.XattrInline[0:], format.XAttrHeaderMagic) // Magic
		putXattrs(state.inode, inode.XattrInline[4:], 0)
	}

	// Write the block attributes. If there was previously an xattr block, then
	// rewrite it even if it is now empty.
	if len(state.block) != 0 || inode.XattrBlock != 0 {
		sort.Slice(state.block, func(i, j int) bool {
			return state.block[i].Index < state.block[j].Index ||
				len(state.block[i].Name) < len(state.block[j].Name) ||
				state.block[i].Name < state.block[j].Name
		})

		var b [BlockSize]byte
		binary.LittleEndian.PutUint32(b[0:], format.XAttrHeaderMagic) // Magic
		binary.LittleEndian.PutUint32(b[4:], 1)                       // ReferenceCount
		binary.LittleEndian.PutUint32(b[8:], 1)                       // Blocks
		putXattrs(state.block, b[32:], 32)

		orig := w.block()
		if inode.XattrBlock == 0 {
			inode.XattrBlock = orig
			inode.BlockCount++
		} else {
			// Reuse the original block.
			w.seekBlock(inode.XattrBlock)
			defer w.seekBlock(orig)
		}

		if _, err := w.write(b[:]); err != nil {
			return err
		}
	}

	return nil
}

func (w *Writer) write(b []byte) (int, error) {
	if w.err != nil {
		return 0, w.err
	}
	if w.pos+int64(len(b)) > w.maxDiskSize {
		w.err = exceededMaxSizeError{w.maxDiskSize}
		return 0, w.err
	}
	n, err := w.bw.Write(b)
	w.pos += int64(n)
	w.err = err
	return n, err
}

func (w *Writer) zero(n int64) (int64, error) {
	if w.err != nil {
		return 0, w.err
	}
	if w.pos+int64(n) > w.maxDiskSize {
		w.err = exceededMaxSizeError{w.maxDiskSize}
		return 0, w.err
	}
	n, err := io.CopyN(w.bw, zero, n)
	w.pos += n
	w.err = err
	return n, err
}

func (w *Writer) makeInode(f *File, node *inode) (*inode, error) {
	mode := f.Mode
	if mode&format.TypeMask == 0 {
		mode |= format.S_IFREG
	}
	typ := mode & format.TypeMask
	ino := format.InodeNumber(len(w.inodes) + 1)
	if node == nil {
		node = &inode{
			Number: ino,
		}
		if typ == S_IFDIR {
			node.Children = make(directory)
			node.LinkCount = 1 // A directory is linked to itself.
		}
	} else if node.Flags&format.InodeFlagExtents != 0 {
		// Since we cannot deallocate or reuse blocks, don't allow updates that
		// would invalidate data that has already been written.
		return nil, errors.New("cannot overwrite file with non-inline data")
	}
	node.Mode = mode
	node.Uid = f.Uid
	node.Gid = f.Gid
	node.Flags = format.InodeFlagHugeFile
	node.Atime = timeToFsTime(f.Atime)
	node.Ctime = timeToFsTime(f.Ctime)
	node.Mtime = timeToFsTime(f.Mtime)
	node.Crtime = timeToFsTime(f.Crtime)
	node.Devmajor = f.Devmajor
	node.Devminor = f.Devminor
	node.Data = nil
	node.XattrInline = nil

	var xstate xattrState
	xstate.init()

	var size int64
	switch typ {
	case format.S_IFREG:
		size = f.Size
		if f.Size > maxFileSize {
			return nil, fmt.Errorf("file too big: %d > %d", f.Size, int64(maxFileSize))
		}
		if f.Size <= inlineDataSize && w.supportInlineData {
			node.Data = make([]byte, f.Size)
			extra := 0
			if f.Size > inodeDataSize {
				extra = int(f.Size - inodeDataSize)
			}
			// Add a dummy entry for now.
			if !xstate.addXattr("system.data", node.Data[:extra]) {
				panic("not enough room for inline data")
			}
			node.Flags |= format.InodeFlagInlineData
		}
	case format.S_IFLNK:
		node.Mode |= 0777 // Symlinks should appear as ugw rwx
		size = int64(len(f.Linkname))
		if size <= smallSymlinkSize {
			// Special case: small symlinks go directly in Block without setting
			// an inline data flag.
			node.Data = make([]byte, len(f.Linkname))
			copy(node.Data, f.Linkname)
		}
	case format.S_IFDIR, format.S_IFIFO, format.S_IFSOCK, format.S_IFCHR, format.S_IFBLK:
	default:
		return nil, fmt.Errorf("invalid mode %o", mode)
	}

	// Accumulate the extended attributes.
	if len(f.Xattrs) != 0 {
		// Sort the xattrs to avoid non-determinism in map iteration.
		var xattrs []string
		for name := range f.Xattrs {
			xattrs = append(xattrs, name)
		}
		sort.Strings(xattrs)
		for _, name := range xattrs {
			if !xstate.addXattr(name, f.Xattrs[name]) {
				return nil, fmt.Errorf("could not fit xattr %s", name)
			}
		}
	}

	if err := w.writeXattrs(node, &xstate); err != nil {
		return nil, err
	}

	node.Size = size
	if typ == format.S_IFLNK && size > smallSymlinkSize {
		// Write the link name as data.
		w.startInode("", node, size)
		if _, err := w.Write([]byte(f.Linkname)); err != nil {
			return nil, err
		}
		if err := w.finishInode(); err != nil {
			return nil, err
		}
	}

	if int(node.Number-1) >= len(w.inodes) {
		w.inodes = append(w.inodes, node)
	}
	return node, nil
}

func (w *Writer) root() *inode {
	return w.getInode(format.InodeRoot)
}

func (w *Writer) lookup(name string, mustExist bool) (*inode, *inode, string, error) {
	root := w.root()
	cleanname := path.Clean("/" + name)[1:]
	if len(cleanname) == 0 {
		return root, root, "", nil
	}
	dirname, childname := path.Split(cleanname)
	if len(childname) == 0 || len(childname) > 0xff {
		return nil, nil, "", fmt.Errorf("%s: invalid name", name)
	}
	dir := w.findPath(root, dirname)
	if dir == nil || !dir.IsDir() {
		return nil, nil, "", fmt.Errorf("%s: path not found", name)
	}
	child := dir.Children[childname]
	if child == nil && mustExist {
		return nil, nil, "", fmt.Errorf("%s: file not found", name)
	}
	return dir, child, childname, nil
}

// CreateWithParents adds a file to the file system creating the parent directories in the path if
// they don't exist (like `mkdir -p`). These non existing parent directories are created
// with the same permissions as that of it's parent directory. It is expected that the a
// call to make these parent directories will be made at a later point with the correct
// permissions, at that time the permissions of these directories will be updated.
func (w *Writer) CreateWithParents(name string, f *File) error {
	if err := w.finishInode(); err != nil {
		return err
	}
	// go through the directories in the path one by one and create the
	// parent directories if they don't exist.
	cleanname := path.Clean("/" + name)[1:]
	parentDirs, _ := path.Split(cleanname)
	currentPath := ""
	root := w.root()
	dirname := ""
	for parentDirs != "" {
		dirname, parentDirs = splitFirst(parentDirs)
		currentPath += "/" + dirname
		if _, ok := root.Children[dirname]; !ok {
			f := &File{
				Mode:     root.Mode,
				Atime:    time.Now(),
				Mtime:    time.Now(),
				Ctime:    time.Now(),
				Crtime:   time.Now(),
				Size:     0,
				Uid:      root.Uid,
				Gid:      root.Gid,
				Devmajor: root.Devmajor,
				Devminor: root.Devminor,
				Xattrs:   make(map[string][]byte),
			}
			if err := w.Create(currentPath, f); err != nil {
				return fmt.Errorf("failed while creating parent directories: %w", err)
			}
		}
		root = root.Children[dirname]
	}
	return w.Create(name, f)
}

// Create adds a file to the file system.
func (w *Writer) Create(name string, f *File) error {
	if err := w.finishInode(); err != nil {
		return err
	}
	dir, existing, childname, err := w.lookup(name, false)
	if err != nil {
		return err
	}
	var reuse *inode
	if existing != nil {
		if existing.IsDir() {
			if f.Mode&TypeMask != S_IFDIR {
				return fmt.Errorf("%s: cannot replace a directory with a file", name)
			}
			reuse = existing
		} else if f.Mode&TypeMask == S_IFDIR {
			return fmt.Errorf("%s: cannot replace a file with a directory", name)
		} else if existing.LinkCount < 2 {
			reuse = existing
		}
	} else {
		if f.Mode&TypeMask == S_IFDIR && dir.LinkCount >= format.MaxLinks {
			return fmt.Errorf("%s: exceeded parent directory maximum link count", name)
		}
	}
	child, err := w.makeInode(f, reuse)
	if err != nil {
		return fmt.Errorf("%s: %s", name, err)
	}
	if existing != child {
		if existing != nil {
			existing.LinkCount--
		}
		dir.Children[childname] = child
		child.LinkCount++
		if child.IsDir() {
			dir.LinkCount++
		}
	}
	if child.Mode&format.TypeMask == format.S_IFREG {
		w.startInode(name, child, f.Size)
	}
	return nil
}

// Link adds a hard link to the file system.
func (w *Writer) Link(oldname, newname string) error {
	if err := w.finishInode(); err != nil {
		return err
	}
	newdir, existing, newchildname, err := w.lookup(newname, false)
	if err != nil {
		return err
	}
	if existing != nil && (existing.IsDir() || existing.LinkCount < 2) {
		return fmt.Errorf("%s: cannot orphan existing file or directory", newname)
	}

	_, oldfile, _, err := w.lookup(oldname, true)
	if err != nil {
		return err
	}
	switch oldfile.Mode & format.TypeMask {
	case format.S_IFDIR, format.S_IFLNK:
		return fmt.Errorf("%s: link target cannot be a directory or symlink: %s", newname, oldname)
	}

	if existing != oldfile && oldfile.LinkCount >= format.MaxLinks {
		return fmt.Errorf("%s: link target would exceed maximum link count: %s", newname, oldname)
	}

	if existing != nil {
		existing.LinkCount--
	}
	oldfile.LinkCount++
	newdir.Children[newchildname] = oldfile
	return nil
}

// Stat returns information about a file that has been written.
func (w *Writer) Stat(name string) (*File, error) {
	if err := w.finishInode(); err != nil {
		return nil, err
	}
	_, node, _, err := w.lookup(name, true)
	if err != nil {
		return nil, err
	}
	f := &File{
		Size:     node.Size,
		Mode:     node.Mode,
		Uid:      node.Uid,
		Gid:      node.Gid,
		Atime:    fsTimeToTime(node.Atime),
		Ctime:    fsTimeToTime(node.Ctime),
		Mtime:    fsTimeToTime(node.Mtime),
		Crtime:   fsTimeToTime(node.Crtime),
		Devmajor: node.Devmajor,
		Devminor: node.Devminor,
	}
	f.Xattrs = make(map[string][]byte)
	if node.XattrBlock != 0 || len(node.XattrInline) != 0 {
		if node.XattrBlock != 0 {
			orig := w.block()
			w.seekBlock(node.XattrBlock)
			if w.err != nil {
				return nil, w.err
			}
			var b [BlockSize]byte
			_, err := w.f.Read(b[:])
			w.seekBlock(orig)
			if err != nil {
				return nil, err
			}
			getXattrs(b[32:], f.Xattrs, 32)
		}
		if len(node.XattrInline) != 0 {
			getXattrs(node.XattrInline[4:], f.Xattrs, 0)
			delete(f.Xattrs, "system.data")
		}
	}
	if node.FileType() == S_IFLNK {
		if node.Size > smallSymlinkSize {
			return nil, fmt.Errorf("%s: cannot retrieve link information", name)
		}
		f.Linkname = string(node.Data)
	}
	return f, nil
}

func (w *Writer) Write(b []byte) (int, error) {
	if len(b) == 0 {
		return 0, nil
	}
	if w.dataWritten+int64(len(b)) > w.dataMax {
		return 0, fmt.Errorf("%s: wrote too much: %d > %d", w.curName, w.dataWritten+int64(len(b)), w.dataMax)
	}

	if w.curInode.Flags&format.InodeFlagInlineData != 0 {
		copy(w.curInode.Data[w.dataWritten:], b)
		w.dataWritten += int64(len(b))
		return len(b), nil
	}

	n, err := w.write(b)
	w.dataWritten += int64(n)
	return n, err
}

func (w *Writer) startInode(name string, inode *inode, size int64) {
	if w.curInode != nil {
		panic("inode already in progress")
	}
	w.curName = name
	w.curInode = inode
	w.dataWritten = 0
	w.dataMax = size
}

func (w *Writer) block() uint32 {
	return uint32(w.pos / BlockSize)
}

func (w *Writer) seekBlock(block uint32) {
	w.pos = int64(block) * BlockSize
	if w.err != nil {
		return
	}
	w.err = w.bw.Flush()
	if w.err != nil {
		return
	}
	_, w.err = w.f.Seek(w.pos, io.SeekStart)
}

func (w *Writer) nextBlock() {
	if w.pos%BlockSize != 0 {
		// Simplify callers; w.err is updated on failure.
		_, _ = w.zero(BlockSize - w.pos%BlockSize)
	}
}

func fillExtents(hdr *format.ExtentHeader, extents []format.ExtentLeafNode, startBlock, offset, inodeSize uint32) {
	*hdr = format.ExtentHeader{
		Magic:   format.ExtentHeaderMagic,
		Entries: uint16(len(extents)),
		Max:     uint16(cap(extents)),
		Depth:   0,
	}
	for i := range extents {
		block := offset + uint32(i)*maxBlocksPerExtent
		length := inodeSize - block
		if length > maxBlocksPerExtent {
			length = maxBlocksPerExtent
		}
		start := startBlock + block
		extents[i] = format.ExtentLeafNode{
			Block:    block,
			Length:   uint16(length),
			StartLow: start,
		}
	}
}

func (w *Writer) writeExtents(inode *inode) error {
	start := w.pos - w.dataWritten
	if start%BlockSize != 0 {
		panic("unaligned")
	}
	w.nextBlock()

	startBlock := uint32(start / BlockSize)
	blocks := w.block() - startBlock
	usedBlocks := blocks

	const extentNodeSize = 12
	const extentsPerBlock = BlockSize/extentNodeSize - 1

	extents := (blocks + maxBlocksPerExtent - 1) / maxBlocksPerExtent
	var b bytes.Buffer
	if extents == 0 {
		// Nothing to do.
	} else if extents <= 4 {
		var root struct {
			hdr     format.ExtentHeader
			extents [4]format.ExtentLeafNode
		}
		fillExtents(&root.hdr, root.extents[:extents], startBlock, 0, blocks)
		_ = binary.Write(&b, binary.LittleEndian, root)
	} else if extents <= 4*extentsPerBlock {
		const extentsPerBlock = BlockSize/extentNodeSize - 1
		extentBlocks := extents/extentsPerBlock + 1
		usedBlocks += extentBlocks
		var b2 bytes.Buffer

		var root struct {
			hdr   format.ExtentHeader
			nodes [4]format.ExtentIndexNode
		}
		root.hdr = format.ExtentHeader{
			Magic:   format.ExtentHeaderMagic,
			Entries: uint16(extentBlocks),
			Max:     4,
			Depth:   1,
		}
		for i := uint32(0); i < extentBlocks; i++ {
			root.nodes[i] = format.ExtentIndexNode{
				Block:   i * extentsPerBlock * maxBlocksPerExtent,
				LeafLow: w.block(),
			}
			extentsInBlock := extents - i*extentBlocks
			if extentsInBlock > extentsPerBlock {
				extentsInBlock = extentsPerBlock
			}

			var node struct {
				hdr     format.ExtentHeader
				extents [extentsPerBlock]format.ExtentLeafNode
				_       [BlockSize - (extentsPerBlock+1)*extentNodeSize]byte
			}

			offset := i * extentsPerBlock * maxBlocksPerExtent
			fillExtents(&node.hdr, node.extents[:extentsInBlock], startBlock+offset, offset, blocks)
			_ = binary.Write(&b2, binary.LittleEndian, node)
			if _, err := w.write(b2.Next(BlockSize)); err != nil {
				return err
			}
		}
		_ = binary.Write(&b, binary.LittleEndian, root)
	} else {
		panic("file too big")
	}

	inode.Data = b.Bytes()
	inode.Flags |= format.InodeFlagExtents
	inode.BlockCount += usedBlocks
	return w.err
}

func (w *Writer) finishInode() error {
	if !w.initialized {
		if err := w.init(); err != nil {
			return err
		}
	}
	if w.curInode == nil {
		return nil
	}
	if w.dataWritten != w.dataMax {
		return fmt.Errorf("did not write the right amount: %d != %d", w.dataWritten, w.dataMax)
	}

	if w.dataMax != 0 && w.curInode.Flags&format.InodeFlagInlineData == 0 {
		if err := w.writeExtents(w.curInode); err != nil {
			return err
		}
	}

	w.dataWritten = 0
	w.dataMax = 0
	w.curInode = nil
	return w.err
}

func modeToFileType(mode uint16) format.FileType {
	switch mode & format.TypeMask {
	default:
		return format.FileTypeUnknown
	case format.S_IFREG:
		return format.FileTypeRegular
	case format.S_IFDIR:
		return format.FileTypeDirectory
	case format.S_IFCHR:
		return format.FileTypeCharacter
	case format.S_IFBLK:
		return format.FileTypeBlock
	case format.S_IFIFO:
		return format.FileTypeFIFO
	case format.S_IFSOCK:
		return format.FileTypeSocket
	case format.S_IFLNK:
		return format.FileTypeSymbolicLink
	}
}

type constReader byte

var zero = constReader(0)

func (r constReader) Read(b []byte) (int, error) {
	for i := range b {
		b[i] = byte(r)
	}
	return len(b), nil
}

func (w *Writer) writeDirectory(dir, parent *inode) error {
	if err := w.finishInode(); err != nil {
		return err
	}

	// The size of the directory is not known yet.
	w.startInode("", dir, 0x7fffffffffffffff)
	left := BlockSize
	finishBlock := func() error {
		if left > 0 {
			e := format.DirectoryEntry{
				RecordLength: uint16(left),
			}
			err := binary.Write(w, binary.LittleEndian, e)
			if err != nil {
				return err
			}
			left -= directoryEntrySize
			if left < 4 {
				panic("not enough space for trailing entry")
			}
			_, err = io.CopyN(w, zero, int64(left))
			if err != nil {
				return err
			}
		}
		left = BlockSize
		return nil
	}

	writeEntry := func(ino format.InodeNumber, name string) error {
		rlb := directoryEntrySize + len(name)
		rl := (rlb + 3) & ^3
		if left < rl+12 {
			if err := finishBlock(); err != nil {
				return err
			}
		}
		e := format.DirectoryEntry{
			Inode:        ino,
			RecordLength: uint16(rl),
			NameLength:   uint8(len(name)),
			FileType:     modeToFileType(w.getInode(ino).Mode),
		}
		err := binary.Write(w, binary.LittleEndian, e)
		if err != nil {
			return err
		}
		_, err = w.Write([]byte(name))
		if err != nil {
			return err
		}
		var zero [4]byte
		_, err = w.Write(zero[:rl-rlb])
		if err != nil {
			return err
		}
		left -= rl
		return nil
	}
	if err := writeEntry(dir.Number, "."); err != nil {
		return err
	}
	if err := writeEntry(parent.Number, ".."); err != nil {
		return err
	}

	// Follow e2fsck's convention and sort the children by inode number.
	var children []string
	for name := range dir.Children {
		children = append(children, name)
	}
	sort.Slice(children, func(i, j int) bool {
		left_num := dir.Children[children[i]].Number
		right_num := dir.Children[children[j]].Number

		if left_num == right_num {
			return children[i] < children[j]
		}
		return left_num < right_num
	})

	for _, name := range children {
		child := dir.Children[name]
		if err := writeEntry(child.Number, name); err != nil {
			return err
		}
	}
	if err := finishBlock(); err != nil {
		return err
	}
	w.curInode.Size = w.dataWritten
	w.dataMax = w.dataWritten
	return nil
}

func (w *Writer) writeDirectoryRecursive(dir, parent *inode) error {
	if err := w.writeDirectory(dir, parent); err != nil {
		return err
	}

	// Follow e2fsck's convention and sort the children by inode number.
	var children []string
	for name := range dir.Children {
		children = append(children, name)
	}
	sort.Slice(children, func(i, j int) bool {
		left_num := dir.Children[children[i]].Number
		right_num := dir.Children[children[j]].Number

		if left_num == right_num {
			return children[i] < children[j]
		}
		return left_num < right_num
	})

	for _, name := range children {
		child := dir.Children[name]
		if child.IsDir() {
			if err := w.writeDirectoryRecursive(child, dir); err != nil {
				return err
			}
		}
	}
	return nil
}

func (w *Writer) writeInodeTable(tableSize uint32) error {
	var b bytes.Buffer
	for _, inode := range w.inodes {
		if inode != nil {
			binode := format.Inode{
				Mode:          inode.Mode,
				Uid:           uint16(inode.Uid & 0xffff),
				Gid:           uint16(inode.Gid & 0xffff),
				SizeLow:       uint32(inode.Size & 0xffffffff),
				SizeHigh:      uint32(inode.Size >> 32),
				LinksCount:    uint16(inode.LinkCount),
				BlocksLow:     inode.BlockCount,
				Flags:         inode.Flags,
				XattrBlockLow: inode.XattrBlock,
				UidHigh:       uint16(inode.Uid >> 16),
				GidHigh:       uint16(inode.Gid >> 16),
				ExtraIsize:    uint16(inodeUsedSize - 128),
				Atime:         uint32(inode.Atime),
				AtimeExtra:    uint32(inode.Atime >> 32),
				Ctime:         uint32(inode.Ctime),
				CtimeExtra:    uint32(inode.Ctime >> 32),
				Mtime:         uint32(inode.Mtime),
				MtimeExtra:    uint32(inode.Mtime >> 32),
				Crtime:        uint32(inode.Crtime),
				CrtimeExtra:   uint32(inode.Crtime >> 32),
			}
			switch inode.Mode & format.TypeMask {
			case format.S_IFDIR, format.S_IFREG, format.S_IFLNK:
				n := copy(binode.Block[:], inode.Data)
				if n < len(inode.Data) {
					// Rewrite the first xattr with the data.
					xattr := [1]xattr{{
						Name:  "data",
						Index: 7, // "system."
						Value: inode.Data[n:],
					}}
					putXattrs(xattr[:], inode.XattrInline[4:], 0)
				}
			case format.S_IFBLK, format.S_IFCHR:
				dev := inode.Devminor&0xff | inode.Devmajor<<8 | (inode.Devminor&0xffffff00)<<12
				binary.LittleEndian.PutUint32(binode.Block[4:], dev)
			}

			_ = binary.Write(&b, binary.LittleEndian, binode)
			b.Truncate(inodeUsedSize)
			n, _ := b.Write(inode.XattrInline)
			_, _ = io.CopyN(&b, zero, int64(inodeExtraSize-n))
		} else {
			_, _ = io.CopyN(&b, zero, inodeSize)
		}
		if _, err := w.write(b.Next(inodeSize)); err != nil {
			return err
		}
	}
	rest := tableSize - uint32(len(w.inodes)*inodeSize)
	if _, err := w.zero(int64(rest)); err != nil {
		return err
	}
	return nil
}

// NewWriter returns a Writer that writes an ext4 file system to the provided
// WriteSeeker.
func NewWriter(f io.ReadWriteSeeker, opts ...Option) *Writer {
	w := &Writer{
		f:           f,
		bw:          bufio.NewWriterSize(f, 65536*8),
		maxDiskSize: defaultMaxDiskSize,
	}
	for _, opt := range opts {
		opt(w)
	}
	return w
}

// An Option provides extra options to NewWriter.
type Option func(*Writer)

// InlineData instructs the Writer to write small files into the inode
// structures directly. This creates smaller images but currently is not
// compatible with DAX.
func InlineData(w *Writer) {
	w.supportInlineData = true
}

// MaximumDiskSize instructs the writer to reserve enough metadata space for the
// specified disk size. If not provided, then 16GB is the default.
func MaximumDiskSize(size int64) Option {
	return func(w *Writer) {
		if size < 0 || size > maxMaxDiskSize {
			w.maxDiskSize = maxMaxDiskSize
		} else if size == 0 {
			w.maxDiskSize = defaultMaxDiskSize
		} else {
			w.maxDiskSize = (size + BlockSize - 1) &^ (BlockSize - 1)
		}
	}
}

func (w *Writer) init() error {
	// Skip the defective block inode.
	w.inodes = make([]*inode, 1, 32)
	// Create the root directory.
	root, _ := w.makeInode(&File{
		Mode: format.S_IFDIR | 0755,
	}, nil)
	root.LinkCount++ // The root is linked to itself.
	// Skip until the first non-reserved inode.
	w.inodes = append(w.inodes, make([]*inode, inodeFirst-len(w.inodes)-1)...)
	maxBlocks := (w.maxDiskSize-1)/BlockSize + 1
	maxGroups := (maxBlocks-1)/blocksPerGroup + 1
	w.gdBlocks = uint32((maxGroups-1)/groupsPerDescriptorBlock + 1)

	// Skip past the superblock and block descriptor table.
	w.seekBlock(1 + w.gdBlocks)
	w.initialized = true

	// The lost+found directory is required to exist for e2fsck to pass.
	if err := w.Create("lost+found", &File{Mode: format.S_IFDIR | 0700}); err != nil {
		return err
	}
	return w.err
}

func groupCount(blocks uint32, inodes uint32, inodesPerGroup uint32) uint32 {
	inodeBlocksPerGroup := inodesPerGroup * inodeSize / BlockSize
	dataBlocksPerGroup := blocksPerGroup - inodeBlocksPerGroup - 2 // save room for the bitmaps

	// Increase the block count to ensure there are enough groups for all the
	// inodes.
	minBlocks := (inodes-1)/inodesPerGroup*dataBlocksPerGroup + 1
	if blocks < minBlocks {
		blocks = minBlocks
	}

	return (blocks + dataBlocksPerGroup - 1) / dataBlocksPerGroup
}

func bestGroupCount(blocks uint32, inodes uint32) (groups uint32, inodesPerGroup uint32) {
	groups = 0xffffffff
	for ipg := uint32(inodesPerGroupIncrement); ipg <= maxInodesPerGroup; ipg += inodesPerGroupIncrement {
		g := groupCount(blocks, inodes, ipg)
		if g < groups {
			groups = g
			inodesPerGroup = ipg
		}
	}
	return
}

func (w *Writer) Close() error {
	if err := w.finishInode(); err != nil {
		return err
	}
	root := w.root()
	if err := w.writeDirectoryRecursive(root, root); err != nil {
		return err
	}
	// Finish the last inode (probably a directory).
	if err := w.finishInode(); err != nil {
		return err
	}

	// Write the inode table
	inodeTableOffset := w.block()
	groups, inodesPerGroup := bestGroupCount(inodeTableOffset, uint32(len(w.inodes)))
	err := w.writeInodeTable(groups * inodesPerGroup * inodeSize)
	if err != nil {
		return err
	}

	// Write the bitmaps.
	bitmapOffset := w.block()
	bitmapSize := groups * 2
	validDataSize := bitmapOffset + bitmapSize
	diskSize := validDataSize
	minSize := (groups-1)*blocksPerGroup + 1
	if diskSize < minSize {
		diskSize = minSize
	}

	usedGdBlocks := (groups-1)/groupsPerDescriptorBlock + 1
	if usedGdBlocks > w.gdBlocks {
		return exceededMaxSizeError{w.maxDiskSize}
	}

	gds := make([]format.GroupDescriptor, w.gdBlocks*groupsPerDescriptorBlock)
	inodeTableSizePerGroup := inodesPerGroup * inodeSize / BlockSize
	var totalUsedBlocks, totalUsedInodes uint32
	for g := uint32(0); g < groups; g++ {
		var b [BlockSize * 2]byte
		var dirCount, usedInodeCount, usedBlockCount uint16

		// Block bitmap
		if (g+1)*blocksPerGroup <= validDataSize {
			// This group is fully allocated.
			for j := range b[:BlockSize] {
				b[j] = 0xff
			}
			usedBlockCount = blocksPerGroup
		} else if g*blocksPerGroup < validDataSize {
			for j := uint32(0); j < validDataSize-g*blocksPerGroup; j++ {
				b[j/8] |= 1 << (j % 8)
				usedBlockCount++
			}
		}
		if g == 0 {
			// Unused group descriptor blocks should be cleared.
			for j := 1 + usedGdBlocks; j < 1+w.gdBlocks; j++ {
				b[j/8] &^= 1 << (j % 8)
				usedBlockCount--
			}
		}
		if g == groups-1 && diskSize%blocksPerGroup != 0 {
			// Blocks that aren't present in the disk should be marked as
			// allocated.
			for j := diskSize % blocksPerGroup; j < blocksPerGroup; j++ {
				b[j/8] |= 1 << (j % 8)
				usedBlockCount++
			}
		}
		// Inode bitmap
		for j := uint32(0); j < inodesPerGroup; j++ {
			ino := format.InodeNumber(1 + g*inodesPerGroup + j)
			inode := w.getInode(ino)
			if ino < inodeFirst || inode != nil {
				b[BlockSize+j/8] |= 1 << (j % 8)
				usedInodeCount++
			}
			if inode != nil && inode.Mode&format.TypeMask == format.S_IFDIR {
				dirCount++
			}
		}
		_, err := w.write(b[:])
		if err != nil {
			return err
		}
		gds[g] = format.GroupDescriptor{
			BlockBitmapLow:     bitmapOffset + 2*g,
			InodeBitmapLow:     bitmapOffset + 2*g + 1,
			InodeTableLow:      inodeTableOffset + g*inodeTableSizePerGroup,
			UsedDirsCountLow:   dirCount,
			FreeInodesCountLow: uint16(inodesPerGroup) - usedInodeCount,
			FreeBlocksCountLow: blocksPerGroup - usedBlockCount,
		}

		totalUsedBlocks += uint32(usedBlockCount)
		totalUsedInodes += uint32(usedInodeCount)
	}

	// Zero up to the disk size.
	_, err = w.zero(int64(diskSize-bitmapOffset-bitmapSize) * BlockSize)
	if err != nil {
		return err
	}

	// Write the block descriptors
	w.seekBlock(1)
	if w.err != nil {
		return w.err
	}
	err = binary.Write(w.bw, binary.LittleEndian, gds)
	if err != nil {
		return err
	}

	// Write the super block
	var blk [BlockSize]byte
	b := bytes.NewBuffer(blk[:1024])
	sb := &format.SuperBlock{
		InodesCount:        inodesPerGroup * groups,
		BlocksCountLow:     diskSize,
		FreeBlocksCountLow: blocksPerGroup*groups - totalUsedBlocks,
		FreeInodesCount:    inodesPerGroup*groups - totalUsedInodes,
		FirstDataBlock:     0,
		LogBlockSize:       2, // 2^(10 + 2)
		LogClusterSize:     2,
		BlocksPerGroup:     blocksPerGroup,
		ClustersPerGroup:   blocksPerGroup,
		InodesPerGroup:     inodesPerGroup,
		Magic:              format.SuperBlockMagic,
		State:              1, // cleanly unmounted
		Errors:             1, // continue on error?
		CreatorOS:          0, // Linux
		RevisionLevel:      1, // dynamic inode sizes
		FirstInode:         inodeFirst,
		LpfInode:           inodeLostAndFound,
		InodeSize:          inodeSize,
		FeatureCompat:      format.CompatSparseSuper2 | format.CompatExtAttr,
		FeatureIncompat:    format.IncompatFiletype | format.IncompatExtents | format.IncompatFlexBg,
		FeatureRoCompat:    format.RoCompatLargeFile | format.RoCompatHugeFile | format.RoCompatExtraIsize | format.RoCompatReadonly,
		MinExtraIsize:      extraIsize,
		WantExtraIsize:     extraIsize,
		LogGroupsPerFlex:   31,
	}
	if w.supportInlineData {
		sb.FeatureIncompat |= format.IncompatInlineData
	}
	_ = binary.Write(b, binary.LittleEndian, sb)
	w.seekBlock(0)
	if _, err := w.write(blk[:]); err != nil {
		return err
	}
	w.seekBlock(diskSize)
	return w.err
}


text:
project_path: /web/_project.yaml
book_path: /web/updates/_book.yaml

{# wf_updated_on: 2012-06-19 #}
{# wf_published_on: 2012-06-19 #}
{# wf_tags: news,css #}

# The amazing powers of CSS {: .page-title }

{% include "web/_shared/contributors/ilmariheikkinen.html" %}

Yesterday at the office, we were coming up with strange and magical CSS tricks. Take this one for instance, it makes empty links very visible:

    a[href = ""] {
      background: red;
      color: white;
      font-size: x-large;
    }

Check out the [live example at jsFiddle](https://jsfiddle.net/VWYsk/){: .external }

You can also style absolute links differently from relative links:

    a[href ^= http] {
      display: inline-block;
      color: red;
      transform: rotate(180deg);
    }

Check out the [live example at jsFiddle](https://jsfiddle.net/RShhf/1/)

If you want to have a different style for links pointing out of your domain, you can use the :not() selector. This is actually how we do the little arrows next to external links at HTML5Rocks.

    a[href ^= 'http']:not([href *= 'html5rocks.']) {
      background: transparent url(arrow.png) no-repeat center right;
      padding-right: 16px;
    }

Check out the [live example at jsFiddle](http://jsfiddle.net/Sts9H/1/)

Just to remind you that you're not limited to styling links, here's how to make all PNG images inverted:

    img[src $= .png] {
      filter: invert(100%);
    }

Moving on from attribute selectors, did you know that you can make the document head visible, along with the other elements there?

    head {
      display: block;
      border-bottom: 5px solid red;
    }
    script, style, link {
      display: block;
      white-space: pre;
      font-family: monospace;
    }

Or that you can use the awesome power of CSS attr-function to fill in the :after and :before content?

    script:before {
      content: "<script src=\"" attr(src) "\" type=\"" attr(type) "\">";
    }
    script:after {
      content: "</script>";
    }

    style:before {
      content: "<style type=\"" attr(type) "\">";
    }
    style:after {
      content: "< /style>";
    }

    /* And for a finish, <link> */
    link:before {
      content: "<link rel=\"" attr(rel) "\" type=\"" attr(type) "\" href=\"" attr(href) "\" />";
    }

Check out the [live example at jsFiddle](http://jsfiddle.net/Wedjf/1/){: .external }

Note that attr() reads in the attribute values of the matching element, so if you use it for #foo:before, it reads the attributes from #foo.

{% include "comment-widget.html" %}


text: Angular 4 Tutorial running in Docker Compose-managed container.