text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Blog | React</title>
  <meta name="viewport" content="width=device-width">
  <meta property="og:title" content="Blog | React">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://facebook.github.io/react/blog/page5/">
  <meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
  <meta property="og:description" content="A JavaScript library for building user interfaces">
  <meta property="fb:app_id" content="623268441017527">

  <link rel="shortcut icon" href="/react/favicon.ico">
  <link rel="alternate" type="application/rss+xml" title="React" href="https://127.0.0.1/react/feed.xml">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" />
  <link rel="stylesheet" href="/react/css/syntax.css">
  <link rel="stylesheet" href="/react/css/codemirror.css">
  <link rel="stylesheet" href="/react/css/react.css">

  <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

          React

Docs/文档

Support/支持

Download/下载

Blog/博客

            <input id="algolia-doc-search" type="text" placeholder="Search docs..." />

GitHub

React Native

Recent posts

Relay: State of the State

Create Apps with No Configuration

Mixins Considered Harmful

Introducing React's Error Code System

React v15.0.1

React v15.0

React v0.14.8

React v15.0 Release Candidate 2

React v15.0 Release Candidate

New Versioning Scheme

All posts ...

  React v0.14

  October  7, 2015
  by

      Ben Alpert

We're happy to announce the release of React 0.14 today! This release has a few major changes, primarily designed to simplify the code you write every day and to better support environments like React Native.

If you tried the release candidate, thank you – your support is invaluable and we've fixed a few bugs that you reported.

As with all of our releases, we consider this version to be stable enough to use in production and recommend that you upgrade in order to take advantage of our latest improvements.

Upgrade Guide #

Like always, we have a few breaking changes in this release. We know changes can be painful (the Facebook codebase has over 15,000 React components), so we always try to make changes gradually in order to minimize the pain.

If your code is free of warnings when running under React 0.13, upgrading should be easy. We have two new small breaking changes that didn't give a warning in 0.13 (see below). Every new change in 0.14, including the major changes below, is introduced with a runtime warning and will work as before until 0.15, so you don't have to worry about your app breaking with this upgrade.

For the two major changes which require significant code changes, we've included codemod scripts to help you upgrade your code automatically.

See the changelog below for more details.

Installation #

We recommend using React from npm and using a tool like browserify or webpack to build your code into a single bundle. To install the two packages:

npm install --save react react-dom

Remember that by default, React runs extra checks and provides helpful warnings in development mode. When deploying your app, set the NODE_ENV environment variable to production to use the production build of React which does not include the development warnings and runs significantly faster.

If you can't use npm yet, we provide pre-built browser builds for your convenience, which are also available in the react package on bower.

React

Dev build with warnings: https://fb.me/react-0.14.0.js

Minified build for production: https://fb.me/react-0.14.0.min.js

React with Add-Ons

Dev build with warnings: https://fb.me/react-with-addons-0.14.0.js

Minified build for production: https://fb.me/react-with-addons-0.14.0.min.js

React DOM (include React in the page before React DOM)

Dev build with warnings: https://fb.me/react-dom-0.14.0.js

Minified build for production: https://fb.me/react-dom-0.14.0.min.js

Changelog #

Major changes #

Two Packages: React and React DOM #

As we look at packages like react-native, react-art, react-canvas, and react-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.

To make this more clear and to make it easier to build more environments that React can render to, we're splitting the main react package into two: react and react-dom. This paves the way to writing components that can be shared between the web version of React and React Native. We don't expect all the code in an app to be shared, but we want to be able to share the components that do behave the same across platforms.

The react package contains React.createElement, .createClass, .Component, .PropTypes, .Children, and the other helpers related to elements and component classes. We think of these as the isomorphic or universal helpers that you need to build components.

The react-dom package has ReactDOM.render, .unmountComponentAtNode, and .findDOMNode. In react-dom/server we have server-side rendering support with ReactDOMServer.renderToString and .renderToStaticMarkup.

var React = require('react');
var ReactDOM = require('react-dom');

var MyComponent = React.createClass({
  render: function() {
    return <div>Hello World</div>;
  }
});

ReactDOM.render(<MyComponent />, node);

The old names will continue to work with a warning until 0.15 is released, and we've published the automated codemod script we used at Facebook to help you with this transition.

The add-ons have moved to separate packages as well:

react-addons-clone-with-props

react-addons-create-fragment

react-addons-css-transition-group

react-addons-linked-state-mixin

react-addons-perf

react-addons-pure-render-mixin

react-addons-shallow-compare

react-addons-test-utils

react-addons-transition-group

react-addons-update

ReactDOM.unstable_batchedUpdates in react-dom.

For now, please use matching versions of react and react-dom (and the add-ons, if you use them) in your apps to avoid versioning problems.

DOM node refs #

The other big change we're making in this release is exposing refs to DOM components as the DOM node itself. That means: we looked at what you can do with a ref to a React DOM component and realized that the only useful thing you can do with it is call this.refs.giraffe.getDOMNode() to get the underlying DOM node. Starting with this release, this.refs.giraffe is the actual DOM node. Note that refs to custom (user-defined) components work exactly as before; only the built-in DOM components are affected by this change.

var Zoo = React.createClass({
  render: function() {
    return <div>Giraffe name: <input ref="giraffe" /></div>;
  },
  showName: function() {
    // Previously: var input = this.refs.giraffe.getDOMNode();
    var input = this.refs.giraffe;
    alert(input.value);
  }
});

This change also applies to the return result of ReactDOM.render when passing a DOM node as the top component. As with refs, this change does not affect custom components.

With this change, we're deprecating .getDOMNode() and replacing it with ReactDOM.findDOMNode (see below). If your components are currently using .getDOMNode(), they will continue to work with a warning until 0.15.

Stateless functional components #

In idiomatic React code, most of the components you write will be stateless, simply composing other components. We're introducing a new, simpler syntax for these components where you can take props as an argument and return the element you want to render:

// A functional component using an ES2015 (ES6) arrow function:
var Aquarium = (props) => {
  var fish = getFish(props.species);
  return <Tank>{fish}</Tank>;
};

// Or with destructuring and an implicit return, simply:
var Aquarium = ({species}) => (
  <Tank>
    {getFish(species)}
  </Tank>
);

// Then use: <Aquarium species="rainbowfish" />

These components behave just like a React class with only a render method defined. Since no component instance is created for a functional component, any ref added to one will evaluate to null. Functional components do not have lifecycle methods, but you can set .propTypes and .defaultProps as properties on the function.

This pattern is designed to encourage the creation of these simple components that should comprise large portions of your apps. In the future, we'll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.

Deprecation of react-tools #

The react-tools package and JSXTransformer.js browser file have been deprecated. You can continue using version 0.13.3 of both, but we no longer support them and recommend migrating to Babel, which has built-in support for React and JSX.

Compiler optimizations #

React now supports two compiler optimizations that can be enabled in Babel 5.8.24 and newer. Both of these transforms should be enabled only in production (e.g., just before minifying your code) because although they improve runtime performance, they make warning messages more cryptic and skip important checks that happen in development mode, including propTypes.

Inlining React elements: The optimisation.react.inlineElements transform converts JSX elements to object literals like {type: 'div', props: ...} instead of calls to React.createElement.

Constant hoisting for React elements: The optimisation.react.constantElements transform hoists element creation to the top level for subtrees that are fully static, which reduces calls to React.createElement and the resulting allocations. More importantly, it tells React that the subtree hasn't changed so React can completely skip it when reconciling.

Breaking changes #

In almost all cases, we change our APIs gradually and warn for at least one release to give you time to clean up your code. These two breaking changes did not have a warning in 0.13 but should be easy to find and clean up:

React.initializeTouchEvents is no longer necessary and has been removed completely. Touch events now work automatically.

Add-Ons: Due to the DOM node refs change mentioned above, TestUtils.findAllInRenderedTree and related helpers are no longer able to take a DOM component, only a custom component.

These three breaking changes had a warning in 0.13, so you shouldn't have to do anything if your code is already free of warnings:

The props object is now frozen, so mutating props after creating a component element is no longer supported. In most cases, React.cloneElement should be used instead. This change makes your components easier to reason about and enables the compiler optimizations mentioned above.

Plain objects are no longer supported as React children; arrays should be used instead. You can use the createFragment helper to migrate, which now returns an array.

Add-Ons: classSet has been removed. Use classnames instead.

New deprecations, introduced with a warning #

Each of these changes will continue to work as before with a new warning until the release of 0.15 so you can upgrade your code gradually.

Due to the DOM node refs change mentioned above, this.getDOMNode() is now deprecated and ReactDOM.findDOMNode(this) can be used instead. Note that in most cases, calling findDOMNode is now unnecessary – see the example above in the "DOM node refs" section.

With each returned DOM node, we've added a getDOMNode method for backwards compatibility that will work with a warning until 0.15. If you have a large codebase, you can use our automated codemod script to change your code automatically.

setProps and replaceProps are now deprecated. Instead, call ReactDOM.render again at the top level with the new props.

ES6 component classes must now extend React.Component in order to enable stateless function components. The ES3 module pattern will continue to work.

Reusing and mutating a style object between renders has been deprecated. This mirrors our change to freeze the props object.

Add-Ons: cloneWithProps is now deprecated. Use React.cloneElement instead (unlike cloneWithProps, cloneElement does not merge className or style automatically; you can merge them manually if needed).

Add-Ons: To improve reliability, CSSTransitionGroup will no longer listen to transition events. Instead, you should specify transition durations manually using props such as transitionEnterTimeout={500}.

Notable enhancements #

Added React.Children.toArray which takes a nested children object and returns a flat array with keys assigned to each child. This helper makes it easier to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down. In addition, React.Children.map now returns plain arrays too.

React uses console.error instead of console.warn for warnings so that browsers show a full stack trace in the console. (Our warnings appear when you use patterns that will break in future releases and for code that is likely to behave unexpectedly, so we do consider our warnings to be "must-fix" errors.)

Previously, including untrusted objects as React children could result in an XSS security vulnerability. This problem should be avoided by properly validating input at the application layer and by never passing untrusted objects around your application code. As an additional layer of protection, React now tags elements with a specific ES2015 (ES6) Symbol in browsers that support it, in order to ensure that React never considers untrusted JSON to be a valid element. If this extra security protection is important to you, you should add a Symbol polyfill for older browsers, such as the one included by Babel's polyfill.

When possible, React DOM now generates XHTML-compatible markup.

React DOM now supports these standard HTML attributes: capture, challenge, inputMode, is, keyParams, keyType, minLength, summary, wrap. It also now supports these non-standard attributes: autoSave, results, security.

