text:
//@file update.h

#include "mongo/pch.h"

#include "mongo/db/jsobj.h"
#include "mongo/db/curop.h"
#include "mongo/db/query_plan_selection_policy.h"

namespace mongo {

    // ---------- public -------------

    struct UpdateResult {
        const bool existing; // if existing objects were modified
        const bool mod;      // was this a $ mod
        const long long num; // how many objects touched
        OID upserted;  // if something was upserted, the new _id of the object

        UpdateResult( bool e, bool m, unsigned long long n , const BSONObj& upsertedObject )
            : existing(e) , mod(m), num(n) {
            upserted.clear();
            BSONElement id = upsertedObject["_id"];
            if ( ! e && n == 1 && id.type() == jstOID ) {
                upserted = id.OID();
            }
        }
    };

    class RemoveSaver;

    /* returns true if an existing object was updated, false if no existing object was found.
       multi - update multiple objects - mostly useful with things like $set
       su - allow access to system namespaces (super user)
    */
    UpdateResult updateObjects(const char* ns,
                               const BSONObj& updateobj,
                               const BSONObj& pattern,
                               bool upsert,
                               bool multi,
                               bool logop,
                               OpDebug& debug,
                               bool fromMigrate = false,
                               const QueryPlanSelectionPolicy& planPolicy = QueryPlanSelectionPolicy::any());

    /*
     * Similar to updateObjects but not strict about applying mods that can fail during initial
     * replication.
     *
     * Reference ticket: SERVER-4781
     */
    UpdateResult updateObjectsForReplication(const char* ns,
                                             const BSONObj& updateobj,
                                             const BSONObj& pattern,
                                             bool upsert,
                                             bool multi,
                                             bool logop,
                                             OpDebug& debug,
                                             bool fromMigrate = false,
                                             const QueryPlanSelectionPolicy& planPolicy =
                                                 QueryPlanSelectionPolicy::any());

    UpdateResult _updateObjects(bool su,
                                const char* ns,
                                const BSONObj& updateobj,
                                const BSONObj& pattern,
                                bool upsert,
                                bool multi,
                                bool logop,
                                OpDebug& debug,
                                RemoveSaver* rs = 0,
                                bool fromMigrate = false,
                                const QueryPlanSelectionPolicy& planPolicy = QueryPlanSelectionPolicy::any(),
                                bool forReplication = false);

    /**
     * takes the from document and returns a new document
     * after apply all the operators
     * e.g.
     *   applyUpdateOperators( BSON( "x" << 1 ) , BSON( "$inc" << BSON( "x" << 1 ) ) );
     *   returns: { x : 2 }
     */
    BSONObj applyUpdateOperators( const BSONObj& from, const BSONObj& operators );

}  // namespace mongo


text:
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

module.exports = function (Cmp) {
    return function (_Cmp) {
        _inherits(DefaultCheckedCmp, _Cmp);

        function DefaultCheckedCmp(props) {
            _classCallCheck(this, DefaultCheckedCmp);

            return _possibleConstructorReturn(this, (DefaultCheckedCmp.__proto__ || Object.getPrototypeOf(DefaultCheckedCmp)).call(this, props));
        }

        _createClass(DefaultCheckedCmp, [{
            key: 'componentWillReceiveProps',
            value: function componentWillReceiveProps(nextProps) {
                var _this2 = this;

                if (_get(DefaultCheckedCmp.prototype.__proto__ || Object.getPrototypeOf(DefaultCheckedCmp.prototype), 'componentWillReceiveProps', this)) {
                    _get(DefaultCheckedCmp.prototype.__proto__ || Object.getPrototypeOf(DefaultCheckedCmp.prototype), 'componentWillReceiveProps', this).call(this, nextProps);
                }

                if (this.props.value !== nextProps.value && ['', [], undefined, null].indexOf(nextProps.value) === -1) {
                    this.setState({
                        value: nextProps.value
                    }, function () {
                        return _this2.props.onChange(_this2.state.value);
                    });
                }
            }
        }, {
            key: 'optionsChangeReInitValue',
            value: function optionsChangeReInitValue(_ref) {
                var _this3 = this;

                var defaultChecked = _ref.defaultChecked,
                    multi = _ref.multi,
                    nextProps = _ref.nextProps;
                var _props = this.props,
                    value = _props.value,
                    valueName = _props.valueName,
                    onChange = _props.onChange;

                if (nextProps.options !== this.props.options) {
                    // re-init value if value exist, but not fit options value
                    if (['', [], undefined, null].indexOf(value) === -1) {
                        var newOptions = nextProps.options;
                        for (var i = 0; i < newOptions.length; i++) {
                            if (multi) {
                                if (value.indexOf(newOptions[i][valueName]) !== -1) {
                                    return;
                                }
                            } else {
                                if (newOptions[i][valueName] === value) {
                                    return;
                                }
                            }
                        }
                    }

                    if (defaultChecked) {
                        this.initDefaultCheckedValue({
                            multi: multi,
                            props: nextProps
                        });
                    } else {
                        this.setState({
                            value: multi ? [] : ''
                        }, function () {
                            return onChange(_this3.state.value);
                        });
                    }
                }
            }
        }, {
            key: 'initDefaultCheckedValue',
            value: function initDefaultCheckedValue() {
                var _this4 = this;

                var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { multi: false },
                    multi = _ref2.multi,
                    props = _ref2.props;

                var _ref3 = props || this.props,
                    valueName = _ref3.valueName,
                    options = _ref3.options,
                    onChange = _ref3.onChange,
                    children = _ref3.children;

                var initVal = multi ? [] : '';
                if (options && options.length > 0) {
                    initVal = options[0][valueName];
                }
                if (children && children.length > 0) {
                    initVal = children[0].props[valueName];
                }
                this.setState({
                    value: multi ? [initVal] : initVal
                }, function () {
                    return onChange(_this4.state.value);
                });
            }
        }]);

        return DefaultCheckedCmp;
    }(Cmp);
};

redpajama_set_name: RedPajamaGithub


text:
ul.jqtree-tree {
    margin-left: 12px;
    font-size: 14px !important;
}

ul.jqtree-tree li span.jqtree-title:hover {
    text-decoration: underline;
}

ul.jqtree-tree,
ul.jqtree-tree ul {
    list-style: none outside !important;
    margin-bottom: 0;
    padding: 0;
}

ul.jqtree-tree ul {
    display: block;
    margin-left: 12px !important;
    margin-right: 0;
}

ul.jqtree-tree li.jqtree-closed > ul {
    display: none;
}

ul.jqtree-tree li {
    clear: both;
}

ul.jqtree-tree .jqtree-toggler {
    background-image: url(/assets/bizarre_cms/jqtree-icons.png);
    background-repeat: no-repeat;
    background-position: -8px 0;
    width: 8px;
    height: 8px;
    display: block;
    position: absolute;
    left: -12px;
    top: 30%;
    text-indent: -9999px;
    border-bottom: none;
}

ul.jqtree-tree div {
    cursor: pointer;
}

ul.jqtree-tree .jqtree-title {
    color: #1C4257;
    vertical-align: middle;
}

ul.jqtree-tree li.jqtree-folder {
    margin-bottom: 4px;
}

ul.jqtree-tree li.jqtree-folder.jqtree-closed {
    margin-bottom: 1px;
}

ul.jqtree-tree li.jqtree-folder .jqtree-title {
    margin-left: 0;
}

ul.jqtree-tree .jqtree-toggler.jqtree-closed {
    background-position: 0 0;
}

span.jqtree-dragging {
    color: #fff;
    background: #000;
    opacity: 0.6;
    cursor: pointer;
    padding: 2px 8px;
}

ul.jqtree-tree li.jqtree-ghost {
    position: relative;
    z-index: 10;
    margin-right: 10px;
}

ul.jqtree-tree li.jqtree-ghost span {
    display: block;
}

ul.jqtree-tree li.jqtree-ghost span.jqtree-circle {
    background-image: url(/assets/bizarre_cms/jqtree-icons.png);
    background-repeat: no-repeat;
    background-position: 0 -8px;
    height: 8px;
    width: 8px;
    position: absolute;
    top: -4px;
    left: 2px;
}

ul.jqtree-tree li.jqtree-ghost span.jqtree-line {
    background-color: #0000ff;
    height: 2px;
    padding: 0;
    position: absolute;
    top: -1px;
    left: 10px;
    width: 100%;
}

ul.jqtree-tree li.jqtree-ghost.jqtree-inside {
    margin-left: 48px;
}

ul.jqtree-tree span.jqtree-border {
    position: absolute;
    display: block;
    left: -2px;
    top: 0;
    border: solid 2px #0000ff;
    -webkit-border-radius: 6px;
    -moz-border-radius: 6px;
    border-radius: 6px;
    margin: 0;
}

ul.jqtree-tree div {
    width: 100%; /* todo: why is this in here? */
    *width: auto; /* ie7 fix; issue 41 */
    position: relative;
}