React DOM now supports these SVG attributes, which render into namespaced attributes: xlinkActuate, xlinkArcrole, xlinkHref, xlinkRole, xlinkShow, xlinkTitle, xlinkType, xmlBase, xmlLang, xmlSpace.

The image SVG tag is now supported by React DOM.

In React DOM, arbitrary attributes are supported on custom elements (those with a hyphen in the tag name or an is="..." attribute).

React DOM now supports these media events on audio and video tags: onAbort, onCanPlay, onCanPlayThrough, onDurationChange, onEmptied, onEncrypted, onEnded, onError, onLoadedData, onLoadedMetadata, onLoadStart, onPause, onPlay, onPlaying, onProgress, onRateChange, onSeeked, onSeeking, onStalled, onSuspend, onTimeUpdate, onVolumeChange, onWaiting.

Many small performance improvements have been made.

Many warnings show more context than before.

Add-Ons: A shallowCompare add-on has been added as a migration path for PureRenderMixin in ES6 classes.

Add-Ons: CSSTransitionGroup can now use custom class names instead of appending -enter-active or similar to the transition name.

New helpful warnings #

React DOM now warns you when nesting HTML elements invalidly, which helps you avoid surprising errors during updates.

Passing document.body directly as the container to ReactDOM.render now gives a warning as doing so can cause problems with browser extensions that modify the DOM.

Using multiple instances of React together is not supported, so we now warn when we detect this case to help you avoid running into the resulting problems.

Notable bug fixes #

Click events are handled by React DOM more reliably in mobile browsers, particularly in Mobile Safari.

SVG elements are created with the correct namespace in more cases.

React DOM now renders <option> elements with multiple text children properly and renders <select> elements on the server with the correct option selected.

When two separate copies of React add nodes to the same document (including when a browser extension uses React), React DOM tries harder not to throw exceptions during event handling.

Using non-lowercase HTML tag names in React DOM (e.g., React.createElement('DIV')) no longer causes problems, though we continue to recommend lowercase for consistency with the JSX tag name convention (lowercase names refer to built-in components, capitalized names refer to custom components).

React DOM understands that these CSS properties are unitless and does not append "px" to their values: animationIterationCount, boxOrdinalGroup, flexOrder, tabSize, stopOpacity.

Add-Ons: When using the test utils, Simulate.mouseEnter and Simulate.mouseLeave now work.

Add-Ons: ReactTransitionGroup now correctly handles multiple nodes being removed simultaneously.

  ReactDOM.render and the Top Level React API

  October  1, 2015
  by

      Jim Sproch

     and

      Sebastian Markbåge

When you're in React's world you are just building components that fit into other components. Everything is a component. Unfortunately not everything around you is built using React. At the root of your tree you still have to write some plumbing code to connect the outer world into React.

The primary API for rendering into the DOM looks like this:

ReactDOM.render(reactElement, domContainerNode)

To update the properties of an existing component, you call render again with a new element.

If you are rendering React components within a single-page app, you may need to plug into the app's view lifecycle to ensure your app will invoke unmountComponentAtNode at the appropriate time. React will not automatically clean up a tree. You need to manually call:

ReactDOM.unmountComponentAtNode(domContainerNode)

This is important and often forgotten. Forgetting to call unmountComponentAtNode will cause your app to leak memory. There is no way for us to automatically detect when it is appropriate to do this work. Every system is different.

It is not unique to the DOM. If you want to insert a React Native view in the middle of an existing iOS app you will hit similar issues.

Helpers #

If you have multiple React roots, or a single root that gets deleted over time, we recommend that you always create your own wrapper API. These will all look slightly different depending on what your outer system looks like. For example, at Facebook we have a system that automatically ties into our page transition router to automatically call unmountComponentAtNode.

Rather than calling ReactDOM.render() directly everywhere, consider writing/using a library that will manage mounting and unmounting within your application.

In your environment you may want to always configure internationalization, routers, user data etc. If you have many different React roots it can be a pain to set up configuration nodes all over the place. By creating your own wrapper you can unify that configuration into one place.

Object Oriented Updates #

If you call ReactDOM.render a second time to update properties, all your props are completely replaced.

ReactDOM.render(<App locale="en-US" userID={1} />, container);
// props.userID == 1
// props.locale == "en-US"
ReactDOM.render(<App userID={2} />, container);
// props.userID == 2
// props.locale == undefined ??!?

In object-oriented programming, all state lives on each object instance and you apply changes incrementally by mutating that state, one piece at a time. If you are using React within an app that expects an object oriented API (for instance, if you are building a custom web component using React), it might be surprising/confusing to a user that setting a single property would wipe out all the other properties on your component.

We used to have a helper function called setProps which allowed you to update only a few properties at a time. Unfortunately this API lived on a component instance, required React to keep this state internally and wasn't very natural anyway. Therefore, we're deprecating it and suggest that you build it into your own wrapper instead.

Here's some boilerplate to get you started. It is a 0.14 migration path for codebases using setProps and replaceProps.

class ReactComponentRenderer {
  constructor(klass, container) {
    this.klass = klass;
    this.container = container;
    this.props = {};
    this.component = null;
  }

  replaceProps(props, callback) {
    this.props = {};
    this.setProps(props, callback);
  }

  setProps(partialProps, callback) {
    if (this.klass == null) {
      console.warn(
        'setProps(...): Can only update a mounted or ' +
        'mounting component. This usually means you called setProps() on ' +
        'an unmounted component. This is a no-op.'
      );
      return;
    }
    Object.assign(this.props, partialProps);
    var element = React.createElement(this.klass, this.props);
    this.component = ReactDOM.render(element, this.container, callback);
  }

  unmount() {
    ReactDOM.unmountComponentAtNode(this.container);
    this.klass = null;
  }
}

Object-oriented APIs don't look like that though. They use setters and methods. I think we can do better. If you know more about the component API that you're rendering, you can create a more natural object-oriented API around your React component.

class ReactVideoPlayer {
  constructor(url, container) {
    this._container = container;
    this._url = url;
    this._isPlaying = false;
    this._render();
  }

  _render() {
    ReactDOM.render(
      <VideoPlayer url={this._url} playing={this._isPlaying} />,
      this._container
    );
  }

  get url() {
    return this._url;
  }

  set url(value) {
    this._url = value;
    this._render();
  }

  play() {
    this._isPlaying = true;
    this._render();
  }

  pause() {
    this._isPlaying = false;
    this._render();
  }

  destroy() {
    ReactDOM.unmountComponentAtNode(this._container);
  }
}

This example shows how to provide an imperative API on top of a declarative one. Similarly, the reverse can be done, and a declarative wrapper can be used when exposing a Web Component as a React component.

  Community Round-up #27 – Relay Edition

  September 14, 2015
  by

      Steven Luscher

In the weeks following the open-source release of the Relay technical preview, the community has been abuzz with activity. We are honored to have been able to enjoy a steady stream of ideas and contributions from such a talented group of individuals. Let's take a look at some of the things we've achieved, together!

Teaching servers to speak GraphQL #

Every great Relay app starts by finding a GraphQL server to talk to. The community has spent the past few weeks teaching GraphQL to a few backend systems.

Bryan Goldstein (brysgo) has built a tool to help you define a GraphQL schema that wraps a set of Bookshelf.JS models. Check out graphql-bookshelf.

RisingStack (risingstack) created a GraphQL ORM called graffiti that you can plug into mongoose and serve using Express, Hapi, or Koa.

David Mongeau-Petitpas (dmongeau) is working on a way to vend your Laravel models through a GraphQL endpoint, laravel-graphql.

Gerald Monaco (devknoll) created graphql-schema to allow the creation of JavaScript GraphQL schemas using a fluent/chainable interface.

Jason Dusek (solidsnack) dove deep into PostgreSQL to teach it how to respond to GraphQL query strings as though they were SQL queries. Check out GraphpostgresQL.

Espen Hovlandsdal (rexxars) built a sql-to-graphql tool that can perform introspection on the tables of a MySQL or PostgreSQL database, and produce a queryable HTTP GraphQL endpoint out of it.

Mick Hansen (mickhansen) offers a set of schema-building helpers for use with the Sequelize ORM for MySQL, PostgreSQL, SQLite, and MSSQL.

GraphQL beyond JavaScript #

Robert Mosolgo (rmosolgo) brought the full set of schema-building and query execution tools to Ruby, in the form of graphql-ruby and graphql-relay-ruby. Check out his Rails-based demo.

Andreas Marek (andimarek) has brewed up a Java implementation of GraphQL, graphql-java.

vladar is hard at work on a PHP port of the GraphQL reference implementation, graphql-php.

Taeho Kim (dittos) is bringing GraphQL to Python, with graphql-py.

Oleg Ilyenko (OlegIlyenko) made a beautiful and delicious-looking website for a Scala implementation of GraphQL, sangria.

Joe McBride (joemcbride) has an up-and-running example of GraphQL for .NET, graphql-dotnet.

Show me, don't tell me #

Interact with this visual tour of Relay's architecture by Sam Gwilym (sgwilym).

Sam has already launched a product that leverages Relay's data-fetching, optimistic responses, pagination, and mutations – all atop a Ruby GraphQL server: new.comique.co

Prototyping in the browser #

I (steveluscher) whipped up a prototyping tool that you can use to hack on a schema and a React/Relay app, from the comfort of your browser. Thanks to Jimmy Jia (taion) for supplying the local-only network layer, relay-local-schema.

Skeletons in the closet #

Joseph Rollins (fortruce) created a hot-reloading, auto schema-regenerating, Relay skeleton that you can use to get up and running quickly.

Michael Hart (mhart) built a simple-relay-starter kit using Browserify.

Routing around #

Jimmy Jia (taion) and Gerald Monaco (devknoll) have been helping lost URLs find their way to Relay apps through their work on react-router-relay. Check out Christoph Pojer's (cpojer) blog post on the topic. Jimmy completed the Relay TodoMVC example with routing, which you can check out at taion/relay-todomvc.

Chen Hung-Tu (transedward) built a chat app atop the above mentioned router, with threaded conversations and pagination. Check it out at transedward/relay-chat.

In your words #

Relay making good on its promise to be the "React.js of data fetching". Rebuilding small app with it. Spectacular how fast/easy building is.
— Kyle Mathews (@kylemathews) September 5, 2015

#RainySundayHackathon exploring #GraphQL #RelayJS pic.twitter.com/Mm3HlqMejJ
— Bastian Kistner (@passionkind) August 16, 2015

Friday. Time to GraphQL a MySQL database. #graphql #relayjs #reactjs #webapp
— xador (@xadorfr) August 14, 2015

Started a new #RelayJS and #GraphQL meet up group! http://t.co/Vt6Cv4nNH4 If you're in the Bay Area, I'd love to have you join! #ReactJS
— Gerald Monaco (@devknoll) August 27, 2015

.@reactjs @laneykuenzel @BhuwanKhattar these #relayjs mutations. they're mind-blowingly awesome. they make so much damn sense. thank you!
— Jimmy Jia (@jimmy_jia) August 20, 2015

REST is dead, long live REST! #graphql #relayjs
— Syrus Akbary (@syrusakbary) August 12, 2015

  React v0.14 Release Candidate

  September 10, 2015
  by

      Ben Alpert

We're happy to announce our first release candidate for React 0.14! We gave you a sneak peek in July at the upcoming changes but we've now stabilized the release more and we'd love for you to try it out before we release the final version.

Let us know if you run into any problems by filing issues on our GitHub repo.

Installation #

We recommend using React from npm and using a tool like browserify or webpack to build your code into a single package:

npm install --save react@0.14.0-rc1

npm install --save react-dom@0.14.0-rc1

Remember that by default, React runs extra checks and provides helpful warnings in development mode. When deploying your app, set the NODE_ENV environment variable to production to use the production build of React which does not include the development warnings and runs significantly faster.

If you can't use npm yet, we also provide pre-built browser builds for your convenience:

React

Dev build with warnings: https://fb.me/react-0.14.0-rc1.js

Minified build for production: https://fb.me/react-0.14.0-rc1.min.js

React with Add-Ons

Dev build with warnings: https://fb.me/react-with-addons-0.14.0-rc1.js

Minified build for production: https://fb.me/react-with-addons-0.14.0-rc1.min.js

React DOM (include React in the page before React DOM)

Dev build with warnings: https://fb.me/react-dom-0.14.0-rc1.js

Minified build for production: https://fb.me/react-dom-0.14.0-rc1.min.js

These builds are also available in the react package on bower.

Changelog #

Major changes #

Two Packages: React and React DOM #

As we look at packages like react-native, react-art, react-canvas, and react-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.

To make this more clear and to make it easier to build more environments that React can render to, we're splitting the main react package into two: react and react-dom. This paves the way to writing components that can be shared between the web version of React and React Native. We don't expect all the code in an app to be shared, but we want to be able to share the components that do behave the same across platforms.

The react package contains React.createElement, .createClass, .Component, .PropTypes, .Children, and the other helpers related to elements and component classes. We think of these as the isomorphic or universal helpers that you need to build components.

The react-dom package has ReactDOM.render, .unmountComponentAtNode, and .findDOMNode. In react-dom/server we have server-side rendering support with ReactDOMServer.renderToString and .renderToStaticMarkup.

var React = require('react');
var ReactDOM = require('react-dom');

var MyComponent = React.createClass({
  render: function() {
    return <div>Hello World</div>;
  }
});

ReactDOM.render(<MyComponent />, node);

We've published the automated codemod script we used at Facebook to help you with this transition.

The add-ons have moved to separate packages as well: react-addons-clone-with-props, react-addons-create-fragment, react-addons-css-transition-group, react-addons-linked-state-mixin, react-addons-perf, react-addons-pure-render-mixin, react-addons-shallow-compare, react-addons-test-utils, react-addons-transition-group, and react-addons-update, plus ReactDOM.unstable_batchedUpdates in react-dom.

For now, please use matching versions of react and react-dom in your apps to avoid versioning problems.

DOM node refs #

The other big change we're making in this release is exposing refs to DOM components as the DOM node itself. That means: we looked at what you can do with a ref to a React DOM component and realized that the only useful thing you can do with it is call this.refs.giraffe.getDOMNode() to get the underlying DOM node. In this release, this.refs.giraffe is the actual DOM node. Note that refs to custom (user-defined) components work exactly as before; only the built-in DOM components are affected by this change.

var Zoo = React.createClass({
  render: function() {
    return <div>Giraffe name: <input ref="giraffe" /></div>;
  },
  showName: function() {
    // Previously: var input = this.refs.giraffe.getDOMNode();
    var input = this.refs.giraffe;
    alert(input.value);
  }
});

This change also applies to the return result of ReactDOM.render when passing a DOM node as the top component. As with refs, this change does not affect custom components. With these changes, we're deprecating .getDOMNode() and replacing it with ReactDOM.findDOMNode (see below).

Stateless function components #

In idiomatic React code, most of the components you write will be stateless, simply composing other components. We're introducing a new, simpler syntax for these components where you can take props as an argument and return the element you want to render:

// Using an ES2015 (ES6) arrow function:
var Aquarium = (props) => {
  var fish = getFish(props.species);
  return <Tank>{fish}</Tank>;
};

// Or with destructuring and an implicit return, simply:
var Aquarium = ({species}) => (
  <Tank>
    {getFish(species)}
  </Tank>
);

// Then use: <Aquarium species="rainbowfish" />

This pattern is designed to encourage the creation of these simple components that should comprise large portions of your apps. In the future, we'll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.

Deprecation of react-tools #

The react-tools package and JSXTransformer.js browser file have been deprecated. You can continue using version 0.13.3 of both, but we no longer support them and recommend migrating to Babel, which has built-in support for React and JSX.

Compiler optimizations #

React now supports two compiler optimizations that can be enabled in Babel 5.8.23 and newer. Both of these transforms should be enabled only in production (e.g., just before minifying your code) because although they improve runtime performance, they make warning messages more cryptic and skip important checks that happen in development mode, including propTypes.

Inlining React elements: The optimisation.react.inlineElements transform converts JSX elements to object literals like {type: 'div', props: ...} instead of calls to React.createElement.

Constant hoisting for React elements: The optimisation.react.constantElements transform hoists element creation to the top level for subtrees that are fully static, which reduces calls to React.createElement and the resulting allocations. More importantly, it tells React that the subtree hasn't changed so React can completely skip it when reconciling.

Breaking changes #

As always, we have a few breaking changes in this release. Whenever we make large changes, we warn for at least one release so you have time to update your code. The Facebook codebase has over 15,000 React components, so on the React team, we always try to minimize the pain of breaking changes.

These three breaking changes had a warning in 0.13, so you shouldn't have to do anything if your code is already free of warnings:

The props object is now frozen, so mutating props after creating a component element is no longer supported. In most cases, React.cloneElement should be used instead. This change makes your components easier to reason about and enables the compiler optimizations mentioned above.

Plain objects are no longer supported as React children; arrays should be used instead. You can use the createFragment helper to migrate, which now returns an array.

Add-Ons: classSet has been removed. Use classnames instead.

And these two changes did not warn in 0.13 but should be easy to find and clean up:

React.initializeTouchEvents is no longer necessary and has been removed completely. Touch events now work automatically.

Add-Ons: Due to the DOM node refs change mentioned above, TestUtils.findAllInRenderedTree and related helpers are no longer able to take a DOM component, only a custom component.

New deprecations, introduced with a warning #

Due to the DOM node refs change mentioned above, this.getDOMNode() is now deprecated and ReactDOM.findDOMNode(this) can be used instead. Note that in most cases, calling findDOMNode is now unnecessary – see the example above in the "DOM node refs" section.

If you have a large codebase, you can use our automated codemod script to change your code automatically.

setProps and replaceProps are now deprecated. Instead, call ReactDOM.render again at the top level with the new props.

ES6 component classes must now extend React.Component in order to enable stateless function components. The ES3 module pattern will continue to work.

Reusing and mutating a style object between renders has been deprecated. This mirrors our change to freeze the props object.

Add-Ons: cloneWithProps is now deprecated. Use React.cloneElement instead (unlike cloneWithProps, cloneElement does not merge className or style automatically; you can merge them manually if needed).

Add-Ons: To improve reliability, CSSTransitionGroup will no longer listen to transition events. Instead, you should specify transition durations manually using props such as transitionEnterTimeout={500}.

Notable enhancements #

Added React.Children.toArray which takes a nested children object and returns a flat array with keys assigned to each child. This helper makes it easier to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down. In addition, React.Children.map now returns plain arrays too.

React uses console.error instead of console.warn for warnings so that browsers show a full stack trace in the console. (Our warnings appear when you use patterns that will break in future releases and for code that is likely to behave unexpectedly, so we do consider our warnings to be "must-fix" errors.)

Previously, including untrusted objects as React children could result in an XSS security vulnerability. This problem should be avoided by properly validating input at the application layer and by never passing untrusted objects around your application code. As an additional layer of protection, React now tags elements with a specific ES2015 (ES6) Symbol in browsers that support it, in order to ensure that React never considers untrusted JSON to be a valid element. If this extra security protection is important to you, you should add a Symbol polyfill for older browsers, such as the one included by Babel's polyfill.

When possible, React DOM now generates XHTML-compatible markup.

React DOM now supports these standard HTML attributes: capture, challenge, inputMode, is, keyParams, keyType, minLength, summary, wrap. It also now supports these non-standard attributes: autoSave, results, security.

React DOM now supports these SVG attributes, which render into namespaced attributes: xlinkActuate, xlinkArcrole, xlinkHref, xlinkRole, xlinkShow, xlinkTitle, xlinkType, xmlBase, xmlLang, xmlSpace.

The image SVG tag is now supported by React DOM.

In React DOM, arbitrary attributes are supported on custom elements (those with a hyphen in the tag name or an is="..." attribute).

React DOM now supports these media events on audio and video tags: onAbort, onCanPlay, onCanPlayThrough, onDurationChange, onEmptied, onEncrypted, onEnded, onError, onLoadedData, onLoadedMetadata, onLoadStart, onPause, onPlay, onPlaying, onProgress, onRateChange, onSeeked, onSeeking, onStalled, onSuspend, onTimeUpdate, onVolumeChange, onWaiting.

Many small performance improvements have been made.

Many warnings show more context than before.

Add-Ons: A shallowCompare add-on has been added as a migration path for PureRenderMixin in ES6 classes.

Add-Ons: CSSTransitionGroup can now use custom class names instead of appending -enter-active or similar to the transition name.

New helpful warnings #

React DOM now warns you when nesting HTML elements invalidly, which helps you avoid surprising errors during updates.

Passing document.body directly as the container to ReactDOM.render now gives a warning as doing so can cause problems with browser extensions that modify the DOM.

Using multiple instances of React together is not supported, so we now warn when we detect this case to help you avoid running into the resulting problems.

Notable bug fixes #

Click events are handled by React DOM more reliably in mobile browsers, particularly in Mobile Safari.

SVG elements are created with the correct namespace in more cases.

React DOM now renders <option> elements with multiple text children properly and renders <select> elements on the server with the correct option selected.