ul.jqtree-tree li.jqtree-selected > div,
ul.jqtree-tree li.jqtree-selected > div:hover {
    background-color: #97BDD6;
    background: -webkit-gradient(linear, left top, left bottom, from(#BEE0F5), to(#89AFCA));
    background: -moz-linear-gradient(top, #BEE0F5, #89AFCA);
    background: -ms-linear-gradient(top, #BEE0F5, #89AFCA);
    background: -o-linear-gradient(top, #BEE0F5, #89AFCA);
    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.7);
}

ul.jqtree-tree .jqtree-moving > div .jqtree-title {
    outline: dashed 1px #0000ff;
}


text:
class Show < ActiveRecord::Base
  has_many :episodes

  validates :description, presence: true
  validates :email, presence: true
  validates :itunes_url, presence: true
  validates :keywords, presence: true
  validates :short_description, presence: true
  validates :slug, presence: true
  validates :title, presence: true

  def to_param
    slug
  end

  def short_title
    title.split.first(2).join(' ')
  end
end


text:
'use strict';

const HTTP = require('http');

/**
 * Wrap a HTTP request in a Promise
 * @param {string} hostname
 * @param {Number} port
 * @param {string} path - request URI
 * @param {string} method - HTTP request method
 * @param {Object} [body] - Body to be sent with request
 * @param {Object} [headers] - Headers to be sent with request
 * @return {Promise}
 */
function send(hostname, port, path, method, body, headers) {
  body = body || {};
  headers = headers || {};

  return new Promise((resolve, reject) => {
    const request = new Buffer(JSON.stringify(body, null, 2));

    const req = HTTP.request({
      hostname,
      port,
      method,
      path,
      headers: Object.assign(headers, {'content-length': request.length})
    });

    const chunks = [];

    req.on('response', function(res) {
      res.on('end', function ended(chunk) {
        if (chunk) {
          chunks.push(chunk);
        }
        try {
          const response = JSON.parse(Buffer.concat(chunks)
              .toString('utf8'));

          resolve(response);
        } catch (e) {
          reject(e);
        }
      });
      res.on('data', (chunk) => chunks.push(chunk));
    });

    req.on('error', (err) => reject(err));

    req.write(request);
    req.end();
  });
}

/* eslint-disable no-unused-vars */
/**
 * Send a request to a Vault endpoint
 * @param {Object} vault - Vault config object
 * @param {string} path - request URI
 * @param {string} method - HTTP request method
 * @param {Object} [body] - Body to be sent with request
 * @param {Object} [data] - arbitrary data to send (implementation TBD)
 * @return {Promise}
 */
function vaultRequest(vault, path, method, body, data) {
  body = body || {};
  data = data || {};

  return send(vault.hostname, vault.port, path, method, body, {
    'X-Vault-Token': vault.token
  });
}

module.exports = {
  vaultRequest,
  send
};


text:
(function(root, factory) {
    'use strict';
    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.

    /* istanbul ignore next */
    if (typeof define === 'function' && define.amd) {
        define('stacktrace', ['error-stack-parser', 'stack-generator', 'stacktrace-gps'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory(require('error-stack-parser'), require('stack-generator'), require('stacktrace-gps'));
    } else {
        root.StackTrace = factory(root.ErrorStackParser, root.StackGenerator, root.StackTraceGPS);
    }
}(this, function StackTrace(ErrorStackParser, StackGenerator, StackTraceGPS) {
    var _options = {
        filter: function(stackframe) {
            // Filter out stackframes for this library by default
            return (stackframe.functionName || '').indexOf('StackTrace$$') === -1 &&
                (stackframe.functionName || '').indexOf('ErrorStackParser$$') === -1 &&
                (stackframe.functionName || '').indexOf('StackTraceGPS$$') === -1 &&
                (stackframe.functionName || '').indexOf('StackGenerator$$') === -1;
        },
        sourceCache: {}
    };

    /**
     * Merge 2 given Objects. If a conflict occurs the second object wins.
     * Does not do deep merges.
     *
     * @param {Object} first base object
     * @param {Object} second overrides
     * @returns {Object} merged first and second
     * @private
     */
    function _merge(first, second) {
        var target = {};

        [first, second].forEach(function(obj) {
            for (var prop in obj) {
                if (obj.hasOwnProperty(prop)) {
                    target[prop] = obj[prop];
                }
            }
            return target;
        });

        return target;
    }

    function _isShapedLikeParsableError(err) {
        return err.stack || err['opera#sourceloc'];
    }

    return {
        /**
         * Get a backtrace from invocation point.
         *
         * @param {Object} opts
         * @returns {Array} of StackFrame
         */
        get: function StackTrace$$get(opts) {
            try {
                // Error must be thrown to get stack in IE
                throw new Error();
            } catch (err) {
                if (_isShapedLikeParsableError(err)) {
                    return this.fromError(err, opts);
                } else {
                    return this.generateArtificially(opts);
                }
            }
        },

        /**
         * Given an error object, parse it.
         *
         * @param {Error} error object
         * @param {Object} opts
         * @returns {Promise} for Array[StackFrame}
         */
        fromError: function StackTrace$$fromError(error, opts) {
            opts = _merge(_options, opts);
            var gps = new StackTraceGPS(opts);
            return new Promise(function(resolve) {
                var stackframes = ErrorStackParser.parse(error);
                if (typeof opts.filter === 'function') {
                    stackframes = stackframes.filter(opts.filter);
                }
                resolve(Promise.all(stackframes.map(function(sf) {
                    return new Promise(function(resolve) {
                        function resolveOriginal() {
                            resolve(sf);
                        }

                        gps.pinpoint(sf).then(resolve, resolveOriginal)['catch'](resolveOriginal);
                    });
                })));
            }.bind(this));
        },

        /**
         * Use StackGenerator to generate a backtrace.
         *
         * @param {Object} opts
         * @returns {Promise} of Array[StackFrame]
         */
        generateArtificially: function StackTrace$$generateArtificially(opts) {
            opts = _merge(_options, opts);
            var stackFrames = StackGenerator.backtrace(opts);
            if (typeof opts.filter === 'function') {
                stackFrames = stackFrames.filter(opts.filter);
            }
            return Promise.resolve(stackFrames);
        },

        /**
         * Given a function, wrap it such that invocations trigger a callback that
         * is called with a stack trace.
         *
         * @param {Function} fn to be instrumented
         * @param {Function} callback function to call with a stack trace on invocation
         * @param {Function} errback optional function to call with error if unable to get stack trace.
         * @param {Object} thisArg optional context object (e.g. window)
         */
        instrument: function StackTrace$$instrument(fn, callback, errback, thisArg) {
            if (typeof fn !== 'function') {
                throw new Error('Cannot instrument non-function object');
            } else if (typeof fn.__stacktraceOriginalFn === 'function') {
                // Already instrumented, return given Function
                return fn;
            }

            var instrumented = function StackTrace$$instrumented() {
                try {
                    this.get().then(callback, errback)['catch'](errback);
                    return fn.apply(thisArg || this, arguments);
                } catch (e) {
                    if (_isShapedLikeParsableError(e)) {
                        this.fromError(e).then(callback, errback)['catch'](errback);
                    }
                    throw e;
                }
            }.bind(this);
            instrumented.__stacktraceOriginalFn = fn;

            return instrumented;
        },

        /**
         * Given a function that has been instrumented,
         * revert the function to it's original (non-instrumented) state.
         *
         * @param {Function} fn to de-instrument
         */
        deinstrument: function StackTrace$$deinstrument(fn) {
            if (typeof fn !== 'function') {
                throw new Error('Cannot de-instrument non-function object');
            } else if (typeof fn.__stacktraceOriginalFn === 'function') {
                return fn.__stacktraceOriginalFn;
            } else {
                // Function not instrumented, return original
                return fn;
            }
        },

        /**
         * Given an Array of StackFrames, serialize and POST to given URL.
         *
         * @param {Array} stackframes
         * @param {String} url
         */
        report: function StackTrace$$report(stackframes, url) {
            return new Promise(function(resolve, reject) {
                var req = new XMLHttpRequest();
                req.onerror = reject;
                req.onreadystatechange = function onreadystatechange() {
                    if (req.readyState === 4) {
                        if (req.status >= 200 && req.status < 400) {
                            resolve(req.responseText);
                        } else {
                            reject(new Error('POST to ' + url + ' failed with status: ' + req.status));
                        }
                    }
                };
                req.open('post', url);
                req.setRequestHeader('Content-Type', 'application/json');
                req.send(JSON.stringify({stack: stackframes}));
            });
        }
    };
}));


text:
import classnames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';

import styles from './Section.less';
import getTenant from '../private/tenant';
import { StyleGuideContext } from '../StyleGuideProvider/StyleGuideProvider';

export const TONE = {
  POSITIVE: 'positive',
  INFO: 'info',
  CRITICAL: 'critical',
  HELP: 'help'
};

export const LEVEL = {
  PRIMARY: 'primary',
  SECONDARY: 'secondary',
  TERTIARY: 'tertiary'
};

export default function Section({
  children,
  className,
  header,
  pullout,
  slim,
  tone,
  level,
  ...restProps
}) {
  return (
    <StyleGuideContext.Consumer>
      {({ tenant }) => {
        const { isJobsDB, isJobStreet } = getTenant(tenant);
        const classesName = classnames({
          [className]: className,
          [styles.root]: true,
          [styles.header]: header,
          [styles.pullout]: pullout,
          [styles.slim]: slim,
          [styles[tone]]: tone,
          [styles[level]]: level,
          [styles.jobsDB]: isJobsDB,
          [styles.jobStreet]: isJobStreet
        });
        return (<div
          {...restProps}
          className={classesName}>
          {children}
        </div>);
      }}
    </StyleGuideContext.Consumer>
  );
}

Section.propTypes = {
  children: PropTypes.node.isRequired,
  className: PropTypes.string,
  header: PropTypes.bool,
  pullout: PropTypes.bool,
  slim: PropTypes.bool,
  tone: PropTypes.oneOf([TONE.POSITIVE, TONE.INFO, TONE.CRITICAL, TONE.HELP]),
  level: PropTypes.oneOf([LEVEL.PRIMARY, LEVEL.SECONDARY])
};

Section.defaultProps = {
  className: '',
  header: false,
  pullout: false,
  slim: false
};


text:
/* Author: pupius@google.com (Daniel Pupius) */

/*
 * goog.ui.Menu
 */

/* State: resting. */
.goog-menu {
  background-color: #fff;
  border-color: #ccc #666 #666 #ccc;
  border-style: solid;
  border-width: 1px;
  cursor: default;
  margin: 0;
  outline: none;
  padding: 4px 0;
  position: absolute;
}

/*
 * goog.ui.MenuItem
 */

/* State: resting. */
.goog-menuitem {
  color: #000;
  font: normal 12px Arial, sans-serif;
  list-style: none;
  margin: 0;
  /* 28px on the left for icon or checkbox; 10ex on the right for shortcut. */
  padding: 4px 10ex 4px 28px;
  white-space: nowrap;
}

/* BiDi override for the resting state. */
.goog-menuitem-rtl {
  /* Flip left/right padding for BiDi. */
  padding: 4px 28px 4px 10ex !important;
}

/* State: disabled. */
.goog-menuitem-disabled {
  color: #ccc;
}

/* State: hover. */
.goog-menuitem-highlight,
.goog-menuitem-hover {
  background-color: #d6e9f8;
}

/* State: selected/checked. */
.goog-menuitem-checkbox,
.goog-menuitem-icon {
  height: 16px;
  left: 6px;
  position: absolute;
  width: 16px;
}
.goog-option-selected .goog-menuitem-checkbox,
.goog-option-selected .goog-menuitem-icon {
  background: transparent url(../images/check.gif) no-repeat center center;
}

/* BiDi override for the selected/checked state. */
.goog-menuitem-rtl .goog-menuitem-checkbox,
.goog-menuitem-rtl .goog-menuitem-icon {
  /* Flip left/right positioning. */
  right: 6px;
  left: auto;
}

/* Keyboard shortcut ("accelerator") style. */
.goog-menuitem-accel {
  color: #999;
  padding: 0 6px;
  position: absolute;
  right: 0;
  text-align: right;
}

/* BiDi override for shortcut style. */
.goog-menuitem-rtl .goog-menuitem-accel {
  /* Flip left/right positioning and text alignment. */
  left: 0;
  right: auto;
  text-align: left;
}

/*
 * goog.ui.MenuSeparator
 */

/* State: resting. */
.goog-menuseparator {
  border-top: 1px solid #ccc;
  margin: 4px 0;
  padding: 0;
  position: relative;
}

/* goog.ui.SubMenu */

.goog-submenu-arrow {
  text-align: right;
  position: absolute;
  right: 0;
  left: auto;
}

.goog-menuitem-rtl .goog-submenu-arrow {
  text-align: left;
  position: absolute;
  left: 0;
  right: auto;
}

.goog-menuitem-disabled .goog-submenu-arrow {
  display: none;
}

/* goog.ui.FilteredMenu */

.goog-menu-filter {
  margin: 2px;
  border: 1px solid silver;
  background: white;
  overflow: hidden;
}

.goog-menu-filter div {
  color: gray;
  position: absolute;
  padding: 1px;
}

.goog-menu-filter input {
  margin: 0;
  border: 0;
  background: transparent;
  width: 100%;
}

/* goog.ui.TriStateMenuItem */

.goog-tristatemenuitem {
  padding: 2px 5px;
  margin: 0;
  list-style: none;
}

.goog-tristatemenuitem-highlight {
  background-color: #4279A5;
  color: #FFF;
}

.goog-tristatemenuitem-disabled {
  color: #999;
}

.goog-tristatemenuitem-checkbox {
  float: left;
  width: 10px;
  height: 1.1em;
}

.goog-tristatemenuitem-partially-checked {
  background-image: url(../images/check-outline.gif);
  background-position: 4px 50%;
  background-repeat: no-repeat;
}

.goog-tristatemenuitem-fully-checked {
  background-image: url(../images/check.gif);
  background-position: 4px 50%;
  background-repeat: no-repeat;
}

/* goog.ui.FilterObservingMenuItem */

.goog-filterobsmenuitem {
  padding: 2px 5px;
  margin: 0;
  list-style: none;
}

.goog-filterobsmenuitem-highlight {
  background-color: #4279A5;
  color: #FFF;
}

.goog-filterobsmenuitem-disabled {
  color: #999;
}


text:
alter table sg_football_bet add (
    bet_date                    date
    , bet_odds_risk_value       number
);

alter table sg_football_bet add constraint football_bet_date_nn check (bet_date is not null);

alter table strategy_positional_attributes add (
    risk_acceptance_level       number
);


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BezierCurve.cs" company="Exit Games GmbH">
//   Part of: Photon Unity Networking Demos
// </copyright>
// <summary>
//  Original: http://catlikecoding.com/unity/tutorials/curves-and-splines/
//  Used in SlotRacer Demo
// </summary>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------

using UnityEngine;

namespace Photon.Pun.Demo.SlotRacer.Utils
{
	public class BezierCurve : MonoBehaviour
	{
		public Vector3[] points;

		public Vector3 GetPoint (float t)
		{
			return transform.TransformPoint(Bezier.GetPoint(points[0], points[1], points[2], points[3], t));
		}

		public Vector3 GetVelocity (float t)
		{
			return transform.TransformPoint(Bezier.GetFirstDerivative(points[0], points[1], points[2], points[3], t)) - transform.position;
		}

		public Vector3 GetDirection (float t)
		{
			return GetVelocity(t).normalized;
		}

		public void Reset ()
		{
			points = new Vector3[] {
				new Vector3(1f, 0f, 0f),
				new Vector3(2f, 0f, 0f),
				new Vector3(3f, 0f, 0f),
				new Vector3(4f, 0f, 0f)
			};
		}
	}
}


text:
package com.reactnativenavigation.react;

import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.reactnativenavigation.views.element.Element;

import static com.reactnativenavigation.utils.UiUtils.runOnPreDrawOnce;
import static com.reactnativenavigation.utils.ViewUtils.performOnParentReactView;

public class ElementViewManager extends ViewGroupManager<Element> {

    @Override
    public String getName() {
        return "RNNElement";
    }

    @Override
    protected Element createViewInstance(ThemedReactContext reactContext) {
        Element element = createView(reactContext);
        register(element);
        return element;
    }

    public Element createView(ThemedReactContext reactContext) {
        return new Element(reactContext);
    }

    @Override
    public void onDropViewInstance(Element element) {
        super.onDropViewInstance(element);
        unregister(element);
    }

    @ReactProp(name = "elementId")
    public void setElementId(Element element, String id) {
        element.setElementId(id);
    }

    @Override
    public boolean needsCustomLayoutForChildren() {
        return true;
    }

    private void register(Element element) {
        runOnPreDrawOnce(element, () -> performOnParentReactView(element, (parent) -> parent.registerElement(element)));
    }

    private void unregister(Element element) {
        performOnParentReactView(element, (parent) -> parent.unregisterElement(element));
    }
}


text:
package com.coolweather.anrdoid.db;

import org.litepal.crud.DataSupport;

/**
 * Created by Hasee on 2017/10/4/0004.
 */

public class City extends DataSupport {
    private int id;
    private String cityName;
    private int provinceId;
    int cityCode;

    public int getCityCode() {
        return cityCode;
    }

    public void setCityCode(int cityCode) {
        this.cityCode = cityCode;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public int getProvinceId() {
        return provinceId;
    }

    public void setProvinceId(int provinceId) {
        this.provinceId = provinceId;
    }
}


text:
<title>dlib C++ Library - getrf.h</title>

// Copyright (C) 2010  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_LAPACk_GETRF_H__
#define DLIB_LAPACk_GETRF_H__

#include "fortran_id.h"
#include "../matrix.h"

namespace dlib
{
    namespace lapack
    {
        namespace binding
        {
            extern "C"
            {
                void DLIB_FORTRAN_ID(dgetrf) (integer* m, integer *n, double *a,
                                             integer* lda, integer *ipiv, integer *info);

                void DLIB_FORTRAN_ID(sgetrf) (integer* m, integer *n, float *a,
                                             integer* lda, integer *ipiv, integer *info);

            }

            inline int getrf (integer m, integer n, double *a,
                              integer lda, integer *ipiv)
            {
                integer info = 0;
                DLIB_FORTRAN_ID(dgetrf)(&m, &n, a, &lda, ipiv, &info);
                return info;
            }

            inline int getrf (integer m, integer n, float *a,
                              integer lda, integer *ipiv)
            {
                integer info = 0;
                DLIB_FORTRAN_ID(sgetrf)(&m, &n, a, &lda, ipiv, &info);
                return info;
            }

        }

    // ------------------------------------------------------------------------------------

/*  -- LAPACK routine (version 3.1) -- */
/*     Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/*     November 2006 */

/*     .. Scalar Arguments .. */
/*     .. */
/*     .. Array Arguments .. */
/*     .. */

/*  Purpose */
/*  ======= */

/*  DGETRF computes an LU factorization of a general M-by-N matrix A */
/*  using partial pivoting with row interchanges. */

/*  The factorization has the form */
/*     A = P * L * U */
/*  where P is a permutation matrix, L is lower triangular with unit */
/*  diagonal elements (lower trapezoidal if m > n), and U is upper */
/*  triangular (upper trapezoidal if m < n). */

/*  This is the right-looking Level 3 BLAS version of the algorithm. */

/*  Arguments */
/*  ========= */

/*  M       (input) INTEGER */
/*          The number of rows of the matrix A.  M >= 0. */

/*  N       (input) INTEGER */
/*          The number of columns of the matrix A.  N >= 0. */

/*  A       (input/output) DOUBLE PRECISION array, dimension (LDA,N) */
/*          On entry, the M-by-N matrix to be factored. */
/*          On exit, the factors L and U from the factorization */
/*          A = P*L*U; the unit diagonal elements of L are not stored. */

/*  LDA     (input) INTEGER */
/*          The leading dimension of the array A.  LDA >= max(1,M). */

/*  IPIV    (output) INTEGER array, dimension (min(M,N)) */
/*          The pivot indices; for 1 <= i <= min(M,N), row i of the */
/*          matrix was interchanged with row IPIV(i). */

/*  INFO    (output) INTEGER */
/*          = 0:  successful exit */
/*          < 0:  if INFO = -i, the i-th argument had an illegal value */
/*          > 0:  if INFO = i, U(i,i) is exactly zero. The factorization */
/*                has been completed, but the factor U is exactly */
/*                singular, and division by zero will occur if it is used */
/*                to solve a system of equations. */

    // ------------------------------------------------------------------------------------

        template <
            typename T,
            long NR1, long NR2,
            long NC1, long NC2,
            typename MM,
            typename layout
            >
        int getrf (
            matrix<T,NR1,NC1,MM,column_major_layout>& a,
            matrix<integer,NR2,NC2,MM,layout>& ipiv
        )
        {
            const long m = a.nr();
            const long n = a.nc();

            ipiv.set_size(std::min(m,n), 1);

            // compute the actual decomposition
            return binding::getrf(m, n, &a(0,0), a.nr(), &ipiv(0,0));
        }

    // ------------------------------------------------------------------------------------

    }

}

// ----------------------------------------------------------------------------------------

#endif // DLIB_LAPACk_GETRF_H__


text:
package endtoend

import (
	"reflect"
	"testing"

	"github.com/youtube/vitess/go/sqltypes"
	querypb "github.com/youtube/vitess/go/vt/proto/query"
	"github.com/youtube/vitess/go/vt/tabletserver/endtoend/framework"
	"github.com/youtube/vitess/go/vt/tabletserver/proto"
)

func TestBatchRead(t *testing.T) {
	client := framework.NewClient()
	queries := []proto.BoundQuery{{
		Sql:           "select * from vitess_a where id = :a",
		BindVariables: map[string]interface{}{"a": 2},
	}, {
		Sql:           "select * from vitess_b where id = :b",
		BindVariables: map[string]interface{}{"b": 2},
	}}
	qr1 := sqltypes.Result{
		Fields: []*querypb.Field{{
			Name: "eid",
			Type: sqltypes.Int64,
		}, {
			Name: "id",
			Type: sqltypes.Int32,
		}, {
			Name: "name",
			Type: sqltypes.VarChar,
		}, {
			Name: "foo",
			Type: sqltypes.VarBinary,
		}},
		RowsAffected: 1,
		Rows: [][]sqltypes.Value{
			[]sqltypes.Value{
				sqltypes.MakeNumeric([]byte("1")),
				sqltypes.MakeNumeric([]byte("2")),
				sqltypes.MakeString([]byte("bcde")),
				sqltypes.MakeString([]byte("fghi")),
			},
		},
	}
	qr2 := sqltypes.Result{
		Fields: []*querypb.Field{{
			Name: "eid",
			Type: sqltypes.Int64,
		}, {
			Name: "id",
			Type: sqltypes.Int32,
		}},
		RowsAffected: 1,
		Rows: [][]sqltypes.Value{
			[]sqltypes.Value{
				sqltypes.MakeNumeric([]byte("1")),
				sqltypes.MakeNumeric([]byte("2")),
			},
		},
	}
	want := &proto.QueryResultList{
		List: []sqltypes.Result{qr1, qr2},
	}

	qrl, err := client.ExecuteBatch(queries, false)
	if err != nil {
		t.Error(err)
		return
	}
	if !reflect.DeepEqual(qrl, want) {
		t.Errorf("ExecueBatch: \n%#v, want \n%#v", qrl, want)
	}
}

func TestBatchTransaction(t *testing.T) {
	client := framework.NewClient()
	queries := []proto.BoundQuery{{
		Sql: "insert into vitess_test values(4, null, null, null)",
	}, {
		Sql: "select * from vitess_test where intval = 4",
	}, {
		Sql: "delete from vitess_test where intval = 4",
	}}

	wantRows := [][]sqltypes.Value{
		[]sqltypes.Value{
			sqltypes.MakeNumeric([]byte("4")),
			sqltypes.Value{},
			sqltypes.Value{},
			sqltypes.Value{},
		},
	}

	// Not in transaction, AsTransaction false
	qrl, err := client.ExecuteBatch(queries, false)
	if err != nil {
		t.Error(err)
		return
	}
	if !reflect.DeepEqual(qrl.List[1].Rows, wantRows) {
		t.Errorf("Rows: \n%#v, want \n%#v", qrl.List[1].Rows, wantRows)
	}

	// Not in transaction, AsTransaction true
	qrl, err = client.ExecuteBatch(queries, true)
	if err != nil {
		t.Error(err)
		return
	}
	if !reflect.DeepEqual(qrl.List[1].Rows, wantRows) {
		t.Errorf("Rows: \n%#v, want \n%#v", qrl.List[1].Rows, wantRows)
	}

	// In transaction, AsTransaction false
	func() {
		err = client.Begin()
		if err != nil {
			t.Error(err)
			return
		}
		defer client.Commit()
		qrl, err = client.ExecuteBatch(queries, false)
		if err != nil {
			t.Error(err)
			return
		}
		if !reflect.DeepEqual(qrl.List[1].Rows, wantRows) {
			t.Errorf("Rows: \n%#v, want \n%#v", qrl.List[1].Rows, wantRows)
		}
	}()

	// In transaction, AsTransaction true
	func() {
		err = client.Begin()
		if err != nil {
			t.Error(err)
			return
		}
		defer client.Rollback()
		qrl, err = client.ExecuteBatch(queries, true)
		want := "error: cannot start a new transaction in the scope of an existing one"
		if err == nil || err.Error() != want {
			t.Errorf("Error: %v, want %s", err, want)
		}
	}()
}


text:
A set of utility data structures that (maybe) could fit in the ``collections`` package of Python's standard library.

Notes: ``collectionz`` is in alpha version and only compatible with Python 3. Support for Python 2 could be added later on ;)

Install by running::

    python3 -m pip install collectionz


text:
<?php
namespace Neat\Test\Http\Message;

use Neat\Http\Message\Uri;

class UriTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Uri
     */
    private $subject;

    /**
     * Set up
     */
    public function setUp()
    {
        $this->subject = new Uri(
            'http://user:password@wwww.test.com:80/path1/path2/path3?query1=value1&query2=value2&query3=value3#fragment');
    }

    /**
     * Test __construct
     */
    public function testConstructorWithMalformedUri()
    {

        $this->subject = new Uri('http:///test.com"');
    }

    /**
     * Test __toString
     */
    public function testStringCasting()
    {
        $this->assertSame(

            (string)$this->subject
        );
    }

    /**
     * Test getScheme
     */
    public function testGetScheme()
    {
        $this->assertSame('http', $this->subject->getScheme());
    }

    /**
     * Test getAuthority
     */
    public function testGetAuthority()
    {
        $this->assertSame('user:password@wwww.test.com', $this->subject->getAuthority());
        $this->assertSame('user:password@wwww.test.com:8080', $this->subject->withPort(8080)->getAuthority());
        $this->assertSame('', $this->subject->withHost('')->getAuthority());
    }

    /**
     * Test getUserInfo
     */
    public function testGetUserInfo()
    {
        $this->assertSame('user:password', $this->subject->getUserInfo());
    }

    /**
     * Test getHost
     */
    public function testGetHost()
    {
        $this->assertSame('wwww.test.com', $this->subject->getHost());
    }

    /**
     * Test getPort
     */
    public function testGetPort()
    {
        $this->assertNull($this->subject->getPort());
    }

    /**
     * Test getPath
     */
    public function testGetPath()
    {
        $this->assertSame('/path1/path2/path3', $this->subject->getPath());
    }

    /**
     * Test getQuery
     */
    public function testGetQuery()
    {
        $this->assertSame('query1=value1&query2=value2&query3=value3', $this->subject->getQuery());
    }

    /**
     * Test getFragment
     */
    public function testGetFragment()
    {
        $this->assertSame('fragment', $this->subject->getFragment());
    }

    /**
     * Test withScheme
     */
    public function testWithScheme()
    {
        $this->assertSame($this->subject, $this->subject->withScheme('http'));
        $this->assertNotSame($this->subject, $this->subject->withScheme('https'));
        $this->assertSame('https', $this->subject->withScheme('https')->getScheme());
    }

    /**
     * Test withScheme
     */
    public function testWithSchemeWithInvalidValue()
    {
        $this->subject->withScheme(array());
    }

    /**
     * Test withScheme
     */
    public function testWithUserInfo()
    {
        $this->assertSame($this->subject, $this->subject->withUserInfo('user', 'password'));
        $this->assertNotSame($this->subject, $this->subject->withUserInfo('new_user', 'new_password'));
        $this->assertSame('new_user:new_password', $this->subject->withUserInfo('new_user', 'new_password')->getUserInfo());
    }

    /**
     * Test withHost
     */
    public function testWithHost()
    {
        $this->assertSame($this->subject, $this->subject->withHost('wwww.test.com'));
        $this->assertNotSame($this->subject, $this->subject->withHost('wwww.test2.com'));
        $this->assertSame('wwww.test2.com', $this->subject->withHost('wwww.test2.com')->getHost());
    }

    /**
     * Test withPort
     */
    public function testWithPort()
    {
        $this->assertSame($this->subject, $this->subject->withPort(80));
        $this->assertNotSame($this->subject, $this->subject->withPort(8080));
        $this->assertSame(8080, $this->subject->withPort(8080)->getPort());
    }

    /**
     * Test withPath
     */
    public function testWithPath()
    {
        $this->assertSame($this->subject, $this->subject->withPath('/path1/path2/path3'));
        $this->assertNotSame($this->subject, $this->subject->withPath('/path'));
        $this->assertSame('/path', $this->subject->withPath('/path')->getPath());
    }

    /**
     * Test withQuery
     */
    public function testWithQuery()
    {
        $this->assertSame($this->subject, $this->subject->withQuery('query1=value1&query2=value2&query3=value3'));
        $this->assertNotSame($this->subject, $this->subject->withQuery(''));
        $this->assertSame('', $this->subject->withQuery('')->getQuery());
    }

    /**
     * Test withFragment
     */
    public function testWithFragment()
    {
        $this->assertSame($this->subject, $this->subject->withFragment('fragment'));
        $this->assertNotSame($this->subject, $this->subject->withFragment('new_fragment'));
        $this->assertSame('new_fragment', $this->subject->withFragment('new_fragment')->getFragment());
    }
}


text:
//
//  Shop.h
//  waterfallLayout
//
//  Created by cxc on 15/6/24.
//  Copyright © 2015年 china. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Shop : NSObject
/**
 *  plist文件字典对应key
 */
@property (nonatomic,copy) NSString *img;
@property (nonatomic,copy) NSString *price;
@property (nonatomic,assign) float w;
@property (nonatomic,assign) float h;

/**
 *  字典转模型
 *
 *  @param dict plist文件
 *
 *  @return shop对象
 */
+ (instancetype)shopWithDict:(NSDictionary *)dict;
/**
 *  根据索引加载店铺数组
 *
 *  @param index 索引
 *
 *  @return 店铺数组
 */
+ (NSArray *)shopsWithIndex:(NSInteger)index;
@end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Gestaocargas extends CI_Controller {

	public $titulo = 'WebSIS';

	public function __construct()
	{
		parent::__construct();
		$this->load->model('geral_model');
		$this->load->model('gestaocargas_model', 'gc_model');
		$this->mes_atual = $this->gc_model->mes_atual();
	}

	public function index()
	{
		redirect('gestaocargas/dados/k9/'.$this->mes_atual);
	}

	public function dados($base = 'k9', $periodo = '')
	{
		/* Declaração de variáveis */
		$tabela = 'gestaocargas_dados_'.$base;
		$numero_dt = array();
		$resultados = array();
		$data['gestao'] = array();
		$data['base_dados'] = $base;
		/* Informações para cabecalho */
		$data['titulo'] = $this->titulo;
		$data['incluir_cabecalho'] = array(
			link_tag('styles/fonts/ubuntu_mono.css'),
			link_tag('styles/gestaocargas.css')
		);
		/* Informações para 'view' */
		$view = 'gestaocargas/painel';
		$data['titulo_pagina'] = 'Gestão de Cargas';
		/* Informações para 'rodape.php' */
		$data['incluir_rodape'] = array(
			$this->load->view('gestaocargas/painel_scripts', $data, true),
			'',
			''
		);
		/* Lógica do controlador */
		/* ->Seleciona os dados conforme o mês especificado no argumento '$periodo' */
		$gestao = $this->db->select()
			->where('MONTH(data_atualizacao)', $periodo)
			->order_by('id', 'ASC')
			->get('gestaocargas')
			->result();
		/* ->Preparação de dados para exibição */
		for ($i = 0; $i < count($gestao); $i++) {
			/* ->Transforma os dados da coluna 'dt' para um formato especifico usando expressão regular */
			array_push($numero_dt, preg_replace('/^000(\d+).+000(\d+)/', '$1', $gestao[$i]->dt));
			/* ->Armazena os resultados da pesquisa de cada DT */
			array_push($resultados, $this->gc_model->pesquisar_registros($tabela, 'dt', $numero_dt[$i]));
			/* ->Falsa função 'JOIN' */
			$gestao_tmp[$i]['id']               = $gestao[$i]->id;
			$gestao_tmp[$i]['data_atualizacao'] = $gestao[$i]->data_atualizacao;
			$gestao_tmp[$i]['status']           = $gestao[$i]->status;
			$gestao_tmp[$i]['dt']               = $gestao[$i]->dt;
			$gestao_tmp[$i]['transportadora']   = $gestao[$i]->transportadora;
			$gestao_tmp[$i]['isca']             = $gestao[$i]->isca;
			$gestao_tmp[$i]['monitoramento']    = $gestao[$i]->monitoramento;
			$gestao_tmp[$i]['escolta_1']        = $gestao[$i]->escolta_1;
			$gestao_tmp[$i]['escolta_2']        = $gestao[$i]->escolta_2;
			$gestao_tmp[$i]['data_checkin']     = $gestao[$i]->data_checkin;
			$gestao_tmp[$i]['data_checkout']    = $gestao[$i]->data_checkout;
			$gestao_tmp[$i]['isca_inserida']    = $gestao[$i]->isca_inserida;
			$gestao_tmp[$i]['numero_dt']        = $numero_dt[$i];
			$gestao_tmp[$i]['resultados']       = count($resultados[$i]);
			/* ->Transforma 'ARRAY' comum em 'ARRAY' de objetos */
			$data['gestao'][$i] = (object) $gestao_tmp[$i];
		}
		/* Conclusão */
		$this->load->view('modelos/cabecalho', $data);
		$this->load->view($view, $data);
		$this->load->view('modelos/rodape', $data);
	}

	public function buscar($base = '')
	{
		$this->input->post('valor') OR exit(show_error('Acesso não permitido.', 403, '403 Forbidden'));
		$numero_dt = $this->input->post('valor');
		$tabela = 'gestaocargas_dados_'.$base;
		$resultados = $this->gc_model->pesquisar_registros($tabela, 'dt', $numero_dt);
		header("Content-Type: text/html; charset=UTF-8");
		for ($i = 0; $i < count($resultados); $i++) {
			echo "

DT	{$resultados[$i]->dt}

STATUS	{$resultados[$i]->status}

PLACAS	{$resultados[$i]->veiculo}/{$resultados[$i]->reboque}

DATA DE CRIAÇÃO	{$this->geral_model->formata_data_hora($resultados[$i]->data_criacao)}

INÍCIO REAL	{$this->geral_model->formata_data_hora($resultados[$i]->inicio_real)}

FIM REAL	{$this->geral_model->formata_data_hora($resultados[$i]->fim_real)}

";
		}
	}
}


text:
function setup()
    location.disable()
    location.enable()
    parameter.action("Open in Google Maps", function() openURL("http://www.google.com/maps/place/"..location.latitude..","..location.longitude) end)
end
function draw()
    background(0, 0, 0, 255)
    fill(255, 255, 255, 255)
    strokeWidth(5)
    font("HelveticaNeue-UltraLight")
    fontSize(64)
    textWrapWidth(WIDTH)
    text("Your latitude: "..location.latitude.."°", WIDTH/2, HEIGHT/4*3)
    text("Your longitude: "..location.longitude.."°", WIDTH/2, HEIGHT/2)
    text("Your altitude: "..location.altitude.." m", WIDTH/2, HEIGHT/4)
end


text:
<?php

/**
 * PluginEavFullValues form.
 *
 * @package    ##PROJECT_NAME##
 * @subpackage form
 * @author     ##AUTHOR_NAME##
 * @version    SVN: $Id: sfDoctrineFormPluginTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
abstract class PluginEavFullValuesForm extends BaseEavFullValuesForm
{
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
All Classes
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

Aula

Entrada

Parametro

Passo

Usuario

Valor


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ca.cumulonimbus.pressurenetsdk
</TITLE>

<META NAME="date" CONTENT="2014-05-22">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package ca.cumulonimbus.pressurenetsdk

Class Summary

BuildConfig

CbAccount

CbAlarm

CbApi
Make PressureNet Live API calls and manage the results locally

CbApiCall
Describe a call to the PressureNet Live API

CbConfiguration
Store configurations for the PressureNet SDK

CbContributions

CbCurrentCondition
A description of the current weather
 at a specific location.

CbDataSender
Securely send collected data to servers.

CbDb
Keep track of app settings, as this SDK may be used by more than one app on a
 device.

CbLocationManager
Implement location strategy for GPS, Network location
 Find the most accurate location within a time limit
 Minimize battery use

CbObservation
Store a single observation Measurement value, measurement accuracy, location,
 location accuracy, time, id, privacy, client key

CbRegisteredApp
Register an application

CbScience
Science methods and classes.

CbScience.ConditionTimeComparator
Compare two current conditions' time vales

CbScience.SensorValueComparator
Compare to observation's sensor values

CbScience.TimeComparator
Compare to observation's time values

CbService
Represent developer-facing pressureNET API Background task; manage and run
 everything Handle Intents

CbSettingsHandler
Use Preferences to hold core PressureNet settings
 Wrap and be compatible with Android Preferences
 Collection and Submission Frequency, Privacy controls

CbStats

CbStatsAPICall

CbWeather
Parent class for all Weather

R

R.attr

R.drawable

R.string

R.style

      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
/* This program takes the previously compiled and linked pieces of the
 * operating system, and puts them together to build a boot diskette.
 * The files are read and put on the boot diskette in this order:
 *
 *      bootblok:       the diskette boot program
 *      kernel:         the operating system kernel
 *      mm:             the memory manager
 *      fs:             the file system
 *      init:           the system initializer
 *      fsck:           the file system checker
 *
 * The bootblok file goes in sector 0 of the boot diskette.  The operating system
 * begins directly after it.  The kernel, mm, fs, init, and fsck are each
 * padded out to a multiple of 16 bytes, and then concatenated into a
 * single file beginning 512 bytes into the file.  The first byte of sector 1
 * contains executable code for the kernel.  There is no header present.
 *
 * After the boot image has been built, build goes back and makes several
 * patches to the image file or diskette:
 *
 *      1. The last 4 words of the boot block are set as follows:
 *	   Word at 504:	Number of sectors to load
 *	   Word at 506:	DS value for running fsck
 *	   Word at 508:	PC value for starting fsck
 *	   Word at 510:	CS value for running fsck
 *
 *	2. Build writes a table into the first 8 words of the kernel's
 *	   data space.  It has 4 entries, the cs and ds values for each
 *	   program.  The kernel needs this information to run mm, fs, and
 *	   init.  Build also writes the kernel's DS value into address 4
 *	   of the kernel's TEXT segment, so the kernel can set itself up.
 *
 *      3. The origin and size of the init program are patched into bytes 4-9
 *         of the file system data space. The file system needs this
 *         information, and expects to find it here.
 *
 * Build is called by:
 *
 *      build bootblok kernel mm fs init fsck image
 *
 * to get the resulting image onto the file "image".
 */

#define PROGRAMS 5              /* kernel + mm + fs + init + fsck = 5 */
#define PROG_ORG 1536           /* where does kernel begin in abs mem */
#define DS_OFFSET 4L            /* position of DS written in kernel text seg */
#define SECTOR_SIZE 512         /* size of buf */
#define READ_UNIT 512           /* how big a chunk to read in */
#define KERNEL_D_MAGIC 0x526F   /* identifies kernel data space */
#define FS_D_MAGIC 0xDADA	/* identifies fs data space */
#define CLICK_SHIFT 4
#define KERN 0
#define MM   1
#define FS   2
#define INIT 3
#define FSCK 4

/* Information about the file header. */
#define HEADER1 32              /* short form header size */
#define HEADER2 48              /* long form header size */
#define SEP_POS 1               /* tells where sep I & D bit is */
#define HDR_LEN 2               /* tells where header length is */
#define TEXT_POS 0              /* where is text size in header */
#define DATA_POS 1              /* where is data size in header */
#define BSS_POS 2               /* where is bss size in header */
#define SEP_ID_BIT 0x20         /* bit that tells if file is separate I & D */

#ifdef MSDOS
# define BREAD 4                /* value 0 means ASCII read */
#else
# define BREAD 0
#endif

int image;                      /* file descriptor used for output file */
int cur_sector;                 /* which 512-byte sector to be written next */
int buf_bytes;                  /* # bytes in buf at present */
char buf[SECTOR_SIZE];          /* buffer for output file */
char zero[SECTOR_SIZE];         /* zeros, for writing bss segment */

long cum_size;                  /* Size of kernel+mm+fs+init */
long all_size;                  /* Size of all 5 programs */

struct sizes {
  unsigned text_size;           /* size in bytes */
  unsigned data_size;           /* size in bytes */
  unsigned bss_size;            /* size in bytes */
  int sep_id;                   /* 1 if separate, 0 if not */
} sizes[PROGRAMS];

char *name[] = {"\nkernel", "mm    ", "fs    ", "init  ", "fsck  "};

main(argc, argv)
int argc;
char *argv[];
{
/* Copy the boot block and the 5 programs to the output. */

  int i;

  if (argc != PROGRAMS+3) pexit("seven file names expected. ", "");

  IOinit();			/* check for DMAoverrun (DOS) */
  create_image(argv[7]);              /* create the output file */

  /* Go get the boot block and copy it to the output file or diskette. */
  copy1(argv[1]);

  /* Copy the 5 programs to the output file or diskette. */
  for (i = 0; i < PROGRAMS; i++) copy2(i, argv[i+2]);
  flush();
  printf("                                               -----     -----\n");
#ifdef PCIX
  printf("Operating system size  %29ld     %5lx\n", cum_size, cum_size);
  printf("\nTotal size including fsck is %ld.\n", all_size);
#else
  printf("Operating system size  %29D     %5X\n", cum_size, cum_size);
  printf("\nTotal size including fsck is %D.\n", all_size);
#endif

  /* Make the three patches to the output file or diskette. */
  patch1(all_size);
  patch2();
  patch3();
  exit(0);
}

copy1(file_name)
char *file_name;
{
/* Copy the specified file to the output.  The file has no header.  All the
 * bytes are copied, until end-of-file is hit.
 */

  int fd, bytes_read;
  char inbuf[READ_UNIT];

  if ( (fd = open(file_name, BREAD)) < 0) pexit("can't open ",file_name);

  do {
        bytes_read = read(fd, inbuf, READ_UNIT);
        if (bytes_read < 0) pexit("read error on file ", file_name);
        if (bytes_read > 0) wr_out(inbuf, bytes_read);
  } while (bytes_read > 0);
  flush();
  close(fd);
}

copy2(num, file_name)
int num;                        /* which program is this (0 - 4) */
char *file_name;                /* file to open */
{
/* Open and read a file, copying it to output.  First read the header,
 * to get the text, data, and bss sizes.  Also see if it is separate I & D.
 * write the text, data, and bss to output.  The sum of these three pieces
 * must be padded upwards to a multiple of 16, if need be.  The individual
 * pieces need not be multiples of 16 bytes, except for the text size when
 * separate I & D is in use.  The total size must be less than 64K, even
 * when separate I & D space is used.
 */

  int fd, sepid, bytes_read, count;
  unsigned text_bytes, data_bytes, bss_bytes, tot_bytes, rest, filler;
  unsigned left_to_read;
  char inbuf[READ_UNIT];

  if ( (fd = open(file_name, BREAD)) < 0) pexit("can't open ", file_name);

  /* Read the header to see how big the segments are. */
  read_header(fd, &sepid, &text_bytes, &data_bytes, &bss_bytes, file_name);

  /* Pad the total size to a 16-byte multiple, if needed. */
  if (sepid && ((text_bytes % 16) != 0) ) {
        pexit("separate I & D but text size not multiple of 16 bytes.  File: ",
                                                                file_name);
  }
  tot_bytes = text_bytes + data_bytes + bss_bytes;
  rest = tot_bytes % 16;
  filler = (rest > 0 ? 16 - rest : 0);
  bss_bytes += filler;
  tot_bytes += filler;
  if (num < FSCK) cum_size += tot_bytes;
  all_size += tot_bytes;

  /* Record the size information in the table. */
  sizes[num].text_size = text_bytes;
  sizes[num].data_size = data_bytes;
  sizes[num].bss_size  = bss_bytes;
  sizes[num].sep_id    = sepid;

  /* Print a message giving the program name and size, except for fsck. */
  if (num < FSCK) {
        printf("%s  text=%5u  data=%5u  bss=%5u  tot=%5u  hex=%4x  %s\n",
                name[num], text_bytes, data_bytes, bss_bytes, tot_bytes,
                tot_bytes, (sizes[num].sep_id ? "Separate I & D" : ""));
  }

  /* Read in the text and data segments, and copy them to output. */
  left_to_read = text_bytes + data_bytes;
  while (left_to_read > 0) {
        count = (left_to_read < READ_UNIT ? left_to_read : READ_UNIT);
        bytes_read = read(fd, inbuf, count);
        if (bytes_read < 0) pexit("read error on file ", file_name);
        if (bytes_read > 0) wr_out(inbuf, bytes_read);
        left_to_read -= count;
  }

  /* Write the bss to output. */
  while (bss_bytes > 0) {
        count = (bss_bytes < SECTOR_SIZE ? bss_bytes : SECTOR_SIZE);
        wr_out(zero, count);
        bss_bytes -= count;
  }
  close(fd);
}

read_header(fd, sepid, text_bytes, data_bytes, bss_bytes, file_name)
int fd, *sepid;
unsigned *text_bytes, *data_bytes, *bss_bytes;
char *file_name;
{
/* Read the header and check the magic number.  The standard Monix header
 * consists of 8 longs, as follows:
 *      0: 0x04100301L (combined I & D space) or 0x04200301L (separate I & D)
 *      1: 0x00000020L (stripped file) or 0x00000030L (unstripped file)
 *      2: size of text segments in bytes
 *      3: size of initialized data segment in bytes
 *      4: size of bss in bytes
 *      5: 0x00000000L
 *      6: total memory allocated to program (text, data and stack, combined)
 *      7: 0x00000000L
 * The longs are represented low-order byte first and high-order byte last.
 * The first byte of the header is always 0x01, followed by 0x03.
 * The header is followed directly by the text and data segments, whose sizes
 * are given in the header.
 */

  long head[12];
  unsigned short hd[4];
  int n, header_len;

  /* Read first 8 bytes of header to get header length. */
  if ((n = read(fd, hd, 8)) != 8) pexit("file header too short: ", file_name);
  header_len = hd[HDR_LEN];
  if (header_len != HEADER1 && header_len != HEADER2)
        pexit("bad header length. File: ", file_name);

  /* Extract separate I & D bit. */
  *sepid = hd[SEP_POS] & SEP_ID_BIT;

  /* Read the rest of the header and extract the sizes. */
  if ((n = read(fd, head, header_len - 8)) != header_len - 8)
        pexit("header too short: ", file_name);

  *text_bytes = (unsigned) head[TEXT_POS];
  *data_bytes = (unsigned) head[DATA_POS];
  *bss_bytes  = (unsigned) head[BSS_POS];
}

wr_out(buffer, bytes)
char buffer[READ_UNIT];
int bytes;
{
/* Write some bytes to the output file.  This procedure must avoid writes
 * that are not entire 512-byte blocks, because when this program runs on
 * MS-DOS, the only way it can write the raw diskette is by using the system
 * calls for raw block I/O.
 */

  int room, count, count1;
  register char *p, *q;

  /* Copy the data to the output buffer. */
  room = SECTOR_SIZE - buf_bytes;
  count = (bytes <= room ? bytes : room);
  count1 = count;
  p = &buf[buf_bytes];
  q = buffer;
  while (count--) *p++ = *q++;

  /* See if the buffer is full. */
  buf_bytes += count1;
  if (buf_bytes == SECTOR_SIZE) {
        /* Write the whole block to the disk. */
        write_block(cur_sector, buf);
        clear_buf();
  }

  /* Is there any more data to copy. */
  if (count1 == bytes) return;
  bytes -= count1;
  buf_bytes = bytes;
  p = buf;
  while (bytes--) *p++ = *q++;
}

flush()
{
  if (buf_bytes == 0) return;
  write_block(cur_sector, buf);
  clear_buf();
}

clear_buf()
{
  register char *p;

  for (p = buf; p < &buf[SECTOR_SIZE]; p++) *p = 0;
  buf_bytes = 0;
  cur_sector++;
}

patch1(all_size)
long all_size;
{
/* Put the ip and cs values for fsck in the last two words of the boot blk.
 * If fsck is sep I&D we must also provide the ds-value (addr. 506).
 * Put in bootblok-offset 504 the number of sectors to load.
 */

  long fsck_org;
  unsigned short ip, cs, ds, ubuf[SECTOR_SIZE/2], sectrs;

  if (cum_size % 16 != 0) pexit("MINIX is not multiple of 16 bytes", "");
  fsck_org = PROG_ORG + cum_size;       /* where does fsck begin */
  ip = 0;
  cs = fsck_org >> CLICK_SHIFT;
  if (sizes[FSCK].sep_id)
     ds = cs + (sizes[FSCK].text_size >> CLICK_SHIFT);
  else
     ds = cs;

  /* calc nr of sectors to load (starting at 0) */
  sectrs = (unsigned) (all_size / 512L);

  read_block(0, ubuf);          /* read in boot block */
  ubuf[(SECTOR_SIZE/2) - 4] = sectrs + 1;
  ubuf[(SECTOR_SIZE/2) - 3] = ds;
  ubuf[(SECTOR_SIZE/2) - 2] = ip;
  ubuf[(SECTOR_SIZE/2) - 1] = cs;
  write_block(0, ubuf);
}

patch2()
{
/* This program now has information about the sizes of the kernel, mm, fs, and
 * init.  This information is patched into the kernel as follows. The first 8
 * words of the kernel data space are reserved for a table filled in by build.
 * The first 2 words are for kernel, then 2 words for mm, then 2 for fs, and
 * finally 2 for init.  The first word of each set is the text size in clicks;
 * the second is the data+bss size in clicks.  If separate I & D is NOT in
 * use, the text size is 0, i.e., the whole thing is data.
 *
 * In addition, the DS value the kernel is to use is computed here, and loaded
 * at location 4 in the kernel's text space.  It must go in text space because
 * when the kernel starts up, only CS is correct.  It does not know DS, so it
 * can't load DS from data space, but it can load DS from text space.
 */

  int i, j;
  unsigned short t, d, b, text_clicks, data_clicks, ds;
  long data_offset;

  /* See if the magic number is where it should be in the kernel. */
  data_offset = 512L + (long)sizes[KERN].text_size;    /* start of kernel data */
  i = (get_byte(data_offset+1L) << 8) + get_byte(data_offset);
  if (i != KERNEL_D_MAGIC)  {
	pexit("kernel data space: no magic #","");
  }

  for (i = 0; i < PROGRAMS - 1; i++) {
        t = sizes[i].text_size;
        d = sizes[i].data_size;
        b = sizes[i].bss_size;
        if (sizes[i].sep_id) {
                text_clicks = t >> CLICK_SHIFT;
                data_clicks = (d + b) >> CLICK_SHIFT;
        } else {
                text_clicks = 0;
                data_clicks = (t + d + b) >> CLICK_SHIFT;
        }
        put_byte(data_offset + 4*i + 0L, (text_clicks>>0) & 0377);
        put_byte(data_offset + 4*i + 1L, (text_clicks>>8) & 0377);
        put_byte(data_offset + 4*i + 2L, (data_clicks>>0) & 0377);
        put_byte(data_offset + 4*i + 3L, (data_clicks>>8) & 0377);
  }

  /* Now write the DS value into word 4 of the kernel text space. */
  if (sizes[KERN].sep_id == 0)
        ds = PROG_ORG >> CLICK_SHIFT;   /* combined I & D space */
  else
        ds = (PROG_ORG + sizes[KERN].text_size) >> CLICK_SHIFT; /* separate */
  put_byte(512L + DS_OFFSET, ds & 0377);
  put_byte(512L + DS_OFFSET + 1L, (ds>>8) & 0377);
}

patch3()
{
/* Write the origin and text and data sizes of the init program in FS's data
 * space.  The file system expects to find these 3 words there.
 */

  unsigned short init_text_size, init_data_size, init_buf[SECTOR_SIZE/2], i;
  unsigned short w0, w1, w2;
  int b0, b1, b2, b3, b4, b5, mag;
  long init_org, fs_org, fbase, mm_data;

  init_org  = PROG_ORG;
  init_org += sizes[KERN].text_size+sizes[KERN].data_size+sizes[KERN].bss_size;
  mm_data = init_org - PROG_ORG +512L;	/* offset of mm in file */
  mm_data += (long) sizes[MM].text_size;
  init_org += sizes[MM].text_size + sizes[MM].data_size + sizes[MM].bss_size;
  fs_org = init_org - PROG_ORG + 512L;   /* offset of fs-text into file */
  fs_org +=  (long) sizes[FS].text_size;
  init_org += sizes[FS].text_size + sizes[FS].data_size + sizes[FS].bss_size;
  init_text_size = sizes[INIT].text_size;
  init_data_size = sizes[INIT].data_size + sizes[INIT].bss_size;
  init_org  = init_org >> CLICK_SHIFT;  /* convert to clicks */
  if (sizes[INIT].sep_id == 0) {
        init_data_size += init_text_size;
        init_text_size = 0;
  }
  init_text_size = init_text_size >> CLICK_SHIFT;
  init_data_size = init_data_size >> CLICK_SHIFT;

  w0 = (unsigned short) init_org;
  w1 = init_text_size;
  w2 = init_data_size;
  b0 =  w0 & 0377;
  b1 = (w0 >> 8) & 0377;
  b2 = w1 & 0377;
  b3 = (w1 >> 8) & 0377;
  b4 = w2 & 0377;
  b5 = (w2 >> 8) & 0377;

  /* Check for appropriate magic numbers. */
  fbase = fs_org;
  mag = (get_byte(mm_data+1L) << 8) + get_byte(mm_data+0L);
  if (mag != FS_D_MAGIC) pexit("mm data space: no magic #","");
  mag = (get_byte(fbase+1L) << 8) + get_byte(fbase+0L);
  if (mag != FS_D_MAGIC) pexit("fs data space: no magic #","");

  put_byte(fbase+4L, b0);
  put_byte(fbase+5L, b1);
  put_byte(fbase+6L, b2);
  put_byte(fbase+7L, b3);
  put_byte(fbase+8L ,b4);
  put_byte(fbase+9L, b5);
}

int get_byte(offset)
long offset;
{
/* Fetch one byte from the output file. */

  char buff[SECTOR_SIZE];

  read_block( (unsigned) (offset / SECTOR_SIZE), buff);
  return(buff[(unsigned) (offset % SECTOR_SIZE)] & 0377);
}

put_byte(offset, byte_value)
long offset;
int byte_value;
{
/* Write one byte into the output file. This is not very efficient, but
 * since it is only called to write a few words it is just simpler.
 */

  char buff[SECTOR_SIZE];

  read_block( (unsigned) (offset/SECTOR_SIZE), buff);
  buff[(unsigned) (offset % SECTOR_SIZE)] = byte_value;
  write_block( (unsigned)(offset/SECTOR_SIZE), buff);
}

pexit(s1, s2)
char *s1, *s2;
{
  printf("Build: %s%s\n", s1, s2);
  exit(1);
}

/*===========================================================================
 * The following code is only used in the UNIX version of this program.
 *===========================================================================*/
#ifndef MSDOS
create_image(f)
char *f;
{
/* Create the output file. */
  image = creat(f, 0666);
  close(image);
  image = open(f, 2);
}

read_block(blk, buff)
int blk;
char buff[SECTOR_SIZE];
{
  lseek(image, (long)SECTOR_SIZE * (long) blk, 0);
  if (read(image, buff, SECTOR_SIZE) != SECTOR_SIZE) pexit("block read error", "");
}

write_block(blk, buff)
int blk;
char buff[SECTOR_SIZE];
{
  lseek(image, (long)SECTOR_SIZE * (long) blk, 0);
  if (write(image, buff, SECTOR_SIZE) != SECTOR_SIZE) pexit("block write error", "");
}

IOinit() {}	/* dummy */

#else /*MSDOS*/
/*===========================================================================
 *   This is the raw diskette I/O for MSDOS. It uses diskio.asm or biosio.asm
 *==========================================================================*/

#define MAX_RETRIES     5

char *buff;
char buff1[SECTOR_SIZE];
char buff2[SECTOR_SIZE];
int drive;

IOinit()			/* check if no DMAoverrun & assign the buffer */
{
  if (DMAoverrun(buff1))
     buff = buff2;
  else
     buff = buff1;
}

read_block (blocknr,user)
int blocknr;
char user[SECTOR_SIZE];
{
  /* read the requested MINIX-block in core */
  int retries,err,i;
  char *p;

  retries = MAX_RETRIES;
  do
      err = absread (drive, blocknr, buff);
  while (err && --retries);

  if (!retries)
    dexit ("reading",drive,blocknr,err);

  p=buff; i=SECTOR_SIZE;
  while (i--) *(user++) = *(p++);
}

write_block (blocknr,user)
int blocknr;
char user[SECTOR_SIZE];
{
  /* write the requested MINIX-block to disk */
  int retries,err,i;
  char *p;

  p=buff; i=SECTOR_SIZE;
  while (i--) *(p++) = *(user++);

  retries = MAX_RETRIES;
  do
      err = abswrite (drive, blocknr, buff);
  while (err && --retries);

  if (!retries)
    dexit ("writing",drive,blocknr,err);
}

dexit (s,drive,sectnum,err)
int sectnum, err,drive;
char *s;
{ extern char *derrtab[];
  printf ("Error %s drive %c, sector: %d, code: %d, %s\n",
           s, drive+'A',sectnum, err, derrtab[err] );
  exit (2);
}

create_image (s)
char *s;
{
  char kbstr[10];
  if (s[1] != ':') pexit ("wrong drive name (dos): ",s);
  drive = (s[0] & ~32) - 'A';
  if (drive<0 || drive>32) pexit ("no such drive: ",s);
  printf("Put a blank, formatted diskette in drive %s\nHit return when ready",s);
  gets (kbstr,10);
  puts("");
}

char *derrtab[14] = {
        "no error",
        "disk is read-only",
        "unknown unit",
        "device not ready",
        "bad command",
        "data error",
        "internal error: bad request structure length",
        "seek error",
        "unknown media type",
        "sector not found",
        "printer out of paper (??)",
        "write fault",
        "read error",
        "general error"
};

#endif /*MSDOS*/


text:
import { MapTo } from '@adobe/aem-react-editable-components';
import DOMPurify from 'dompurify';
import React, { Component } from 'react';
import extractModelId from '../../utils/extract-model-id';

require('./Text.css');

/**
 * Default Edit configuration for the Text component that interact with the Core Text component and sub-types
 *
 * @type EditConfig
 */
const TextEditConfig = {
  emptyLabel: 'Text',

  isEmpty: function(props) {
    return !props || !props.text || props.text.trim().length < 1;
  }
};

/**
 * Text React component
 */
class Text extends Component {
  get richTextContent() {
    return (
      <div
        id={extractModelId(this.props.cqPath)}
        data-rte-editelement
        dangerouslySetInnerHTML={{
          __html: DOMPurify.sanitize(this.props.text)
        }}
      />
    );
  }

  get textContent() {
    return <div>{this.props.text}</div>;
  }

  render() {
    return this.props.richText ? this.richTextContent : this.textContent;
  }
}

export default MapTo('${appId}/components/text')(
  Text,
  TextEditConfig
);


text:
import stringcase

from graph_diff.cpp_algorithms.parameters import SUPPORTED_ALGORITHMS
from graph_diff.graph import GraphWithRepetitiveNodesWithRoot
from graph_diff.graph.graph_printer import GraphPrinter
from graph_diff.graph_diff_algorithm import GraphMap, GraphDiffAlgorithm

def add_run_algorithms(cls: type):
    """
    Adds supported algorithms-classes to class-container.

    :param cls: class-container to modify
    :return:    modified class
    """
    from graph_diff.cpp_algorithms.algorithm_runner import AlgorithmRunner
    runner = AlgorithmRunner()
    for algo in SUPPORTED_ALGORITHMS:
        class CppAlgorithm(GraphDiffAlgorithm):
            def construct_diff(self,
                               graph1: GraphWithRepetitiveNodesWithRoot,
                               graph2: GraphWithRepetitiveNodesWithRoot) -> GraphMap:
                __name__ = type(self).__name__
                return runner.construct_diff(__name__,
                                             graph1,
                                             graph2)

        CppAlgorithm.__name__ = algo
        CppAlgorithm.__doc__ = """Realization of algorithm {} on cpp""".format(algo)

        setattr(cls, algo, CppAlgorithm)
    return cls

def add_imported_algorithms(cls: type):
    """
    Adds supported algorithms-classes to class-container.

    :param cls: class-container to modify
    :return:    modified class
    """
    from graph_diff.cpp_algorithms.algorithm_importer import AlgorithmImporter
    algorithm_importer = AlgorithmImporter()
    for algo in SUPPORTED_ALGORITHMS:
        class CppAlgorithm(GraphDiffAlgorithm):
            def construct_diff(self,
                               graph1: GraphWithRepetitiveNodesWithRoot,
                               graph2: GraphWithRepetitiveNodesWithRoot) -> GraphMap:
                graph_printer = GraphPrinter(graph1, graph2)
                repr_first = graph_printer.graph_transformer_first()
                repr_second = graph_printer.graph_transformer_second()

                __name__ = type(self).__name__
                output = getattr(algorithm_importer.module, stringcase.snakecase(__name__)) \
                    (*repr_first, *repr_second)
                return graph_printer.back_transformer(output)

        CppAlgorithm.__name__ = algo
        CppAlgorithm.__doc__ = """Realization of algorithm {} on cpp""".format(algo)

        setattr(cls, algo, CppAlgorithm)
    return cls

def clone_method(method_name: str, *args):
    """
    Clones given method by given args and creates series of methods.
    Let x be one of the args. For every x in args
    this method adds method which has logic to run original method with x as argument
    and which name is f'{method_name}_{x}'.

    :param method_name:     name of the method with exactly one argument
    :param args:            arguments for the method
    :return:                decorator function that will modify a class given
    """

    def wrapped_decorator(cls: type):
        for clone_id in args:
            snake_case_clone_id = stringcase.snakecase(clone_id)
            new_method_name = '{}_{}'.format(method_name, snake_case_clone_id)

            def new_method(self):
                method = getattr(self, method_name)
                return method(clone_id)

            new_method.__doc__ = """
            Generated by clone_method decorator method {} of class {cls}.
            Please refer to {cls}.{method_name} documentation.
            """.format(new_method_name, method_name=method_name, cls=cls.__name__)
            new_method.__name__ = new_method_name
            setattr(cls, new_method_name, new_method)
        return cls

    return wrapped_decorator


text:
FactoryGirl.define do
  factory :post do
    price 30
    title "Intro to Stats"
    condition "Good"
    university_id 1
    course_id 1
    seller_id 1
  end
end


text:
(function () {
  'use strict';

  angular.module('pnc.common.authentication').provider('authConfig',
    function () {
      var ssoTokenLifespan = 86400000; // Default: 24 Hours

      function getSsoTokenLifespan() {
        return ssoTokenLifespan;
      }

      function setSsoTokenLifespan(timeInMilis) {
        if (!angular.isNumber(timeInMilis)) {
          console.warn('Invalid value for configuration item ssoTokenLifespan: %s, using default of %d', timeInMilis, ssoTokenLifespan);
          return;
        }
        ssoTokenLifespan = timeInMilis;
      }

      return {
        setSsoTokenLifespan: setSsoTokenLifespan,
        getSsoTokenLifespan: getSsoTokenLifespan,
        $get: function () {
          return {
            getSsoTokenLifespan: getSsoTokenLifespan
          };
        }
      };

    }
  );

})();


text:
{% extends "base.html" %}

{% block title %}Editar {{ client.name }}{% endblock title %}

{% block content-header-title %}
Editar
{% endblock content-header-title %}

{% block content-header-subtitle %}
Editar cliente
{% endblock content-header-subtitle %}

{% block content-header-breadcrumb %}

Clientes

Editar

{% endblock content-header-breadcrumb %}

{% block content %}

Editando: {{ client.name }}

				Remover

			<form  method="POST" enctype="multipart/form-data" role="form">

						{% csrf_token %}
		  	    {{ form.non_field_errors}}

				    {% for field in form %}

						    {{ field.label_tag }}
						    {{ field }}
						    {{ field.errors }}

				    {% endfor %}

			    <button type="submit" class="btn btn-primary">
			    	 Salvar
			    </button>

						 Cancelar

			</form>

{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Microsoft.Azure.Test;
using Xunit;

namespace Sql2.Tests.ScenarioTests
{
    /// <summary>
    /// Contains tests for Server, Elastic Pool and Database Advisors
    /// </summary>
    public class Sql2AdvisorScenarioTests : TestBase
    {
        private const string ResourceGroupName = "WIRunnersProd";
        private const string ServerName = "wi-runner-australia-east";
        private const string DatabaseName = "WIRunner";
        private const string ElasticPoolName = "WIRunnerPool";
        private const string AdvisorName = "CreateIndex";
        private const string ExpandKey = "recommendedActions";

        private const string ServerAdvisorType = "Microsoft.Sql/servers/advisors";
        private const string DatabaseAdvisorType = "Microsoft.Sql/servers/databases/advisors";
        private const string ElasticPoolAdvisorType = "Microsoft.Sql/servers/elasticPools/advisors";

        /// <summary>
        /// Test for list server advisors request
        /// </summary>
        [Fact]
        public void ListAdvisorsForServer()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                var response = sqlClient.ServerAdvisors.List(ResourceGroupName, ServerName, expand: null);

                ValidateAdvisorList(response.Advisors, ServerAdvisorType);
            }
        }

        /// <summary>
        /// Test for list server advisors request expanded for recommended actions
        /// </summary>
        [Fact]
        public void ListAdvisorsForServerExpandedWithRecommendedActions()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                var response = sqlClient.ServerAdvisors.List(ResourceGroupName, ServerName, expand: ExpandKey);

                ValidateAdvisorList(response.Advisors, ServerAdvisorType);
                ValidatePresenceOfRecommendedActions(response);
            }
        }

        /// <summary>
        /// Test for get server advisor request
        /// </summary>
        [Fact]
        public void GetSingleAdvisorForServer()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                var response = sqlClient.ServerAdvisors.Get(ResourceGroupName, ServerName, AdvisorName, expand: null);

                ValidateSingleAdvisor(response.Advisor, ServerAdvisorType);
            }
        }

        /// <summary>
        /// Test for update status of server advisor request
        /// </summary>
        [Fact]
        public void UpdateStatusOfServerAdvisor()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                AdvisorUpdateParameters updateParameters = new AdvisorUpdateParameters()
                {
                    Properties = new AdvisorUpdateProperties()
                    {
                        AutoExecuteStatus = "Disabled"
                    }
                };

                var response = sqlClient.ServerAdvisors.Update(ResourceGroupName, ServerName, AdvisorName, updateParameters);
                ValidateSingleAdvisor(response.Advisor, ServerAdvisorType, expectedAutoExecuteStatus: "Disabled");
            }
        }

        /// <summary>
        /// Test for list database advisors request
        /// </summary>
        [Fact]
        public void ListAdvisorsForDatabase()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                var response = sqlClient.DatabaseAdvisors.List(ResourceGroupName, ServerName, DatabaseName, expand: null);

                ValidateAdvisorList(response.Advisors, DatabaseAdvisorType);
            }
        }

        /// <summary>
        /// Test for list database advisors request expanded for recommended actions
        /// </summary>
        [Fact]
        public void ListAdvisorsForDatabaseExpandedWithRecommendedActions()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                var response = sqlClient.DatabaseAdvisors.List(ResourceGroupName, ServerName, DatabaseName, expand: ExpandKey);

                ValidateAdvisorList(response.Advisors, DatabaseAdvisorType);
                ValidatePresenceOfRecommendedActions(response);
            }
        }

        /// <summary>
        /// Test for get database advisor request
        /// </summary>
        [Fact]
        public void GetSingleAdvisorForDatabase()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                var response = sqlClient.DatabaseAdvisors.Get(ResourceGroupName, ServerName, DatabaseName, AdvisorName, expand: null);

                ValidateSingleAdvisor(response.Advisor, DatabaseAdvisorType);
            }
        }

        /// <summary>
        /// Test for update status of database advisor request
        /// </summary>
        [Fact]
        public void UpdateStatusOfDatabaseAdvisor()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                AdvisorUpdateParameters updateParameters = new AdvisorUpdateParameters()
                {
                    Properties = new AdvisorUpdateProperties()
                    {
                        AutoExecuteStatus = "Disabled"
                    }
                };

                var response = sqlClient.DatabaseAdvisors.Update(ResourceGroupName, ServerName, DatabaseName, AdvisorName, updateParameters);
                ValidateSingleAdvisor(response.Advisor, DatabaseAdvisorType, expectedAutoExecuteStatus: "Disabled");
            }
        }

        /// <summary>
        /// Test for list elastic pool advisors request
        /// </summary>
        [Fact]
        public void ListAdvisorsForElasticPool()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                var response = sqlClient.ElasticPoolAdvisors.List(ResourceGroupName, ServerName, ElasticPoolName, expand: null);

                ValidateAdvisorList(response.Advisors, ElasticPoolAdvisorType);
            }
        }

        /// <summary>
        /// Test for list elastic pool advisors request expanded for recommended actions
        /// </summary>
        [Fact]
        public void ListAdvisorsForElasticPoolExpandedWithRecommendedActions()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                var response = sqlClient.ElasticPoolAdvisors.List(ResourceGroupName, ServerName, ElasticPoolName, expand: ExpandKey);

                ValidateAdvisorList(response.Advisors, ElasticPoolAdvisorType);
                ValidatePresenceOfRecommendedActions(response);
            }
        }

        /// <summary>
        /// Test for get elastic pool advisor request
        /// </summary>
        [Fact]
        public void GetSingleAdvisorForElasticPool()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                var response = sqlClient.ElasticPoolAdvisors.Get(ResourceGroupName, ServerName, ElasticPoolName, AdvisorName, expand: null);

                ValidateSingleAdvisor(response.Advisor, ElasticPoolAdvisorType);
            }
        }

        /// <summary>
        /// Test for update status of elastic pool advisor request
        /// </summary>
        [Fact]
        public void UpdateStatusOfElasticPoolAdvisor()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var handler = new BasicDelegatingHandler();
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                AdvisorUpdateParameters updateParameters = new AdvisorUpdateParameters()
                {
                    Properties = new AdvisorUpdateProperties()
                    {
                        AutoExecuteStatus = "Disabled"
                    }
                };

                var response = sqlClient.ElasticPoolAdvisors.Update(ResourceGroupName, ServerName, ElasticPoolName, AdvisorName, updateParameters);
                ValidateSingleAdvisor(response.Advisor, ElasticPoolAdvisorType, expectedAutoExecuteStatus: "Disabled");
            }
        }

        /// <summary>
        /// Validates list of advisors
        /// </summary>
        private static void ValidateAdvisorList(IList<Advisor> responseList, string expectedResponseType)
        {
            Assert.NotNull(responseList);
            IList<Advisor> expectedList = CreateAdvisorListForValidation();

            Assert.Equal(expectedList.Count, responseList.Count);
            foreach (var response in responseList)
            {
                ValidateSingleAdvisor(response, expectedResponseType);
            }
        }

        /// <summary>
        /// Validates single advisor object
        /// </summary>
        private static void ValidateSingleAdvisor(Advisor response, string expectedAdvisorType, string expectedAutoExecuteStatus = null)
        {
            Assert.NotNull(response);

            Advisor expected = CreateAdvisorListForValidation().SingleOrDefault(a => a.Name.Equals(response.Name));
            Assert.NotNull(expected);

            Assert.Equal(expectedAdvisorType, response.Type);
            CompareAdvisorProperties(expected, response, expectedAutoExecuteStatus);
        }

        /// <summary>
        /// Validates presence of recommended actions inside advisor objects, when expand call was made.
        /// </summary>
        private static void ValidatePresenceOfRecommendedActions(AdvisorListResponse response)
        {
            Assert.Equal(10, response.Advisors.Single(a => a.Name.Equals("CreateIndex")).Properties.RecommendedActions.Count);
            Assert.Equal(10, response.Advisors.Single(a => a.Name.Equals("DropIndex")).Properties.RecommendedActions.Count);
            Assert.Equal(0, response.Advisors.Single(a => a.Name.Equals("DbParameterization")).Properties.RecommendedActions.Count);
            Assert.Equal(0, response.Advisors.Single(a => a.Name.Equals("SchemaIssue")).Properties.RecommendedActions.Count);
        }

        private static void CompareAdvisorProperties(Advisor expected, Advisor response, string expectedAutoExecuteStatus = null)
        {
            Assert.Equal(expected.Properties.AdvisorStatus, response.Properties.AdvisorStatus);
            Assert.Equal(expectedAutoExecuteStatus ?? expected.Properties.AutoExecuteStatus, response.Properties.AutoExecuteStatus);
            Assert.Equal(expected.Properties.AutoExecuteStatusInheritedFrom, response.Properties.AutoExecuteStatusInheritedFrom);
            Assert.Equal(expected.Properties.RecommendationsStatus, response.Properties.RecommendationsStatus);
            Assert.Equal(expected.Properties.LastChecked, response.Properties.LastChecked);
        }

        /// <summary>
        /// Creates a list of Advisor objects for validating responses.
        /// </summary>
        private static List<Advisor> CreateAdvisorListForValidation()
        {
            return new List<Advisor>()
            {
                new Advisor()
                {
                    Name = "CreateIndex",
                    Properties = new AdvisorProperties()
                    {
                        AdvisorStatus = "GA",
                        AutoExecuteStatus = "Disabled",
                        AutoExecuteStatusInheritedFrom = "Database",
                        RecommendationsStatus = "Ok",
                        LastChecked = DateTime.Parse("2016-06-23T03:57:09Z").ToUniversalTime()
                    }
                },
                new Advisor()
                {
                    Name = "DropIndex",
                    Properties = new AdvisorProperties()
                    {
                        AdvisorStatus = "PublicPreview",
                        AutoExecuteStatus = "Disabled",
                        AutoExecuteStatusInheritedFrom = "Database",
                        RecommendationsStatus = "Ok",
                        LastChecked = DateTime.Parse("2016-06-22T18:34:42Z").ToUniversalTime()
                    }
                },
                new Advisor()
                {
                    Name = "DbParameterization",
                    Properties = new AdvisorProperties()
                    {
                        AdvisorStatus = "PublicPreview",
                        AutoExecuteStatus = "Disabled",
                        AutoExecuteStatusInheritedFrom = "Subscription",
                        RecommendationsStatus = "NoDbParameterizationIssue",
                        LastChecked = DateTime.Parse("2016-06-21T22:04:57Z").ToUniversalTime()
                    }
                },
                new Advisor()
                {
                    Name = "SchemaIssue",
                    Properties = new AdvisorProperties()
                    {
                        AdvisorStatus = "PublicPreview",
                        AutoExecuteStatus = "Disabled",
                        AutoExecuteStatusInheritedFrom = "Subscription",
                        RecommendationsStatus = "SchemaIsConsistent",
                        LastChecked = DateTime.Parse("2016-06-23T10:20:59Z").ToUniversalTime()
                    }
                },
            };
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_subtitledelay_normal" android:state_focused="true" android:state_pressed="true"/>
    <item android:drawable="@drawable/ic_subtitledelay_pressed" android:state_focused="true"/>
    <item android:drawable="@drawable/ic_subtitledelay_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/ic_subtitledelay_normal"/>
</selector>


text:
<?php
// Copyright 2004-present Facebook. All Rights Reserved.
//
// 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.

namespace Facebook\WebDriver\Support\Events;

use Facebook\WebDriver\Exception\WebDriverException;
use Facebook\WebDriver\WebDriverDispatcher;
use Facebook\WebDriver\WebDriverNavigation;

class EventFiringWebDriverNavigation
{
    /**
     * @var WebDriverNavigation
     */
    protected $navigator;
    /**
     * @var WebDriverDispatcher
     */
    protected $dispatcher;

    /**
     * @param WebDriverNavigation $navigator
     * @param WebDriverDispatcher $dispatcher
     */
    public function __construct(WebDriverNavigation $navigator, WebDriverDispatcher $dispatcher)
    {
        $this->navigator = $navigator;
        $this->dispatcher = $dispatcher;

        return $this;
    }

    /**
     * @return WebDriverDispatcher
     */
    public function getDispatcher()
    {
        return $this->dispatcher;
    }

    /**
     * @param mixed $method
     */
    protected function dispatch($method)
    {
        if (!$this->dispatcher) {
            return;
        }

        $arguments = func_get_args();
        unset($arguments[0]);
        $this->dispatcher->dispatch($method, $arguments);
    }

    /**
     * @return WebDriverNavigation
     */
    public function getNavigator()
    {
        return $this->navigator;
    }

    /**
     * @throws WebDriverException
     * @return $this
     */
    public function back()
    {
        $this->dispatch(
            'beforeNavigateBack',
            $this->getDispatcher()->getDefaultDriver()
        );
        try {
            $this->navigator->back();
        } catch (WebDriverException $exception) {
            $this->dispatchOnException($exception);
        }
        $this->dispatch(
            'afterNavigateBack',
            $this->getDispatcher()->getDefaultDriver()
        );

        return $this;
    }

    /**
     * @throws WebDriverException
     * @return $this
     */
    public function forward()
    {
        $this->dispatch(
            'beforeNavigateForward',
            $this->getDispatcher()->getDefaultDriver()
        );
        try {
            $this->navigator->forward();
        } catch (WebDriverException $exception) {
            $this->dispatchOnException($exception);
        }
        $this->dispatch(
            'afterNavigateForward',
            $this->getDispatcher()->getDefaultDriver()
        );

        return $this;
    }

    /**
     * @throws WebDriverException
     * @return $this
     */
    public function refresh()
    {
        try {
            $this->navigator->refresh();

            return $this;
        } catch (WebDriverException $exception) {
            $this->dispatchOnException($exception);
        }
    }

    /**
     * @param mixed $url
     * @throws WebDriverException
     * @return $this
     */
    public function to($url)
    {
        $this->dispatch(
            'beforeNavigateTo',
            $url,
            $this->getDispatcher()->getDefaultDriver()
        );
        try {
            $this->navigator->to($url);
        } catch (WebDriverException $exception) {
            $this->dispatchOnException($exception);
        }
        $this->dispatch(
            'afterNavigateTo',
            $url,
            $this->getDispatcher()->getDefaultDriver()
        );

        return $this;
    }

    private function dispatchOnException($exception)
    {
        $this->dispatch('onException', $exception);
        throw $exception;
    }
}


text:
layout: year
title: Limpopo Provincial Gazettes 2006
jurisdiction: ZA-LP
jurisdiction_name: Limpopo
provincial: true
year: "2006"
---


text:
package global.namespace.neuron.di.java.sample;

import global.namespace.neuron.di.java.Caching;
import global.namespace.neuron.di.java.Incubator;
import global.namespace.neuron.di.java.Neuron;

@Neuron
public interface GreetingModule {

    @Caching
    default Greeting greeting() { return Incubator.wire(RealGreeting.class).using(this); }

    default Formatter formatter() { return Incubator.wire(RealFormatter.class).using(this); }

    default String getFormat() { return "Hello %s!"; }
}


text:
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
  public static void test(List<String> strings) {
    final Map<Boolean, Map<Character, Set<String>>> nestedMap =
      strings.stream().c<caret>ollect(Collectors.partitioningBy((String s) -> s.length() > 2, Collectors.groupingBy(s -> s.charAt(0), Collectors.toSet())));
    System.out.println(nestedMap);
  }

  public static void main(String[] args) {
    test(Arrays.asList("a", "bbb", "cccc", "dddd"));
  }
}


text:
package com.kzmen.sczxjf.bean;

/**
 * 说明:
 * note:
 * Created by FuPei
 * on 2015/12/1 at 15:41
 */
public class EarnBean {
    public double money;
    public String datetime;
    public String title;

    @Override
    public String toString() {
        return "title = " + title + ", datetime = " + datetime + ", money = " + money;
    }
}