When two separate copies of React add nodes to the same document (including when a browser extension uses React), React DOM tries harder not to throw exceptions during event handling.

Using non-lowercase HTML tag names in React DOM (e.g., React.createElement('DIV')) no longer causes problems, though we continue to recommend lowercase for consistency with the JSX tag name convention (lowercase names refer to built-in components, capitalized names refer to custom components).

React DOM understands that these CSS properties are unitless and does not append "px" to their values: animationIterationCount, boxOrdinalGroup, flexOrder, tabSize, stopOpacity.

Add-Ons: When using the test utils, Simulate.mouseEnter and Simulate.mouseLeave now work.

Add-Ons: ReactTransitionGroup now correctly handles multiple nodes being removed simultaneously.

  New React Developer Tools

  September  2, 2015
  by

      Ben Alpert

A month ago, we posted a beta of the new React developer tools. Today, we're releasing the first stable version of the new devtools. We're calling it version 0.14, but it's a full rewrite so we think of it more like a 2.0 release.

It contains a handful of new features, including:

Built entirely with React, making it easier to develop and extend

Firefox support

Selected component instance is available as $r from the console

More detail is shown in props in the component tree

Right-click any node and choose "Show Source" to jump to the render method in the Sources panel

Right-click any props or state value to make it available as $tmp from the console

Full React Native support

Installation #

Download the new devtools from the Chrome Web Store and on Mozilla Add-ons for Firefox. If you're developing using React, we highly recommend installing these devtools.

If you already have the Chrome extension installed, it should autoupdate within the next week. You can also head to chrome://extensions and click "Update extensions now" if you'd like to get the new version today. If you installed the devtools beta, please remove it and switch back to the version from the store to make sure you always get the latest updates and bug fixes.

If you run into any issues, please post them on our react-devtools GitHub repo.

          « Previous Page

          Next Page »

        A Facebook & Instagram collaboration.

        Acknowledgements

        © 2013–2016 Facebook Inc.

        Documentation licensed under CC BY 4.0.


text:
FROM kalabox/debian:stable

RUN \
  mkdir -p /usr/local/bin && \
  mkdir -p /root/.ssh

COPY krsync /usr/local/bin/krsync
COPY ssh-config /root/.ssh/config

RUN chmod +x /usr/local/bin/krsync

ENV SSH_KEY id_rsa

ENTRYPOINT ["/usr/local/bin/krsync"]

redpajama_set_name: RedPajamaGithub


text:
using System.IO;
using Microsoft.TemplateEngine.Abstractions.Mount;

namespace Microsoft.TemplateEngine.Edge.Mount.FileSystem
{
    internal class FileSystemFile : FileBase
    {
        private readonly string _physicalPath;

        public FileSystemFile(IMountPoint mountPoint, string fullPath, string name, string physicalPath)
            : base(mountPoint, fullPath, name)
        {
            _physicalPath = physicalPath;
        }

        public override bool Exists => MountPoint.EnvironmentSettings.Host.FileSystem.FileExists(_physicalPath);

        public override Stream OpenRead()
        {
            return MountPoint.EnvironmentSettings.Host.FileSystem.OpenRead(_physicalPath);
        }
    }
}


text:
<meta charset="UTF-8">

通过 调用java方法来调用html中的方法

通过 html调用html中的方法


text:
Reports cases where the static Integer.compare() method or similar methods can be used
instead of more verbose or less efficient constructs.

If x and y are already boxed integers, then x.compareTo(y) is suggested.

Example:

  public int compare(int x, int y) {
    return x > y ? 1 : x < y ? -1 : 0;
  }

After the quick-fix is applied:

  public int compare(int x, int y) {
    return Integer.compare(x, y);
  }

  The Double.compare() and Float.compare() methods were introduced in Java 1.4. Methods for other primitive types
  are available since Java 1.7.

New in 2017.2


text:
package com.example.asynctaskdemo;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.widget.ImageView;

import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class ImageLoader {

	private ImageView mImageView;
	private String mUrl;
	// ´´½¨cache
	private LruCache<String, Bitmap> mCache;

	private PullToRefreshListView mListView;
	private Set<NewsAsyncTask> mTasks;

	public ImageLoader(PullToRefreshListView mPullToRefreshListView) {
		mListView = mPullToRefreshListView;
		mTasks = new HashSet<>();
		// »ñÈ¡×î´ó¿ÉÓÃÄÚ´æ
		int maxMemory = (int) Runtime.getRuntime().maxMemory();
		int cacheSize = maxMemory / 4;
		mCache = new LruCache<String, Bitmap>(cacheSize) {
			@Override
			protected int sizeOf(String key, Bitmap value) {
				// TODO Auto-generated method stub
				// ÔÚÿ´Î´æÈ뻺´æµÄµÄʱºòµ÷ÓÃ
				return value.getByteCount();
			}
		};
	}

	// Ôö¼Óµ½»º´æ
	public void addBitmapToCache(String url, Bitmap bitmap) {
		if (getBitmapFromCache(url) == null) {
			mCache.put(url, bitmap);
		}
	}

	// ´Ó»º´æÖлñÈ¡Êý¾Ý
	public Bitmap getBitmapFromCache(String url) {
		return mCache.get(url);

	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (mImageView.getTag().equals(mUrl)) {
				mImageView.setImageBitmap((Bitmap) msg.obj);
			}
		}
	};

	/**
	 * ͨ¹ý¶àÏ̵߳ķ½Ê½¼ÓÔØͼƬ
	 *
	 * @param imageView
	 * @param url
	 */
	public void showImageByThread(ImageView imageView, final String url) {
		mImageView = imageView;
		mUrl = url;
		new Thread(new Runnable() {

			@Override
			public void run() {
				Bitmap bitmap = getBitmapFromURL(url);
				Message message = Message.obtain();
				message.obj = bitmap;
				mHandler.sendMessage(message);
			}
		}).start();
	}

	public Bitmap getBitmapFromURL(String urlString) {
		Bitmap bitmap = null;
		InputStream is = null;
		try {
			URL url = new URL(urlString);
			try {
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				is = new BufferedInputStream(connection.getInputStream());
				bitmap = BitmapFactory.decodeStream(is);
				connection.disconnect();
				// return bitmap;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// return null;
		return bitmap;
	}

	public void cancelAllTasks() {
		// TODO Auto-generated method stub
		if (mTasks != null) {
			for (NewsAsyncTask task : mTasks) {
				task.cancel(false);
			}
		}
	}

	// ÓÃÀ´¼ÓÔØ´Óstartµ½endµÄËùÓÐͼƬ
	public void loadImages(int start, int end) {
		for (int i = start; i < end; i++) {
			String url = NewsAdapter.URLS[i];// Õâ¸öµØ·½Êý×éË÷ÒýÒç³öÁË£¬»¹Î´½â¾ö
			// ´Ó»º´æÖÐÈ¡³ö¶ÔÓ¦µÄͼƬ
			Bitmap bitmap = getBitmapFromCache(url);
			// Èç¹û»º´æÖÐûÓÐͼƬ£¬ÄÇô±ØÐëÈ¥ÏÂÔØ
			if (bitmap == null) {
				NewsAsyncTask task = new NewsAsyncTask(url);
				task.execute(url);
				mTasks.add(task);
			} else {
				ImageView imageView = (ImageView) mListView
						.findViewWithTag(url);
				imageView.setImageBitmap(bitmap);
			}
		}
	}

	/**
	 * ͨ¹ýÒì²½µÄ·½Ê½¼ÓÔØͼƬ
	 *
	 * @param imageView
	 * @param url
	 */
	public void showIamgeByAsyncTask(ImageView imageView, String url) {
		// ´Ó»º´æÖÐÈ¡³ö¶ÔÓ¦µÄͼƬ
		Bitmap bitmap = getBitmapFromCache(url);
		// Èç¹û»º´æÖÐûÓÐͼƬ£¬ÄÇô±ØÐëÈ¥ÏÂÔØ
		if (bitmap == null) {
			imageView.setImageResource(R.drawable.ic_launcher);
		} else {
			imageView.setImageBitmap(bitmap);
		}

	}

	private class NewsAsyncTask extends AsyncTask<String, Void, Bitmap> {

		// private ImageView mImageView;
		private String mUrl;

		public NewsAsyncTask(String url) {
			mUrl = url;
			// mImageView = imageView;
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			// TODO Auto-generated method stub
			String url = params[0];
			// ´ÓÍøÂç»ñȡͼƬ
			Bitmap bitmap = getBitmapFromURL(params[0]);
			if (bitmap != null) {
				// ½«²»ÔÙ»º´æµÄͼƬ´æ·Åµ½»º´æ
				addBitmapToCache(url, bitmap);
			}
			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap bitmap) {
			// TODO Auto-generated method stub
			super.onPostExecute(bitmap);
			// if (mImageView.getTag().equals(mUrl)) {
			// mImageView.setImageBitmap(bitmap);
			// }
			ImageView imageView = (ImageView) mListView.findViewWithTag(mUrl);
			if (imageView != null && bitmap != null) {
				imageView.setImageBitmap(bitmap);
			}
			mTasks.remove(this);
		}
	}

}


text:
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> myList = new LinkedList<String>();
        myList.add("I");
        myList.add("think");
        myList.add("therefore");
        myList.add("I");
        myList.add("am");

        System.out.println(myList);
        Collections.sort(myList);
        System.out.println(myList);
    }
}


text:
package com.akjava.gwt.modelweight.client;

import com.akjava.gwt.three.client.js.math.Vector3;

public class NameAndPosition {
private String name;
private Vector3 position;
private int index;
public int getIndex() {
	return index;
}
public void setIndex(int index) {
	this.index = index;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public Vector3 getPosition() {
	return position;
}
public void setPosition(Vector3 position) {
	this.position = position;
}
public NameAndPosition(String name,Vector3 position,int index){
	this.name=name;
	this.position=position;
	this.index=index;
}
}


text:
\section{Literaturverzeichnis}

\textbf{Beutelspacher, A., Neumann, H. B. und Schwarzpaul, T.:}\\
Kryptografie in Theorie und Praxis.\\
Wiesbaden, Vieweg+Teubner Verlag, 2005.

\textbf{Brill, M.:}\\
Mathematik für Informatiker.\\
Wien, Hanser Verlag, 2004.

\textbf{Forster, O.:}\\
Algorithmische Zahlentheorie.\\
Wiesbaden, Vieweg Braunschweig/Wiesbaden, 1996.

\textbf{Pethö, A. und Pohst, M.:}\\
Algebraische Algorithmen.\\
Wiesbaden, Vieweg+Teubner Verlag, 1999.

\textbf{Reiss, K. und Schmieder, G.:}\\
Basiswissen Zahlentheorie.\\
Berlin Heidelberg, Springer-Verlag, 2007.

\textbf{Rothe, J.:}\\
Komplexitätstheorie und Kryptologie.\\
Berlin, Springer, 2008.

\textbf{Wrixon, F. B.:}\\
Geheimsprachen.\\
Königswinter, Tandem Verlag GmbH, 2006.

\newpage
\subsection*{Internetadressen}
{\footnotesize
\begin{tabular}{lp{12cm}}
{[Berendt]} &
Berendt, Gerhard.\newline
Seminar über Zahlentheorie/Kryptographie.\hfill10.04.2008\newline
URL:  http://userpage.fu-berlin.de/$\sim$berendt/lehre2008\_neu.html\newline
{[Stand: 09.01.2010]} \\
{[Birthälmer]} &
Birthälmer, Melita.\newline
Kryptografie\hfill13.04.2008\newline
URL: http://www.birthaelmer.com/fileadmin/birthaelmer/portfolio/Kryptografie\_web.pdf\newline
{[Stand: 09.01.2010]} \\
{[msri]} &
SIAM News.\newline
Still Guarding Secrets after Years of Attacks, RSA Earns Accolades for its Founders.\hfill17.06.2003\newline
URL: http://www.msri.org/people/members/sara/articles/rsa.pdf\newline
{[Stand: 09.01.2010]} \\
{[Paixão]} &
Paixão, Cesar A. M.. \newline
An efficient variant of the RSA cryptosystem.\hfill11.08.2009\newline
URL: http://eprint.iacr.org/2003/159.pdf\newline
{[Stand: 26.11.2009]} \\
{[Petitcolas]} &
Petitcolas, Fabien. \newline
DESIDERATA DE LA CRYPTOGRAPHIE MILITAIRE.\hfill20.06.2009\newline
URL: http://www.petitcolas.net/fabien/kerckhoffs/la\_cryptographie\_militaire\_i.htm\#desiderata \newline
{[Stand: 09.01.2010]} \\
{[RSA-2190]} &
RSA Laboratories.\newline
What are the best factoring methods in use today?\hfill03.11.2009\newline
URL: http://www.rsa.com/rsalabs/node.asp?id=2190\newline
{[Stand: 09.01.2010]} \\
{[RSA-2191]} &
RSA Laboratories.\newline
What improvements are likely in factoring capability?\hfill03.11.2009\newline
URL: http://www.rsa.com/rsalabs/node.asp?id=2191\newline
{[Stand: 09.01.2010]} \\
{[RSA-2216]} &
RSA Laboratories.\newline
What would it take to break the RSA cryptosystem?\hfill03.11.2009\newline
URL: http://www.rsa.com/rsalabs/node.asp?id=2216\newline
{[Stand: 09.01.2010]} \\
{[RSA-2964]} &
RSA Laboratories.\newline
RSA-640 factored!\hfill03.01.2010\newline
URL: http://www.rsa.com/rsalabs/node.asp?id=2964\newline
{[Stand: 09.01.2010]} \\
{[wiki-RSA]} &
Ladenthin, Bernhard.\newline
RSA-Kryptosystem.\hfill08.01.2010\newline
URL: http://de.wikipedia.org/wiki/RSA-Kryptosystem\#Erzeugung\_des\_öffentlichen\_und\_privaten\_Schlüssels\newline
{[Stand: 09.01.2010]}
\end{tabular}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <title>
        {% if page.title %}
            {{ page.title }} –
        {% endif %}
        {{ site.name }}
    </title>

    <meta name="author" content="{{ site.name }}" />
    <meta name="description" content="{{ site.description }}" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    {% for style in site.data.stylesheets %}
        <link href="{{style.href}}" rel="{{style.rel}}" type="{{style.type}}" media="{{style.media}}"/>
    {% endfor %}

    {% for script in site.data.javascripts %}

    {% endfor %}

                {{ site.name|split:' '|first }}
                {{ site.name|split:' '|last }}

about

posts

    {{ content }}


text:
<?php

namespace Documents\Functional\Ticket\MODM160;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/** @ODM\EmbeddedDocument */
class MODM160Level2
{
    /** @ODM\String */
    public $name;

}


text:
type Maybe<T> = null | undefined | T

export default Maybe


text:
Docs for SplitConfig files.
==========================

### Basic foo.splitconfig.json structure

	{
		"target_path":"full/path/to/target/repo",
		"author_behavior": preserve, // value from [preserve, overwrite]
		"committer_behavior": preserve, // value from [preserve, overwrite]
		"collision_strategies": {
			default:{
				file: "abort",// value from [abort, erase_target_first, single_commit]
				// if a file collides with an existing file in the target repo, what should we do?
				// - abort: print message & abort
				// - erase_target_first: erases the target file with a special commit before installing the new one.
				// - "single_commit": drop the history, but take the final file state, and create a single commit for it moving it from current state to the final state.

				branch: "prefix", // value from [prefix, abort, unsafe_ignore]
				// What should we do if a needed branch already exists in the target repo?
				// - prefix: proceed anyhow, by appending a prefix to the branch name.
				// - abort: print message & abort
				// - unsafe_ignore: proceed anyhow, only use this if you're sure the file won't collide!
				branch_prefix:"git-split/",

				branch_cleanup:true, // Should we auto-delete any branches created due to git-split?
			},
			branch_specific:{
				// see collision_strategies.default.branch* for fields that can go in here.
				"master":{
					branch: "unsafe_ignore",// The master branch is special, and very likely to exist
				}
			}
			file_specific:{
				//Overrides for a specific path, see collision_strategies.default.file
				"full/path": "abort"
			},
		},
		"files":[ // This is the list of actual files to trace
			"full/file/path"
		]
	}

### Special case: deleteset.splitconfig.json

`$ git-split prepare` will ask if you want to delete the files referenced in the new splitconfigs from the original source repo, if yes, this is the structure:
	{
		delete_paths:[
			"full/file/path"
		]
	}
These paths will be the union of all the splitconfigs considered when preparing the deleteset. You should feel free to edit this file to remove any paths you want to copy rather than remove from the source repo. They will simply all be passed to git rm, and the results staged and committed. (You can amend this commit if you want to change the message or contents.)


text:
// Entry component with image and sound
enyo.kind({
	name: "TamTam.Item",
	kind: enyo.Control,
	published: { name: "" },
	classes: "item",
	components: [
		{ name: "itemImage", classes: "itemImage", kind: "Image", ontap: "play" }
	],

	// Constructor
	create: function() {
		this.inherited(arguments);
		this.nameChanged();
		this.sound = null;
	},

	// Item setup
	nameChanged: function() {
		this.$.itemImage.setAttribute("src", "images/database/"+this.name+".png");
	},

	// Play sound using the media
	play: function() {
		this.$.itemImage.setAttribute("src", "images/database/"+this.name+"sel.png");
		if (this.name != null) {
			this.sound = "audio/database/"+this.name;
			sound.play(this);
		}
	},

	endofsound: function() {
		if (this.$.itemImage)
			this.$.itemImage.setAttribute("src", "images/database/"+this.name+".png");
	},

	abort: function() {
		this.endofsound();
	}
});


text:
package de.toble.tetris.gui.render;

import java.awt.Color;
import java.awt.image.BufferedImage;

public class LighthouseTetrisRender
{
	public void render(Color[][] colors, BufferedImage img)
	{
		for(int y = 0; y < img.getHeight(); y++)
		{
			for(int x = 0; x < img.getWidth(); x++)
			{
				if(colors[y][x] == null) continue;
				img.setRGB(x, img.getHeight() - y - 1, colors[y][x].getRGB());
			}
		}
	}
}


text:
import Credentials from './credentials';
import {registerPlugin} from '../../spark-core';

registerPlugin('credentials', Credentials, {
  proxies: [
    'canAuthorize',
    'canRefresh'
  ]
});

export {default as Credentials} from './credentials';
export {filterScope, sortScope} from './scope';
export {default as Token} from './token';
export {default as grantErrors} from './grant-errors';


text:
import Vue from 'vue'
import Router from 'vue-router'
import home from '@/router/home'
import logout from '@/router/logout'
import profile from '@/router/profile'
import requestGroup from '@/router/requestGroup'
import createGroup from '@/router/createGroup'
import userAdministration from '@/router/userAdministration'
import appAdministration from '@/router/appAdministration'
import browseGroups from '@/router/browseGroup'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: home
    },
    {
      path: '/profile',
      name: 'profile',
      component: profile
    },
    {
      path: '/logout',
      name: 'logout',
      component: logout
    },
    {
      path: '/requestgroup',
      name: 'requestGroup',
      component: requestGroup
    },
    {
      path: '/creategroup',
      name: 'createGroup',
      component: createGroup
    },
    {
      path: '/useradministration',
      name: 'userAdministration',
      component: userAdministration
    },
    {
      path: '/appadministration',
      name: 'appAdministration',
      component: appAdministration
    },
    {
      path: '/browsegroup',
      name: 'browseGroup',
      component: browseGroups
    }
  ]
})


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;

namespace Roslyn.Test.Utilities
{
    /// <summary>
    /// Used to tag test methods or types which are created for a given WorkItem
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
    public sealed class WorkItemAttribute : Attribute
    {
        public int Id
        {
            get;
        }

        public string Location
        {
            get;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="WorkItemAttribute"/>.
        /// </summary>
        /// <param name="id">The ID of the issue in the original tracker where the work item was first reported. This
        /// could be a GitHub issue or pull request number, or the number of a Microsoft-internal bug.</param>
        /// <param name="issueUri">The URI where the work item can be viewed. This is a link to work item
        /// <paramref name="id"/> in the original source.</param>
        public WorkItemAttribute(int id, string issueUri)
        {
            Id = id;
            Location = issueUri;
        }
    }
}


text:
// Generated on Mon Mar 17 18:02:09 MSK 2008
// DTD/Schema  :    http://maven.apache.org/POM/4.0.0

package org.jetbrains.idea.maven.dom.model;

import com.intellij.util.xml.Convert;
import com.intellij.util.xml.GenericDomValue;
import com.intellij.util.xml.Required;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.maven.dom.converters.MavenDistributionStatusConverter;
import org.jetbrains.idea.maven.dom.MavenDomElement;
import org.jetbrains.idea.maven.dom.converters.MavenUrlConverter;

public interface MavenDomDistributionManagement extends MavenDomElement {
  @NotNull
  MavenDomDeploymentRepository getRepository();

  @NotNull
  MavenDomDeploymentRepository getSnapshotRepository();

  @NotNull
  MavenDomSite getSite();

  @NotNull
  @Convert(MavenUrlConverter.class)
  GenericDomValue<String> getDownloadUrl();

  @NotNull
  MavenDomRelocation getRelocation();

  @NotNull
  @Required(value = false, nonEmpty = true)
  @Convert(MavenDistributionStatusConverter.class)
  GenericDomValue<String> getStatus();
}


text:
package com.untzuntz.ustack.data;

import java.net.InetSocketAddress;
import java.util.List;

import net.spy.memcached.AddrUtil;
import net.spy.memcached.BinaryConnectionFactory;
import net.spy.memcached.MemcachedClient;

import org.apache.log4j.Logger;

import com.untzuntz.ustack.main.UAppCfg;
import com.untzuntz.ustack.main.UOpts;

/**
 * Memcache data cache interface
 *
 * @author jdanner
 *
 */
public class UDataCache {

	static Logger logger = Logger.getLogger(UDataCache.class);

	private static final String NAMESPACE = "UST_n7zv1";
	private static UDataCache instance = null;
	private static MemcachedClient[] m = null;
	private static final int CLIENT_COUNT = 20;

	private UDataCache() {

		try {
			List<InetSocketAddress> addrList = AddrUtil.getAddresses(UOpts.getString(UAppCfg.CACHE_HOST_STRING));
			m = new MemcachedClient[CLIENT_COUNT + 1];
			for (int i = 0; i <= CLIENT_COUNT; i ++) {
				MemcachedClient c =  new MemcachedClient(new BinaryConnectionFactory(), addrList);
				m[i] = c;
			}
		} catch (Exception e) {
			logger.warn("Failed to setup clients", e);
		}

	}

	public static synchronized UDataCache getInstance() {

		if(instance == null) {
			String hosts = UOpts.getString(UAppCfg.CACHE_HOST_STRING);
			if (hosts != null && hosts.length() > 0)
			{
				logger.info("Creating a new UDataCache instance...[" + hosts + "]");
				instance = new UDataCache();
			}
		}
		return instance;

	}

	public long incr(String key, int ttl, final long o) {

		MemcachedClient client = getCache();
		if (client != null)
		{
			try {
				return client.incr(key, 1, 0, ttl);
			} catch (Exception er) {}
		}
		return 0L;
	}

	public void set(String key, int ttl, final Object o) {

		MemcachedClient client = getCache();
		if (client == null)
			return;

		try {
			client.set(NAMESPACE + key, ttl, o);
		} catch (Exception e) {}

	}

	public Object get(String key) {

		MemcachedClient client = getCache();
		if (client == null)
			return null;

		try {
			Object o = client.get(NAMESPACE + key);
			if(o == null) {
				logger.debug("Cache MISS for KEY: " + key);
			} else {
				logger.debug("Cache HIT for KEY: " + key);
			}
			return o;
		} catch (Exception e) {
			logger.warn("unable to get key from memcache server", e);
		}

		return null;

	}

	public Object delete(String key) {

		MemcachedClient client = getCache();
		if (client == null)
			return null;

		try {
			return client.delete(NAMESPACE + key);
		} catch (Exception e) {}

		return null;
	}

	public MemcachedClient getCache() {

		if (!UOpts.getCacheEnabled())
			return null;

		MemcachedClient c = null;

		try {

			int i = (int)(Math.random() * CLIENT_COUNT);
			c = m[i];

		} catch(Exception e) {
			logger.warn("Failed to get memcache client", e);
		}

		return c;

	}

}


text:
<!DOCTYPE html>

	<meta charset="UTF-8" />
	<title>Progressbar Static Test : Default</title>
	<link rel="stylesheet" href="../static.css" type="text/css" />
	<link rel="stylesheet" href="../../../themes/base/jquery.ui.base.css" type="text/css" />
	<link rel="stylesheet" href="../../../themes/base/jquery.ui.theme.css" type="text/css" title="ui-theme" />


text:
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

      <title>Documentation for xcesc - XMLSchema.xsd - Simple Type QName</title>
      <meta http-equiv="Content-Type" content="text/xml; charset=iso-8859-1"/>

         Documentation for xcesc

Simple Type: QName

         [Table of contents]

            Super-types:

                  xs:anySimpleType
                < QName (by restriction)

            Sub-types:
            None

            Name
            QName

            Used by (from the same schema document)
            Attribute Group
                  defRef
               , Complex Type
                  attribute
               , Complex Type
                  restrictionType
               , Complex Type
                  extensionType
               , Complex Type
                  element
               , Complex Type
                  element
               , Complex Type
                  groupRef
               , Complex Type
                  explicitGroup
               , Complex Type
                  attributeGroupRef
               , Element
                  keyref
               , Element
                  restriction
               , Element
                  list

            Content

Base XSD Type:
                        xs:anySimpleType

                     Whitespace policy:
                     collapse

            Documentation

            Application Data

               <hfp:hasFacet name="length"/>
               <hfp:hasFacet name="minLength"/>
               <hfp:hasFacet name="maxLength"/>
               <hfp:hasFacet name="pattern"/>
               <hfp:hasFacet name="enumeration"/>
               <hfp:hasFacet name="whiteSpace"/>
               <hfp:hasProperty name="ordered" value="false"/>
               <hfp:hasProperty name="bounded" value="false"/>
               <hfp:hasProperty name="cardinality" value="countably infinite"/>
               <hfp:hasProperty name="numeric" value="false"/>

            <input type="button" id="h-1112572617_diagram_button" class="control"
                   onclick="switchState('h-1112572617_diagram'); return false;"
                   style="display: none"/>
            Diagram

            <map name="h-1668339744">
</map>

            <input type="button" id="h-1112572617_scbox_button" class="control"
                   onclick="switchState('h-1112572617_scbox'); return false;"
                   style="display: none"/>
            Schema Component Representation

<xs:simpleType
               name="QName" id="QName">
<xs:restriction
                  base="

                        xs:anySimpleType

                  ">
<xs:whiteSpace
                     value="collapse" fixed="true" id="QName.whiteSpace"/>
</xs:restriction>
</xs:simpleType>

Generated by <oXygen/> XML Editor using a modified version of xs3p that adds schema diagrams and chunking support. Last modified:


text:
/*
Theme Name:         Mikey Sage Theme
Theme URI:          http://iwantcat.com
Description:        Theme for Mikey Tomkins site using: Sage starter theme. Contribute on GitHub
Version:            0.1
Author:             I Want Cat
Author URI:         https://iwantcat.com

License:            MIT License
License URI:        http://opensource.org/licenses/MIT
*/


text:
using System;
using System.ComponentModel;
using Melanchall.DryWetMidi.Common;

namespace Melanchall.DryWetMidi.Interaction
{
    ///
    /// Settings which define how chords should be detected and built.
    ///
    /// <seealso cref="ChordsManagingUtilities"/>
    public sealed class ChordDetectionSettings
    {
        #region Constants

        private const int DefaultNotesMinCount = 1;
        private static readonly long DefaultNotesTolerance = 0;

        #endregion

        #region Fields

        private int _notesMinCount = DefaultNotesMinCount;
        private long _notesTolerance = DefaultNotesTolerance;

        private ChordSearchContext _chordSearchContext = ChordSearchContext.SingleEventsCollection;

        #endregion

        #region Properties

        ///
        /// Gets or sets a minimum count of notes a chord can contain. So if count of simultaneously sounding
        /// notes is less than this value, they won't make up a chord. The default value is <c>1</c>.
        ///
        /// <example>
        /// <para>Let's take a look at the example:</para>
        /// <para>
        ///
        /// ...###...
        /// ...#####.
        /// .....###.
        ///
        /// </para>
        /// <para>
        /// So we have three notes (represented by <c>#</c> symbol). For simplicity we'll assume that
        /// <see cref="NotesTolerance"/> is <c>0</c> (default value) and every character occupies 1 unit
        /// of time. If we set notes min count to <c>1</c> (which is default value), we'll get two different
        /// instances of <see cref="Chord"/>:
        ///
        ///      A
        ///      |
        /// ...[###]...
        /// ...[#####].
        /// .....(###).
        ///        |
        ///        B
        ///
        /// <c>[...]</c> and <c>(...)</c> denote two different chords (A and B).
        /// </para>
        /// <para>
        /// If we set notes min count to <c>2</c>, we'll get only one chord:
        ///
        ///           A
        ///           |
        ///       +---+---+
        ///       |       |
        /// ...[###]...   |
        /// ...[#####].   |
        ///       |       |
        ///       +-------+
        ///
        /// .....###...
        ///
        /// Last note will not be turned into a chord because count of notes for a chord will be <c>1</c>
        /// which is less than the specified minimum count.
        /// </para>
        /// <para>
        /// With minimum count of notes of <c>3</c> we'll get no chords:
        ///
        /// ...###...
        /// ...#####.
        /// .....###.
        ///
        /// First possible chord will contain two notes and second chord will contain one note. In both cases
        /// count of notes is less than the specified minimum count.
        /// </para>
        /// </example>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is zero or negative.</exception>
        public int NotesMinCount
        {
            get { return _notesMinCount; }
            set
            {
                ThrowIfArgument.IsNonpositive(nameof(value), value, "Value is zero or negative.");

                _notesMinCount = value;
            }
        }

        ///
        /// Gets or sets maximum distance of notes from the start of the first note of a chord.
        /// Notes within this tolerance will be included in a chord. The default value is <c>0</c>.
        ///
        /// <example>
        /// <para>Let's take a look at the example:</para>
        /// <para>
        ///
        /// ...###...
        /// ....#####
        /// .....###.
        ///
        /// </para>
        /// <para>
        /// So we have three notes (represented by <c>#</c> symbol). Every character occupies 1 unit of time.
        /// If we set notes tolerance to <c>0</c> (which is default value), we'll get three different instances of
        /// <see cref="Chord"/>:
        ///
        ///      A
        ///      |
        /// ...[###]...
        ///        B
        ///        |
        /// ....(#####)
        /// .....{###}.
        ///        |
        ///        C
        ///
        /// <c>[...]</c>, <c>(...)</c> and <c>{...}</c> denote three different chords (A, B and C).
        /// </para>
        /// <para>
        /// If we set notes tolerance to <c>1</c>, we'll get two chords:
        ///
        ///           A
        ///           |
        ///       +---+---+
        ///       |       |
        /// ...[###]...   |
        /// ....[#####]   |
        ///       |       |
        ///       +-------+
        ///
        /// .....{###}.
        ///        |
        ///        B
        ///
        /// </para>
        /// <para>
        /// With tolerance of <c>2</c> we'll finally get a single chord:
        ///
        ///           A
        ///           |
        ///       +---+---+
        ///       |       |
        /// ...[###]...   |
        ///       |       |
        /// ....[#####]   |
        ///       |       |
        /// .....[###].   |
        ///       |       |
        ///       +-------+
        ///
        /// </para>
        /// </example>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is negative.</exception>
        public long NotesTolerance
        {
            get { return _notesTolerance; }
            set
            {
                ThrowIfArgument.IsNegative(nameof(value), value, "Value is negative.");

                _notesTolerance = value;
            }
        }

        ///
        /// Gets or sets settings according to which notes should be detected and built. Chords will be
        /// built on top of those notes.
        ///
        public NoteDetectionSettings NoteDetectionSettings { get; set; } = new NoteDetectionSettings();

        ///
        /// Gets or sets a value defining a context to search chords within. The default value is
        /// <see cref="ChordSearchContext.SingleEventsCollection"/>.
        ///
        /// <remarks>
        /// See Remarks section of the <see cref="Interaction.ChordSearchContext"/> enum.
        /// </remarks>
        /// <exception cref="InvalidEnumArgumentException"><paramref name="value"/> specified an invalid value.</exception>
        public ChordSearchContext ChordSearchContext
        {
            get { return _chordSearchContext; }
            set
            {
                ThrowIfArgument.IsInvalidEnumValue(nameof(value), value);

                _chordSearchContext = value;
            }
        }

        #endregion
    }
}


text:
package polka.lfds;

/**
 * Means the series is (more or less irreparably) damaged
 *
 */
public class LFDDamagedException extends LFDException {
	public LFDDamagedException(String reason) { super(reason); }
}


text:
package org.openengsb.core.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.openengsb.core.api.OsgiServiceNotAvailableException;
import org.openengsb.core.api.OsgiUtilsService;
import org.openengsb.core.api.context.ContextHolder;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Function;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;

public class DefaultOsgiUtilsService implements OsgiUtilsService {

    /**
     * serves as common invocation handler for proxies that resolve osgi-services dynamically. The proxy tries to
     * resolve the service for the given timeout. A timeout of 0 means that the proxy will wait for the service
     * indefinitely {@link ServiceTracker#waitForService(long)} A timeout < 0 means that the service tracker will not
     * wait for the service at all. If the service is not available immediately an
     * {@link OsgiServiceNotAvailableException} is thrown.
     *
     */
    private final class ServiceTrackerInvocationHandler implements InvocationHandler {
        private ServiceTracker tracker;
        private Long timeout = -1L;
        private final String info;

        protected ServiceTrackerInvocationHandler(Filter filter, long timeout) {
            this(filter);
            this.timeout = timeout;
        }

        protected ServiceTrackerInvocationHandler(Filter filter) {
            tracker = new ServiceTracker(bundleContext, filter, null);
            info = filter.toString();
        }

        protected ServiceTrackerInvocationHandler(String className, long timeout) {
            this(className);
            this.timeout = timeout;
        }

        protected ServiceTrackerInvocationHandler(String className) {
            tracker = new ServiceTracker(bundleContext, className, null);
            info = "Class: " + className;
        }

        protected ServiceTrackerInvocationHandler(Class<?> targetClass, long timeout) {
            this(targetClass.getName(), timeout);
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object service = getService();
            if (service == null) {
                throw new OsgiServiceNotAvailableException("could not resolve service with tracker: " + info);
            }
            try {
                return method.invoke(service, args);
            } catch (InvocationTargetException e) {
                throw e.getCause();
            }
        }

        private synchronized Object getService() throws InterruptedException {
            tracker.open();
            try {
                if (timeout < 0) {
                    return tracker.getService();
                } else {
                    return tracker.waitForService(timeout);
                }
            } finally {
                tracker.close();
            }
        }
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultOsgiUtilsService.class);
    private static final long DEFAULT_TIMEOUT = 30000L;

    private BundleContext bundleContext;

    public DefaultOsgiUtilsService() {
    }

    public DefaultOsgiUtilsService(BundleContext bundleContext) {
        this.bundleContext = bundleContext;
    }

    @Override
    public <T> T getService(Class<T> clazz) throws OsgiServiceNotAvailableException {
        return getService(clazz, DEFAULT_TIMEOUT);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getService(Class<T> clazz, long timeout) throws OsgiServiceNotAvailableException {
        ServiceTracker tracker = new ServiceTracker(bundleContext, clazz.getName(), null);
        Object result = waitForServiceFromTracker(tracker, timeout);
        if (result == null) {
            throw new OsgiServiceNotAvailableException(String.format("no service of type %s available at the time",
                clazz.getName()));
        }
        return (T) result;
    }

    @Override
    public Object getService(Filter filter)
        throws OsgiServiceNotAvailableException {
        return getService(filter, DEFAULT_TIMEOUT);
    }

    @Override
    public Object getService(Filter filter, long timeout) throws OsgiServiceNotAvailableException {
        ServiceTracker t = new ServiceTracker(bundleContext, filter, null);
        LOGGER.debug("getting service for filter {} from tracker", filter);
        Object result = waitForServiceFromTracker(t, timeout);
        if (result == null) {
            throw new OsgiServiceNotAvailableException(String.format(
                "no service matching filter \"%s\" available at the time", filter.toString()));
        }
        return result;
    }

    @Override
    public Object getService(String filterString) throws OsgiServiceNotAvailableException {
        return getService(filterString, DEFAULT_TIMEOUT);
    }

    @Override
    public Object getService(String filterString, long timeout) throws OsgiServiceNotAvailableException {
        return getService(FilterUtils.createFilter(filterString), timeout);
    }

    @Override
    public <T> T getServiceWithId(Class<? extends T> clazz, String id) throws OsgiServiceNotAvailableException {
        return getServiceWithId(clazz, id, DEFAULT_TIMEOUT);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getServiceWithId(Class<? extends T> clazz, String id, long timeout)
        throws OsgiServiceNotAvailableException {
        return (T) getServiceWithId(clazz.getName(), id, timeout);
    }

    @Override
    public Object getServiceWithId(String className, String id) throws OsgiServiceNotAvailableException {
        return getServiceWithId(className, id, DEFAULT_TIMEOUT);
    }

    @Override
    public Object getServiceWithId(String className, String id, long timeout) throws OsgiServiceNotAvailableException {
        Filter filter = FilterUtils.makeFilter(className, String.format("(%s=%s)", Constants.SERVICE_PID, id));
        return getService(filter, timeout);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T getOsgiServiceProxy(final Filter filter, Class<T> targetClass, final long timeout) {
        return (T) Proxy.newProxyInstance(targetClass.getClassLoader(), new Class<?>[]{ targetClass },
            new ServiceTrackerInvocationHandler(filter, timeout));
    }

    @Override
    public <T> T getOsgiServiceProxy(final String filter, Class<T> targetClass, long timeout) {
        return getOsgiServiceProxy(FilterUtils.createFilter(filter), targetClass, timeout);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T getOsgiServiceProxy(Class<T> targetClass, long timeout) {
        return (T) Proxy.newProxyInstance(targetClass.getClassLoader(), new Class<?>[]{ targetClass },
            new ServiceTrackerInvocationHandler(targetClass, timeout));
    }

    @Override
    public <T> T getOsgiServiceProxy(Class<T> targetClass) {
        return getOsgiServiceProxy(targetClass, DEFAULT_TIMEOUT);
    }

    @Override
    public <T> T getOsgiServiceProxy(Filter filter, Class<T> targetClass) {
        return getOsgiServiceProxy(filter, targetClass, DEFAULT_TIMEOUT);
    }

    @Override
    public <T> T getOsgiServiceProxy(String filter, Class<T> targetClass) {
        return getOsgiServiceProxy(filter, targetClass, DEFAULT_TIMEOUT);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getServiceForLocation(Class<T> clazz, String location, String context)
        throws OsgiServiceNotAvailableException, IllegalArgumentException {
        Filter compiled = OsgiUtils.getFilterForLocation(clazz, location, context);
        return (T) getService(compiled);
    }

    @Override
    public Object getServiceForLocation(String location, String context) throws OsgiServiceNotAvailableException,
        IllegalArgumentException {
        return getService(OsgiUtils.getFilterForLocation(location, context));
    }

    @Override
    public Object getServiceForLocation(String location) throws OsgiServiceNotAvailableException,
        IllegalArgumentException {
        LOGGER.debug("retrieve service for location: {}", location);
        return getService(OsgiUtils.getFilterForLocation(location));
    }

    @Override
    public <T> T getServiceForLocation(Class<T> clazz, String location) throws OsgiServiceNotAvailableException,
        IllegalArgumentException {
        return getServiceForLocation(clazz, location, ContextHolder.get().getCurrentContextId());
    }

    /**
     * tries to retrieve the service from the given service-tracker for the amount of milliseconds provided by the given
     * timeout.
     *
     * @throws OsgiServiceNotAvailableException if the service could not be found within the given timeout
     */
    private static Object waitForServiceFromTracker(ServiceTracker tracker, long timeout)
        throws OsgiServiceNotAvailableException {
        synchronized (tracker) {
            tracker.open();
            try {
                return tracker.waitForService(timeout);
            } catch (InterruptedException e) {
                throw new OsgiServiceNotAvailableException(e);
            } finally {
                tracker.close();
            }
        }
    }

    @Override
    public <T> List<ServiceReference<T>> listServiceReferences(Class<T> clazz) {
        return listServiceReferences(clazz, null);
    }

    @Override
    public List<ServiceReference<?>> listServiceReferences(String filter) {
        ServiceReference<?>[] serviceReferences;
        try {
            serviceReferences = bundleContext.getServiceReferences((String) null, filter);
        } catch (InvalidSyntaxException e) {
            throw new IllegalArgumentException(e);
        }
        if (serviceReferences == null) {
            return Collections.emptyList();
        }
        return Arrays.asList(serviceReferences);
    }

    @Override
    public <T> List<ServiceReference<T>> listServiceReferences(Class<T> clazz, String filter) {
        Collection<ServiceReference<T>> serviceReferences;
        try {
            serviceReferences = bundleContext.getServiceReferences(clazz, filter);
        } catch (InvalidSyntaxException e) {
            throw new IllegalArgumentException(e);
        }
        return Lists.newArrayList(serviceReferences);
    }

    @Override
    public <T> List<T> listServices(Class<T> clazz) {
        ServiceTracker tracker = new ServiceTracker(bundleContext, clazz.getName(), null);
        return getListFromTracker(tracker);
    }

    private <T> List<T> getListFromTracker(ServiceTracker tracker) {
        tracker.open();
        Object[] services = tracker.getServices();
        List<T> result = new ArrayList<T>();
        if (services != null) {
            CollectionUtils.addAll(result, services);
        }
        tracker.close();
        return result;
    }

    @Override
    public <T> List<T> listServices(Class<T> clazz, String filterString) throws IllegalArgumentException {
        Filter filter = FilterUtils.makeFilter(clazz, filterString);
        ServiceTracker tracker = new ServiceTracker(bundleContext, filter, null);
        return getListFromTracker(tracker);
    }

    @Override
    public <T> Iterator<T> getServiceIterator(Iterable<ServiceReference<T>> references) {
        return Iterators.transform(references.iterator(), new Function<ServiceReference<T>, T>() {
            @Override
            public T apply(ServiceReference<T> input) {
                return bundleContext.getService(input);
            }
        });
    }

    @Override
    public <T> Iterator<T> getServiceIterator(Iterable<ServiceReference> references, Class<T> serviceType) {
        return Iterators.transform(references.iterator(), new Function<ServiceReference, T>() {
            @Override
            public T apply(ServiceReference input) {
                return (T) bundleContext.getService(input);
            }
        });
    }

    /**
     * Any bundle-context is fine here, since it does not matter from which bundlecontext services are retrieved.
     */
    public void setBundleContext(BundleContext bundleContext) {
        this.bundleContext = bundleContext;
    }
}


text:
<?php

namespace TCG\Voyager\Http\Controllers;

use Illuminate\Http\Request;
use TCG\Voyager\Facades\Voyager;

class VoyagerRoleController extends VoyagerBreadController
{
    // POST BR(E)AD
    public function update(Request $request, $id)
    {
        Voyager::canOrFail('edit_roles');

        $slug = $this->getSlug($request);

        $dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();

        $data = call_user_func([$dataType->model_name, 'findOrFail'], $id);
        $this->insertUpdateData($request, $slug, $dataType->editRows, $data);

        $data->permissions()->sync($request->input('permissions', []));

        return redirect()
            ->route("voyager.{$dataType->slug}.index")
            ->with([
                'message'    => "Successfully Updated {$dataType->display_name_singular}",
                'alert-type' => 'success',
            ]);
    }

    // POST BRE(A)D
    public function store(Request $request)
    {
        Voyager::canOrFail('add_roles');

        $slug = $this->getSlug($request);

        $dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();

        $data = new $dataType->model_name();
        $this->insertUpdateData($request, $slug, $dataType->addRows, $data);

        $data->permissions()->sync($request->input('permissions', []));

        return redirect()
            ->route("voyager.{$dataType->slug}.index")
            ->with([
                'message'    => "Successfully Added New {$dataType->display_name_singular}",
                'alert-type' => 'success',
            ]);
    }
}


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.
 */
package com.facebook.presto.example;

import com.google.common.collect.ImmutableMap;
import io.airlift.configuration.testing.ConfigAssertions;
import org.testng.annotations.Test;

import java.net.URI;
import java.util.Map;

public class TestExampleConfig
{
    @Test
    public void testDefaults()
    {
        ConfigAssertions.assertRecordedDefaults(ConfigAssertions.recordDefaults(LuceneConfig.class)
                .setMetadata(null));
    }

    @Test
    public void testExplicitPropertyMappings()
    {
        Map<String, String> properties = new ImmutableMap.Builder<String, String>()
                .put("metadata-uri", "file://test.json")
                .build();

        LuceneConfig expected = new LuceneConfig()
                .setMetadata(URI.create("file://test.json"));

        ConfigAssertions.assertFullMapping(properties, expected);
    }
}


text:
// -*- c++ -*-

#include "Index.h"
#include "common/logging.h"
#include <cstring>

namespace faiss {

Index::~Index ()
{
}

void Index::train(idx_t /*n*/, const float* /*x*/) {
    // does nothing by default
}

void Index::range_search (idx_t , const float *, float,
                          RangeSearchResult *) const
{
  ABORT ("range search not implemented");
}

void Index::assign (idx_t n, const float * x, idx_t * labels, idx_t k)
{
  float * distances = new float[n * k];
  ScopeDeleter<float> del(distances);
  search (n, x, k, distances, labels);
}

void Index::add_with_ids(
    idx_t /*n*/,
    const float* /*x*/,
    const idx_t* /*xids*/) {
  ABORT ("add_with_ids not implemented for this type of index");
}

size_t Index::remove_ids(const IDSelector& /*sel*/) {
  ABORT ("remove_ids not implemented for this type of index");
  return -1;
}

void Index::reconstruct (idx_t, float * ) const {
  ABORT ("reconstruct not implemented for this type of index");
}

void Index::reconstruct_n (idx_t i0, idx_t ni, float *recons) const {
  for (idx_t i = 0; i < ni; i++) {
    reconstruct (i0 + i, recons + i * d);
  }
}

void Index::search_and_reconstruct (idx_t n, const float *x, idx_t k,
                                    float *distances, idx_t *labels,
                                    float *recons) const {
  search (n, x, k, distances, labels);
  for (idx_t i = 0; i < n; ++i) {
    for (idx_t j = 0; j < k; ++j) {
      idx_t ij = i * k + j;
      idx_t key = labels[ij];
      float* reconstructed = recons + ij * d;
      if (key < 0) {
        // Fill with NaNs
        memset(reconstructed, -1, sizeof(*reconstructed) * d);
      } else {
        reconstruct (key, reconstructed);
      }
    }
  }
}

void Index::compute_residual (const float * x,
                              float * residual, idx_t key) const {
  reconstruct (key, residual);
  for (size_t i = 0; i < d; i++) {
    residual[i] = x[i] - residual[i];
  }
}

void Index::compute_residual_n (idx_t n, const float* xs,
                                float* residuals,
                                const idx_t* keys) const {
//#pragma omp parallel for
  for (idx_t i = 0; i < n; ++i) {
    compute_residual(&xs[i * d], &residuals[i * d], keys[i]);
  }
}

size_t Index::sa_code_size () const
{
    ABORT ("standalone codec not implemented for this type of index");
}

void Index::sa_encode (idx_t, const float *,
                             uint8_t *) const
{
    ABORT ("standalone codec not implemented for this type of index");
}

void Index::sa_decode (idx_t, const uint8_t *,
                            float *) const
{
    ABORT ("standalone codec not implemented for this type of index");
}

}


text:
import collections
from datetime import timedelta

from django.contrib.auth.models import User
from django.db import models
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill, Adjust

from gatherings.conference.managers import SessionManager
from gatherings.conference.constants import (SESSION_TYPE_TALK,
        SESSION_TYPE_LIGHTNING_TALK, SESSION_TYPE_BREAK, SESSION_TYPE_CHOICES,
        SESSION_STATUS_DRAFT, SESSION_STATUS_PUBLISHED, SESSION_STATUS_CHOICES)

class Event(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField(null=True)
    start = models.DateTimeField()
    end = models.DateTimeField()

    def __unicode__(self):
        return self.name

    def get_datetimes(self):
        return [self.start + timedelta(days=x) for x in range(0,
            (self.end.date() - self.start.date()).days + 1)]

    @property
    def sessions_by_days_struct(self):
        sessions = collections.OrderedDict()
        for dt in self.get_datetimes():
            sessions[dt] = self.session_set.filter(
                status=SESSION_STATUS_PUBLISHED,
                start__startswith=dt.date()).order_by('start')
        return sessions

class Track(models.Model):
    name = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name

class Room(models.Model):
    name = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name

class Session(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
    event = models.ForeignKey('Event')
    room = models.ForeignKey('Room', null=True, blank=True)
    speakers = models.ManyToManyField('Speaker', null=True, blank=True)
    session_type = models.IntegerField(default=SESSION_TYPE_TALK,
                                       choices=SESSION_TYPE_CHOICES)
    status = models.IntegerField(default=SESSION_STATUS_DRAFT,
                                 choices=SESSION_STATUS_CHOICES)
    start = models.DateTimeField(null=True, blank=True)
    end = models.DateTimeField(null=True, blank=True)

    objects = SessionManager()

    def __unicode__(self):
        return self.name

    @property
    def is_break(self):
        return self.session_type == SESSION_TYPE_BREAK

    @property
    def is_talk(self):
        return self.session_type == SESSION_TYPE_TALK

    @property
    def is_lightning_talk(self):
        return self.session_type == SESSION_TYPE_LIGHTNING_TALK

    @property
    def is_published(self):
        return self.status == SESSION_STATUS_PUBLISHED

class Speaker(models.Model):
    bio = models.TextField()
    user = models.ForeignKey(User, null=True, blank=True)
    tags = models.ManyToManyField('SpeakerTag', null=True, blank=True)
    image = models.ImageField(upload_to='speaker_images', null=True, blank=True)
    image_thumbnail = ImageSpecField([Adjust(contrast=1.2, sharpness=1.1),
                                     ResizeToFill(130, 130)],
                                     image_field='image',
                                     format='PNG',
                                     options={'quality': 90})
    events = models.ManyToManyField('Event', null=True, blank=True)

    @property
    def full_name(self):
        return '{first_name} {last_name}'.format(
            first_name=self.user.first_name, last_name=self.user.last_name)

    def __unicode__(self):
        return self.full_name

class SpeakerTag(models.Model):

    name = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name


text:
from mbuild.tests.base_test import BaseTest

class TestExamples(BaseTest):

    def test_alkane(self):
        import mbuild.examples.alkane.alkane as example
        example.main()

    def test_alkane_monolayer(self):
        import mbuild.examples.alkane_monolayer.alkane_monolayer as example
        example.main()

    def test_bilayer(self):
        import mbuild.examples.bilayer.bilayer as example
        example.main()

    def test_ethane(self):
        import mbuild.examples.ethane.ethane as example
        ethane = example.main()
        assert ethane.n_particles == 8
        assert ethane.n_bonds == 7

    def test_methane(self):
        import mbuild.examples.methane.methane as example
        methane = example.main()

        assert len(methane.children) == 5
        assert methane.n_particles == 5

        assert len(methane.bond_graph) == 5
        assert methane.n_bonds == 4

        assert next(methane.particles()).name == 'C'
        assert methane[0].name == 'C'
        assert (methane[1].name == methane[2].name ==
                methane[3].name == methane[4].name == "H")

    def test_pmpc(self):
        import mbuild.examples.pmpc.pmpc_brush_layer as example
        example.main()

    def test_reload(self):
        import mbuild.examples.reload.reload as example
        example.main()

    def test_solvate(self):
        import mbuild.examples.solvate.solvate as example
        example.main()

    def test_tnp(self):
        import mbuild.examples.tnp.tnp as example
        example.main()

    def test_tnp_box(self):
        import mbuild.examples.tnp.tnp_box as example
        example.main()